3c3510744dab285d0c3f20acfd528a51906f634c
[linux-2.6-microblaze.git] / tools / perf / util / metricgroup.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2017, Intel Corporation.
4  */
5
6 /* Manage metrics and groups of metrics from JSON files */
7
8 #include "metricgroup.h"
9 #include "debug.h"
10 #include "evlist.h"
11 #include "evsel.h"
12 #include "strbuf.h"
13 #include "pmu.h"
14 #include "pmu-hybrid.h"
15 #include "expr.h"
16 #include "rblist.h"
17 #include <string.h>
18 #include <errno.h>
19 #include "strlist.h"
20 #include <assert.h>
21 #include <linux/ctype.h>
22 #include <linux/list_sort.h>
23 #include <linux/string.h>
24 #include <linux/zalloc.h>
25 #include <subcmd/parse-options.h>
26 #include <api/fs/fs.h>
27 #include "util.h"
28 #include <asm/bug.h>
29 #include "cgroup.h"
30
31 struct metric_event *metricgroup__lookup(struct rblist *metric_events,
32                                          struct evsel *evsel,
33                                          bool create)
34 {
35         struct rb_node *nd;
36         struct metric_event me = {
37                 .evsel = evsel
38         };
39
40         if (!metric_events)
41                 return NULL;
42
43         nd = rblist__find(metric_events, &me);
44         if (nd)
45                 return container_of(nd, struct metric_event, nd);
46         if (create) {
47                 rblist__add_node(metric_events, &me);
48                 nd = rblist__find(metric_events, &me);
49                 if (nd)
50                         return container_of(nd, struct metric_event, nd);
51         }
52         return NULL;
53 }
54
55 static int metric_event_cmp(struct rb_node *rb_node, const void *entry)
56 {
57         struct metric_event *a = container_of(rb_node,
58                                               struct metric_event,
59                                               nd);
60         const struct metric_event *b = entry;
61
62         if (a->evsel == b->evsel)
63                 return 0;
64         if ((char *)a->evsel < (char *)b->evsel)
65                 return -1;
66         return +1;
67 }
68
69 static struct rb_node *metric_event_new(struct rblist *rblist __maybe_unused,
70                                         const void *entry)
71 {
72         struct metric_event *me = malloc(sizeof(struct metric_event));
73
74         if (!me)
75                 return NULL;
76         memcpy(me, entry, sizeof(struct metric_event));
77         me->evsel = ((struct metric_event *)entry)->evsel;
78         INIT_LIST_HEAD(&me->head);
79         return &me->nd;
80 }
81
82 static void metric_event_delete(struct rblist *rblist __maybe_unused,
83                                 struct rb_node *rb_node)
84 {
85         struct metric_event *me = container_of(rb_node, struct metric_event, nd);
86         struct metric_expr *expr, *tmp;
87
88         list_for_each_entry_safe(expr, tmp, &me->head, nd) {
89                 free((char *)expr->metric_name);
90                 free(expr->metric_refs);
91                 free(expr->metric_events);
92                 free(expr);
93         }
94
95         free(me);
96 }
97
98 static void metricgroup__rblist_init(struct rblist *metric_events)
99 {
100         rblist__init(metric_events);
101         metric_events->node_cmp = metric_event_cmp;
102         metric_events->node_new = metric_event_new;
103         metric_events->node_delete = metric_event_delete;
104 }
105
106 void metricgroup__rblist_exit(struct rblist *metric_events)
107 {
108         rblist__exit(metric_events);
109 }
110
111 /*
112  * A node in the list of referenced metrics. metric_expr
113  * is held as a convenience to avoid a search through the
114  * metric list.
115  */
116 struct metric_ref_node {
117         const char *metric_name;
118         const char *metric_expr;
119         struct list_head list;
120 };
121
122 /**
123  * The metric under construction. The data held here will be placed in a
124  * metric_expr.
125  */
126 struct metric {
127         struct list_head nd;
128         /**
129          * The expression parse context importantly holding the IDs contained
130          * within the expression.
131          */
132         struct expr_parse_ctx *pctx;
133         /** The name of the metric such as "IPC". */
134         const char *metric_name;
135         /** Modifier on the metric such as "u" or NULL for none. */
136         const char *modifier;
137         /** The expression to parse, for example, "instructions/cycles". */
138         const char *metric_expr;
139         /**
140          * The "ScaleUnit" that scales and adds a unit to the metric during
141          * output.
142          */
143         const char *metric_unit;
144         /** Optional null terminated array of referenced metrics. */
145         struct metric_ref *metric_refs;
146         /**
147          * Is there a constraint on the group of events? In which case the
148          * events won't be grouped.
149          */
150         bool has_constraint;
151         /**
152          * Parsed events for the metric. Optional as events may be taken from a
153          * different metric whose group contains all the IDs necessary for this
154          * one.
155          */
156         struct evlist *evlist;
157 };
158
159 static void metricgroup___watchdog_constraint_hint(const char *name, bool foot)
160 {
161         static bool violate_nmi_constraint;
162
163         if (!foot) {
164                 pr_warning("Splitting metric group %s into standalone metrics.\n", name);
165                 violate_nmi_constraint = true;
166                 return;
167         }
168
169         if (!violate_nmi_constraint)
170                 return;
171
172         pr_warning("Try disabling the NMI watchdog to comply NO_NMI_WATCHDOG metric constraint:\n"
173                    "    echo 0 > /proc/sys/kernel/nmi_watchdog\n"
174                    "    perf stat ...\n"
175                    "    echo 1 > /proc/sys/kernel/nmi_watchdog\n");
176 }
177
178 static bool metricgroup__has_constraint(const struct pmu_event *pe)
179 {
180         if (!pe->metric_constraint)
181                 return false;
182
183         if (!strcmp(pe->metric_constraint, "NO_NMI_WATCHDOG") &&
184             sysctl__nmi_watchdog_enabled()) {
185                 metricgroup___watchdog_constraint_hint(pe->metric_name, false);
186                 return true;
187         }
188
189         return false;
190 }
191
192 static struct metric *metric__new(const struct pmu_event *pe,
193                                   const char *modifier,
194                                   bool metric_no_group,
195                                   int runtime)
196 {
197         struct metric *m;
198
199         m = zalloc(sizeof(*m));
200         if (!m)
201                 return NULL;
202
203         m->pctx = expr__ctx_new();
204         if (!m->pctx) {
205                 free(m);
206                 return NULL;
207         }
208
209         m->metric_name = pe->metric_name;
210         m->modifier = modifier ? strdup(modifier) : NULL;
211         if (modifier && !m->modifier) {
212                 expr__ctx_free(m->pctx);
213                 free(m);
214                 return NULL;
215         }
216         m->metric_expr = pe->metric_expr;
217         m->metric_unit = pe->unit;
218         m->pctx->runtime = runtime;
219         m->has_constraint = metric_no_group || metricgroup__has_constraint(pe);
220         m->metric_refs = NULL;
221         m->evlist = NULL;
222
223         return m;
224 }
225
226 static void metric__free(struct metric *m)
227 {
228         free(m->metric_refs);
229         expr__ctx_free(m->pctx);
230         free((char *)m->modifier);
231         evlist__delete(m->evlist);
232         free(m);
233 }
234
235 static bool contains_metric_id(struct evsel **metric_events, int num_events,
236                                const char *metric_id)
237 {
238         int i;
239
240         for (i = 0; i < num_events; i++) {
241                 if (!strcmp(evsel__metric_id(metric_events[i]), metric_id))
242                         return true;
243         }
244         return false;
245 }
246
247 /**
248  * setup_metric_events - Find a group of events in metric_evlist that correspond
249  *                       to the IDs from a parsed metric expression.
250  * @ids: the metric IDs to match.
251  * @metric_evlist: the list of perf events.
252  * @out_metric_events: holds the created metric events array.
253  */
254 static int setup_metric_events(struct hashmap *ids,
255                                struct evlist *metric_evlist,
256                                struct evsel ***out_metric_events)
257 {
258         struct evsel **metric_events;
259         const char *metric_id;
260         struct evsel *ev;
261         size_t ids_size, matched_events, i;
262
263         *out_metric_events = NULL;
264         ids_size = hashmap__size(ids);
265
266         metric_events = calloc(sizeof(void *), ids_size + 1);
267         if (!metric_events)
268                 return -ENOMEM;
269
270         matched_events = 0;
271         evlist__for_each_entry(metric_evlist, ev) {
272                 struct expr_id_data *val_ptr;
273
274                 /*
275                  * Check for duplicate events with the same name. For
276                  * example, uncore_imc/cas_count_read/ will turn into 6
277                  * events per socket on skylakex. Only the first such
278                  * event is placed in metric_events.
279                  */
280                 metric_id = evsel__metric_id(ev);
281                 if (contains_metric_id(metric_events, matched_events, metric_id))
282                         continue;
283                 /*
284                  * Does this event belong to the parse context? For
285                  * combined or shared groups, this metric may not care
286                  * about this event.
287                  */
288                 if (hashmap__find(ids, metric_id, (void **)&val_ptr)) {
289                         metric_events[matched_events++] = ev;
290
291                         if (matched_events >= ids_size)
292                                 break;
293                 }
294         }
295         if (matched_events < ids_size) {
296                 free(metric_events);
297                 return -EINVAL;
298         }
299         for (i = 0; i < ids_size; i++) {
300                 ev = metric_events[i];
301                 ev->collect_stat = true;
302
303                 /*
304                  * The metric leader points to the identically named
305                  * event in metric_events.
306                  */
307                 ev->metric_leader = ev;
308                 /*
309                  * Mark two events with identical names in the same
310                  * group (or globally) as being in use as uncore events
311                  * may be duplicated for each pmu. Set the metric leader
312                  * of such events to be the event that appears in
313                  * metric_events.
314                  */
315                 metric_id = evsel__metric_id(ev);
316                 evlist__for_each_entry_continue(metric_evlist, ev) {
317                         if (!strcmp(evsel__metric_id(ev), metric_id))
318                                 ev->metric_leader = metric_events[i];
319                 }
320         }
321         *out_metric_events = metric_events;
322         return 0;
323 }
324
325 static bool match_metric(const char *n, const char *list)
326 {
327         int len;
328         char *m;
329
330         if (!list)
331                 return false;
332         if (!strcmp(list, "all"))
333                 return true;
334         if (!n)
335                 return !strcasecmp(list, "No_group");
336         len = strlen(list);
337         m = strcasestr(n, list);
338         if (!m)
339                 return false;
340         if ((m == n || m[-1] == ';' || m[-1] == ' ') &&
341             (m[len] == 0 || m[len] == ';'))
342                 return true;
343         return false;
344 }
345
346 static bool match_pe_metric(const struct pmu_event *pe, const char *metric)
347 {
348         return match_metric(pe->metric_group, metric) ||
349                match_metric(pe->metric_name, metric);
350 }
351
352 struct mep {
353         struct rb_node nd;
354         const char *name;
355         struct strlist *metrics;
356 };
357
358 static int mep_cmp(struct rb_node *rb_node, const void *entry)
359 {
360         struct mep *a = container_of(rb_node, struct mep, nd);
361         struct mep *b = (struct mep *)entry;
362
363         return strcmp(a->name, b->name);
364 }
365
366 static struct rb_node *mep_new(struct rblist *rl __maybe_unused,
367                                         const void *entry)
368 {
369         struct mep *me = malloc(sizeof(struct mep));
370
371         if (!me)
372                 return NULL;
373         memcpy(me, entry, sizeof(struct mep));
374         me->name = strdup(me->name);
375         if (!me->name)
376                 goto out_me;
377         me->metrics = strlist__new(NULL, NULL);
378         if (!me->metrics)
379                 goto out_name;
380         return &me->nd;
381 out_name:
382         zfree(&me->name);
383 out_me:
384         free(me);
385         return NULL;
386 }
387
388 static struct mep *mep_lookup(struct rblist *groups, const char *name)
389 {
390         struct rb_node *nd;
391         struct mep me = {
392                 .name = name
393         };
394         nd = rblist__find(groups, &me);
395         if (nd)
396                 return container_of(nd, struct mep, nd);
397         rblist__add_node(groups, &me);
398         nd = rblist__find(groups, &me);
399         if (nd)
400                 return container_of(nd, struct mep, nd);
401         return NULL;
402 }
403
404 static void mep_delete(struct rblist *rl __maybe_unused,
405                        struct rb_node *nd)
406 {
407         struct mep *me = container_of(nd, struct mep, nd);
408
409         strlist__delete(me->metrics);
410         zfree(&me->name);
411         free(me);
412 }
413
414 static void metricgroup__print_strlist(struct strlist *metrics, bool raw)
415 {
416         struct str_node *sn;
417         int n = 0;
418
419         strlist__for_each_entry (sn, metrics) {
420                 if (raw)
421                         printf("%s%s", n > 0 ? " " : "", sn->s);
422                 else
423                         printf("  %s\n", sn->s);
424                 n++;
425         }
426         if (raw)
427                 putchar('\n');
428 }
429
430 static int metricgroup__print_pmu_event(const struct pmu_event *pe,
431                                         bool metricgroups, char *filter,
432                                         bool raw, bool details,
433                                         struct rblist *groups,
434                                         struct strlist *metriclist)
435 {
436         const char *g;
437         char *omg, *mg;
438
439         g = pe->metric_group;
440         if (!g && pe->metric_name) {
441                 if (pe->name)
442                         return 0;
443                 g = "No_group";
444         }
445
446         if (!g)
447                 return 0;
448
449         mg = strdup(g);
450
451         if (!mg)
452                 return -ENOMEM;
453         omg = mg;
454         while ((g = strsep(&mg, ";")) != NULL) {
455                 struct mep *me;
456                 char *s;
457
458                 g = skip_spaces(g);
459                 if (*g == 0)
460                         g = "No_group";
461                 if (filter && !strstr(g, filter))
462                         continue;
463                 if (raw)
464                         s = (char *)pe->metric_name;
465                 else {
466                         if (asprintf(&s, "%s\n%*s%s]",
467                                      pe->metric_name, 8, "[", pe->desc) < 0)
468                                 return -1;
469                         if (details) {
470                                 if (asprintf(&s, "%s\n%*s%s]",
471                                              s, 8, "[", pe->metric_expr) < 0)
472                                         return -1;
473                         }
474                 }
475
476                 if (!s)
477                         continue;
478
479                 if (!metricgroups) {
480                         strlist__add(metriclist, s);
481                 } else {
482                         me = mep_lookup(groups, g);
483                         if (!me)
484                                 continue;
485                         strlist__add(me->metrics, s);
486                 }
487
488                 if (!raw)
489                         free(s);
490         }
491         free(omg);
492
493         return 0;
494 }
495
496 struct metricgroup_print_sys_idata {
497         struct strlist *metriclist;
498         char *filter;
499         struct rblist *groups;
500         bool metricgroups;
501         bool raw;
502         bool details;
503 };
504
505 typedef int (*metricgroup_sys_event_iter_fn)(const struct pmu_event *pe, void *);
506
507 struct metricgroup_iter_data {
508         metricgroup_sys_event_iter_fn fn;
509         void *data;
510 };
511
512 static int metricgroup__sys_event_iter(const struct pmu_event *pe, void *data)
513 {
514         struct metricgroup_iter_data *d = data;
515         struct perf_pmu *pmu = NULL;
516
517         if (!pe->metric_expr || !pe->compat)
518                 return 0;
519
520         while ((pmu = perf_pmu__scan(pmu))) {
521
522                 if (!pmu->id || strcmp(pmu->id, pe->compat))
523                         continue;
524
525                 return d->fn(pe, d->data);
526         }
527
528         return 0;
529 }
530
531 static int metricgroup__print_sys_event_iter(const struct pmu_event *pe, void *data)
532 {
533         struct metricgroup_print_sys_idata *d = data;
534
535         return metricgroup__print_pmu_event(pe, d->metricgroups, d->filter, d->raw,
536                                      d->details, d->groups, d->metriclist);
537 }
538
539 void metricgroup__print(bool metrics, bool metricgroups, char *filter,
540                         bool raw, bool details, const char *pmu_name)
541 {
542         struct rblist groups;
543         struct rb_node *node, *next;
544         struct strlist *metriclist = NULL;
545
546         if (!metricgroups) {
547                 metriclist = strlist__new(NULL, NULL);
548                 if (!metriclist)
549                         return;
550         }
551
552         rblist__init(&groups);
553         groups.node_new = mep_new;
554         groups.node_cmp = mep_cmp;
555         groups.node_delete = mep_delete;
556         for (const struct pmu_event *pe = pmu_events_table__find(); pe; pe++) {
557
558                 if (!pe->name && !pe->metric_group && !pe->metric_name)
559                         break;
560                 if (!pe->metric_expr)
561                         continue;
562                 if (pmu_name && perf_pmu__is_hybrid(pe->pmu) &&
563                     strcmp(pmu_name, pe->pmu)) {
564                         continue;
565                 }
566                 if (metricgroup__print_pmu_event(pe, metricgroups, filter,
567                                                  raw, details, &groups,
568                                                  metriclist) < 0)
569                         return;
570         }
571
572         {
573                 struct metricgroup_iter_data data = {
574                         .fn = metricgroup__print_sys_event_iter,
575                         .data = (void *) &(struct metricgroup_print_sys_idata){
576                                 .metriclist = metriclist,
577                                 .metricgroups = metricgroups,
578                                 .filter = filter,
579                                 .raw = raw,
580                                 .details = details,
581                                 .groups = &groups,
582                         },
583                 };
584
585                 pmu_for_each_sys_event(metricgroup__sys_event_iter, &data);
586         }
587
588         if (!filter || !rblist__empty(&groups)) {
589                 if (metricgroups && !raw)
590                         printf("\nMetric Groups:\n\n");
591                 else if (metrics && !raw)
592                         printf("\nMetrics:\n\n");
593         }
594
595         for (node = rb_first_cached(&groups.entries); node; node = next) {
596                 struct mep *me = container_of(node, struct mep, nd);
597
598                 if (metricgroups)
599                         printf("%s%s%s", me->name, metrics && !raw ? ":" : "", raw ? " " : "\n");
600                 if (metrics)
601                         metricgroup__print_strlist(me->metrics, raw);
602                 next = rb_next(node);
603                 rblist__remove_node(&groups, node);
604         }
605         if (!metricgroups)
606                 metricgroup__print_strlist(metriclist, raw);
607         strlist__delete(metriclist);
608 }
609
610 static const char *code_characters = ",-=@";
611
612 static int encode_metric_id(struct strbuf *sb, const char *x)
613 {
614         char *c;
615         int ret = 0;
616
617         for (; *x; x++) {
618                 c = strchr(code_characters, *x);
619                 if (c) {
620                         ret = strbuf_addch(sb, '!');
621                         if (ret)
622                                 break;
623
624                         ret = strbuf_addch(sb, '0' + (c - code_characters));
625                         if (ret)
626                                 break;
627                 } else {
628                         ret = strbuf_addch(sb, *x);
629                         if (ret)
630                                 break;
631                 }
632         }
633         return ret;
634 }
635
636 static int decode_metric_id(struct strbuf *sb, const char *x)
637 {
638         const char *orig = x;
639         size_t i;
640         char c;
641         int ret;
642
643         for (; *x; x++) {
644                 c = *x;
645                 if (*x == '!') {
646                         x++;
647                         i = *x - '0';
648                         if (i > strlen(code_characters)) {
649                                 pr_err("Bad metric-id encoding in: '%s'", orig);
650                                 return -1;
651                         }
652                         c = code_characters[i];
653                 }
654                 ret = strbuf_addch(sb, c);
655                 if (ret)
656                         return ret;
657         }
658         return 0;
659 }
660
661 static int decode_all_metric_ids(struct evlist *perf_evlist, const char *modifier)
662 {
663         struct evsel *ev;
664         struct strbuf sb = STRBUF_INIT;
665         char *cur;
666         int ret = 0;
667
668         evlist__for_each_entry(perf_evlist, ev) {
669                 if (!ev->metric_id)
670                         continue;
671
672                 ret = strbuf_setlen(&sb, 0);
673                 if (ret)
674                         break;
675
676                 ret = decode_metric_id(&sb, ev->metric_id);
677                 if (ret)
678                         break;
679
680                 free((char *)ev->metric_id);
681                 ev->metric_id = strdup(sb.buf);
682                 if (!ev->metric_id) {
683                         ret = -ENOMEM;
684                         break;
685                 }
686                 /*
687                  * If the name is just the parsed event, use the metric-id to
688                  * give a more friendly display version.
689                  */
690                 if (strstr(ev->name, "metric-id=")) {
691                         bool has_slash = false;
692
693                         free(ev->name);
694                         for (cur = strchr(sb.buf, '@') ; cur; cur = strchr(++cur, '@')) {
695                                 *cur = '/';
696                                 has_slash = true;
697                         }
698
699                         if (modifier) {
700                                 if (!has_slash && !strchr(sb.buf, ':')) {
701                                         ret = strbuf_addch(&sb, ':');
702                                         if (ret)
703                                                 break;
704                                 }
705                                 ret = strbuf_addstr(&sb, modifier);
706                                 if (ret)
707                                         break;
708                         }
709                         ev->name = strdup(sb.buf);
710                         if (!ev->name) {
711                                 ret = -ENOMEM;
712                                 break;
713                         }
714                 }
715         }
716         strbuf_release(&sb);
717         return ret;
718 }
719
720 static int metricgroup__build_event_string(struct strbuf *events,
721                                            const struct expr_parse_ctx *ctx,
722                                            const char *modifier,
723                                            bool has_constraint)
724 {
725         struct hashmap_entry *cur;
726         size_t bkt;
727         bool no_group = true, has_tool_events = false;
728         bool tool_events[PERF_TOOL_MAX] = {false};
729         int ret = 0;
730
731 #define RETURN_IF_NON_ZERO(x) do { if (x) return x; } while (0)
732
733         hashmap__for_each_entry(ctx->ids, cur, bkt) {
734                 const char *sep, *rsep, *id = cur->key;
735                 enum perf_tool_event ev;
736
737                 pr_debug("found event %s\n", id);
738
739                 /* Always move tool events outside of the group. */
740                 ev = perf_tool_event__from_str(id);
741                 if (ev != PERF_TOOL_NONE) {
742                         has_tool_events = true;
743                         tool_events[ev] = true;
744                         continue;
745                 }
746                 /* Separate events with commas and open the group if necessary. */
747                 if (no_group) {
748                         if (!has_constraint) {
749                                 ret = strbuf_addch(events, '{');
750                                 RETURN_IF_NON_ZERO(ret);
751                         }
752
753                         no_group = false;
754                 } else {
755                         ret = strbuf_addch(events, ',');
756                         RETURN_IF_NON_ZERO(ret);
757                 }
758                 /*
759                  * Encode the ID as an event string. Add a qualifier for
760                  * metric_id that is the original name except with characters
761                  * that parse-events can't parse replaced. For example,
762                  * 'msr@tsc@' gets added as msr/tsc,metric-id=msr!3tsc!3/
763                  */
764                 sep = strchr(id, '@');
765                 if (sep != NULL) {
766                         ret = strbuf_add(events, id, sep - id);
767                         RETURN_IF_NON_ZERO(ret);
768                         ret = strbuf_addch(events, '/');
769                         RETURN_IF_NON_ZERO(ret);
770                         rsep = strrchr(sep, '@');
771                         ret = strbuf_add(events, sep + 1, rsep - sep - 1);
772                         RETURN_IF_NON_ZERO(ret);
773                         ret = strbuf_addstr(events, ",metric-id=");
774                         RETURN_IF_NON_ZERO(ret);
775                         sep = rsep;
776                 } else {
777                         sep = strchr(id, ':');
778                         if (sep != NULL) {
779                                 ret = strbuf_add(events, id, sep - id);
780                                 RETURN_IF_NON_ZERO(ret);
781                         } else {
782                                 ret = strbuf_addstr(events, id);
783                                 RETURN_IF_NON_ZERO(ret);
784                         }
785                         ret = strbuf_addstr(events, "/metric-id=");
786                         RETURN_IF_NON_ZERO(ret);
787                 }
788                 ret = encode_metric_id(events, id);
789                 RETURN_IF_NON_ZERO(ret);
790                 ret = strbuf_addstr(events, "/");
791                 RETURN_IF_NON_ZERO(ret);
792
793                 if (sep != NULL) {
794                         ret = strbuf_addstr(events, sep + 1);
795                         RETURN_IF_NON_ZERO(ret);
796                 }
797                 if (modifier) {
798                         ret = strbuf_addstr(events, modifier);
799                         RETURN_IF_NON_ZERO(ret);
800                 }
801         }
802         if (!no_group && !has_constraint) {
803                 ret = strbuf_addf(events, "}:W");
804                 RETURN_IF_NON_ZERO(ret);
805         }
806         if (has_tool_events) {
807                 int i;
808
809                 perf_tool_event__for_each_event(i) {
810                         if (tool_events[i]) {
811                                 if (!no_group) {
812                                         ret = strbuf_addch(events, ',');
813                                         RETURN_IF_NON_ZERO(ret);
814                                 }
815                                 no_group = false;
816                                 ret = strbuf_addstr(events, perf_tool_event__to_str(i));
817                                 RETURN_IF_NON_ZERO(ret);
818                         }
819                 }
820         }
821
822         return ret;
823 #undef RETURN_IF_NON_ZERO
824 }
825
826 int __weak arch_get_runtimeparam(const struct pmu_event *pe __maybe_unused)
827 {
828         return 1;
829 }
830
831 /*
832  * A singly linked list on the stack of the names of metrics being
833  * processed. Used to identify recursion.
834  */
835 struct visited_metric {
836         const char *name;
837         const struct visited_metric *parent;
838 };
839
840 struct metricgroup_add_iter_data {
841         struct list_head *metric_list;
842         const char *metric_name;
843         const char *modifier;
844         int *ret;
845         bool *has_match;
846         bool metric_no_group;
847         struct metric *root_metric;
848         const struct visited_metric *visited;
849         const struct pmu_event *table;
850 };
851
852 static int add_metric(struct list_head *metric_list,
853                       const struct pmu_event *pe,
854                       const char *modifier,
855                       bool metric_no_group,
856                       struct metric *root_metric,
857                       const struct visited_metric *visited,
858                       const struct pmu_event *table);
859
860 /**
861  * resolve_metric - Locate metrics within the root metric and recursively add
862  *                    references to them.
863  * @metric_list: The list the metric is added to.
864  * @modifier: if non-null event modifiers like "u".
865  * @metric_no_group: Should events written to events be grouped "{}" or
866  *                   global. Grouping is the default but due to multiplexing the
867  *                   user may override.
868  * @root_metric: Metrics may reference other metrics to form a tree. In this
869  *               case the root_metric holds all the IDs and a list of referenced
870  *               metrics. When adding a root this argument is NULL.
871  * @visited: A singly linked list of metric names being added that is used to
872  *           detect recursion.
873  * @table: The table that is searched for metrics, most commonly the table for the
874  *       architecture perf is running upon.
875  */
876 static int resolve_metric(struct list_head *metric_list,
877                           const char *modifier,
878                           bool metric_no_group,
879                           struct metric *root_metric,
880                           const struct visited_metric *visited,
881                           const struct pmu_event *table)
882 {
883         struct hashmap_entry *cur;
884         size_t bkt;
885         struct to_resolve {
886                 /* The metric to resolve. */
887                 const struct pmu_event *pe;
888                 /*
889                  * The key in the IDs map, this may differ from in case,
890                  * etc. from pe->metric_name.
891                  */
892                 const char *key;
893         } *pending = NULL;
894         int i, ret = 0, pending_cnt = 0;
895
896         /*
897          * Iterate all the parsed IDs and if there's a matching metric and it to
898          * the pending array.
899          */
900         hashmap__for_each_entry(root_metric->pctx->ids, cur, bkt) {
901                 const struct pmu_event *pe;
902
903                 pe = metricgroup__find_metric(cur->key, table);
904                 if (pe) {
905                         pending = realloc(pending,
906                                         (pending_cnt + 1) * sizeof(struct to_resolve));
907                         if (!pending)
908                                 return -ENOMEM;
909
910                         pending[pending_cnt].pe = pe;
911                         pending[pending_cnt].key = cur->key;
912                         pending_cnt++;
913                 }
914         }
915
916         /* Remove the metric IDs from the context. */
917         for (i = 0; i < pending_cnt; i++)
918                 expr__del_id(root_metric->pctx, pending[i].key);
919
920         /*
921          * Recursively add all the metrics, IDs are added to the root metric's
922          * context.
923          */
924         for (i = 0; i < pending_cnt; i++) {
925                 ret = add_metric(metric_list, pending[i].pe, modifier, metric_no_group,
926                                 root_metric, visited, table);
927                 if (ret)
928                         break;
929         }
930
931         free(pending);
932         return ret;
933 }
934
935 /**
936  * __add_metric - Add a metric to metric_list.
937  * @metric_list: The list the metric is added to.
938  * @pe: The pmu_event containing the metric to be added.
939  * @modifier: if non-null event modifiers like "u".
940  * @metric_no_group: Should events written to events be grouped "{}" or
941  *                   global. Grouping is the default but due to multiplexing the
942  *                   user may override.
943  * @runtime: A special argument for the parser only known at runtime.
944  * @root_metric: Metrics may reference other metrics to form a tree. In this
945  *               case the root_metric holds all the IDs and a list of referenced
946  *               metrics. When adding a root this argument is NULL.
947  * @visited: A singly linked list of metric names being added that is used to
948  *           detect recursion.
949  * @table: The table that is searched for metrics, most commonly the table for the
950  *       architecture perf is running upon.
951  */
952 static int __add_metric(struct list_head *metric_list,
953                         const struct pmu_event *pe,
954                         const char *modifier,
955                         bool metric_no_group,
956                         int runtime,
957                         struct metric *root_metric,
958                         const struct visited_metric *visited,
959                         const struct pmu_event *table)
960 {
961         const struct visited_metric *vm;
962         int ret;
963         bool is_root = !root_metric;
964         struct visited_metric visited_node = {
965                 .name = pe->metric_name,
966                 .parent = visited,
967         };
968
969         for (vm = visited; vm; vm = vm->parent) {
970                 if (!strcmp(pe->metric_name, vm->name)) {
971                         pr_err("failed: recursion detected for %s\n", pe->metric_name);
972                         return -1;
973                 }
974         }
975
976         if (is_root) {
977                 /*
978                  * This metric is the root of a tree and may reference other
979                  * metrics that are added recursively.
980                  */
981                 root_metric = metric__new(pe, modifier, metric_no_group, runtime);
982                 if (!root_metric)
983                         return -ENOMEM;
984
985         } else {
986                 int cnt = 0;
987
988                 /*
989                  * This metric was referenced in a metric higher in the
990                  * tree. Check if the same metric is already resolved in the
991                  * metric_refs list.
992                  */
993                 if (root_metric->metric_refs) {
994                         for (; root_metric->metric_refs[cnt].metric_name; cnt++) {
995                                 if (!strcmp(pe->metric_name,
996                                             root_metric->metric_refs[cnt].metric_name))
997                                         return 0;
998                         }
999                 }
1000
1001                 /* Create reference. Need space for the entry and the terminator. */
1002                 root_metric->metric_refs = realloc(root_metric->metric_refs,
1003                                                 (cnt + 2) * sizeof(struct metric_ref));
1004                 if (!root_metric->metric_refs)
1005                         return -ENOMEM;
1006
1007                 /*
1008                  * Intentionally passing just const char pointers,
1009                  * from 'pe' object, so they never go away. We don't
1010                  * need to change them, so there's no need to create
1011                  * our own copy.
1012                  */
1013                 root_metric->metric_refs[cnt].metric_name = pe->metric_name;
1014                 root_metric->metric_refs[cnt].metric_expr = pe->metric_expr;
1015
1016                 /* Null terminate array. */
1017                 root_metric->metric_refs[cnt+1].metric_name = NULL;
1018                 root_metric->metric_refs[cnt+1].metric_expr = NULL;
1019         }
1020
1021         /*
1022          * For both the parent and referenced metrics, we parse
1023          * all the metric's IDs and add it to the root context.
1024          */
1025         if (expr__find_ids(pe->metric_expr, NULL, root_metric->pctx) < 0) {
1026                 /* Broken metric. */
1027                 ret = -EINVAL;
1028         } else {
1029                 /* Resolve referenced metrics. */
1030                 ret = resolve_metric(metric_list, modifier, metric_no_group, root_metric,
1031                                      &visited_node, table);
1032         }
1033
1034         if (ret) {
1035                 if (is_root)
1036                         metric__free(root_metric);
1037
1038         } else if (is_root)
1039                 list_add(&root_metric->nd, metric_list);
1040
1041         return ret;
1042 }
1043
1044 #define table_for_each_event(__pe, __idx, __table)                                      \
1045         if (__table)                                                            \
1046                 for (__idx = 0, __pe = &__table[__idx];                         \
1047                      __pe->name || __pe->metric_group || __pe->metric_name;     \
1048                      __pe = &__table[++__idx])
1049
1050 #define table_for_each_metric(__pe, __idx, __table, __metric)           \
1051         table_for_each_event(__pe, __idx, __table)                              \
1052                 if (__pe->metric_expr &&                                \
1053                     (match_metric(__pe->metric_group, __metric) ||      \
1054                      match_metric(__pe->metric_name, __metric)))
1055
1056 const struct pmu_event *metricgroup__find_metric(const char *metric,
1057                                                  const struct pmu_event *table)
1058 {
1059         const struct pmu_event *pe;
1060         int i;
1061
1062         table_for_each_event(pe, i, table) {
1063                 if (match_metric(pe->metric_name, metric))
1064                         return pe;
1065         }
1066
1067         return NULL;
1068 }
1069
1070 static int add_metric(struct list_head *metric_list,
1071                       const struct pmu_event *pe,
1072                       const char *modifier,
1073                       bool metric_no_group,
1074                       struct metric *root_metric,
1075                       const struct visited_metric *visited,
1076                       const struct pmu_event *table)
1077 {
1078         int ret = 0;
1079
1080         pr_debug("metric expr %s for %s\n", pe->metric_expr, pe->metric_name);
1081
1082         if (!strstr(pe->metric_expr, "?")) {
1083                 ret = __add_metric(metric_list, pe, modifier, metric_no_group, 0,
1084                                    root_metric, visited, table);
1085         } else {
1086                 int j, count;
1087
1088                 count = arch_get_runtimeparam(pe);
1089
1090                 /* This loop is added to create multiple
1091                  * events depend on count value and add
1092                  * those events to metric_list.
1093                  */
1094
1095                 for (j = 0; j < count && !ret; j++)
1096                         ret = __add_metric(metric_list, pe, modifier, metric_no_group, j,
1097                                         root_metric, visited, table);
1098         }
1099
1100         return ret;
1101 }
1102
1103 static int metricgroup__add_metric_sys_event_iter(const struct pmu_event *pe,
1104                                                   void *data)
1105 {
1106         struct metricgroup_add_iter_data *d = data;
1107         int ret;
1108
1109         if (!match_pe_metric(pe, d->metric_name))
1110                 return 0;
1111
1112         ret = add_metric(d->metric_list, pe, d->modifier, d->metric_no_group,
1113                          d->root_metric, d->visited, d->table);
1114         if (ret)
1115                 goto out;
1116
1117         *(d->has_match) = true;
1118
1119 out:
1120         *(d->ret) = ret;
1121         return ret;
1122 }
1123
1124 /**
1125  * metric_list_cmp - list_sort comparator that sorts metrics with more events to
1126  *                   the front. tool events are excluded from the count.
1127  */
1128 static int metric_list_cmp(void *priv __maybe_unused, const struct list_head *l,
1129                            const struct list_head *r)
1130 {
1131         const struct metric *left = container_of(l, struct metric, nd);
1132         const struct metric *right = container_of(r, struct metric, nd);
1133         struct expr_id_data *data;
1134         int i, left_count, right_count;
1135
1136         left_count = hashmap__size(left->pctx->ids);
1137         perf_tool_event__for_each_event(i) {
1138                 if (!expr__get_id(left->pctx, perf_tool_event__to_str(i), &data))
1139                         left_count--;
1140         }
1141
1142         right_count = hashmap__size(right->pctx->ids);
1143         perf_tool_event__for_each_event(i) {
1144                 if (!expr__get_id(right->pctx, perf_tool_event__to_str(i), &data))
1145                         right_count--;
1146         }
1147
1148         return right_count - left_count;
1149 }
1150
1151 /**
1152  * metricgroup__add_metric - Find and add a metric, or a metric group.
1153  * @metric_name: The name of the metric or metric group. For example, "IPC"
1154  *               could be the name of a metric and "TopDownL1" the name of a
1155  *               metric group.
1156  * @modifier: if non-null event modifiers like "u".
1157  * @metric_no_group: Should events written to events be grouped "{}" or
1158  *                   global. Grouping is the default but due to multiplexing the
1159  *                   user may override.
1160  * @metric_list: The list that the metric or metric group are added to.
1161  * @table: The table that is searched for metrics, most commonly the table for the
1162  *       architecture perf is running upon.
1163  */
1164 static int metricgroup__add_metric(const char *metric_name, const char *modifier,
1165                                    bool metric_no_group,
1166                                    struct list_head *metric_list,
1167                                    const struct pmu_event *table)
1168 {
1169         const struct pmu_event *pe;
1170         LIST_HEAD(list);
1171         int i, ret;
1172         bool has_match = false;
1173
1174         /*
1175          * Iterate over all metrics seeing if metric matches either the name or
1176          * group. When it does add the metric to the list.
1177          */
1178         table_for_each_metric(pe, i, table, metric_name) {
1179                 has_match = true;
1180                 ret = add_metric(&list, pe, modifier, metric_no_group,
1181                                  /*root_metric=*/NULL,
1182                                  /*visited_metrics=*/NULL, table);
1183                 if (ret)
1184                         goto out;
1185         }
1186
1187         {
1188                 struct metricgroup_iter_data data = {
1189                         .fn = metricgroup__add_metric_sys_event_iter,
1190                         .data = (void *) &(struct metricgroup_add_iter_data) {
1191                                 .metric_list = &list,
1192                                 .metric_name = metric_name,
1193                                 .modifier = modifier,
1194                                 .metric_no_group = metric_no_group,
1195                                 .has_match = &has_match,
1196                                 .ret = &ret,
1197                                 .table = table,
1198                         },
1199                 };
1200
1201                 pmu_for_each_sys_event(metricgroup__sys_event_iter, &data);
1202         }
1203         /* End of pmu events. */
1204         if (!has_match)
1205                 ret = -EINVAL;
1206
1207 out:
1208         /*
1209          * add to metric_list so that they can be released
1210          * even if it's failed
1211          */
1212         list_splice(&list, metric_list);
1213         return ret;
1214 }
1215
1216 /**
1217  * metricgroup__add_metric_list - Find and add metrics, or metric groups,
1218  *                                specified in a list.
1219  * @list: the list of metrics or metric groups. For example, "IPC,CPI,TopDownL1"
1220  *        would match the IPC and CPI metrics, and TopDownL1 would match all
1221  *        the metrics in the TopDownL1 group.
1222  * @metric_no_group: Should events written to events be grouped "{}" or
1223  *                   global. Grouping is the default but due to multiplexing the
1224  *                   user may override.
1225  * @metric_list: The list that metrics are added to.
1226  * @table: The table that is searched for metrics, most commonly the table for the
1227  *       architecture perf is running upon.
1228  */
1229 static int metricgroup__add_metric_list(const char *list, bool metric_no_group,
1230                                         struct list_head *metric_list,
1231                                         const struct pmu_event *table)
1232 {
1233         char *list_itr, *list_copy, *metric_name, *modifier;
1234         int ret, count = 0;
1235
1236         list_copy = strdup(list);
1237         if (!list_copy)
1238                 return -ENOMEM;
1239         list_itr = list_copy;
1240
1241         while ((metric_name = strsep(&list_itr, ",")) != NULL) {
1242                 modifier = strchr(metric_name, ':');
1243                 if (modifier)
1244                         *modifier++ = '\0';
1245
1246                 ret = metricgroup__add_metric(metric_name, modifier,
1247                                               metric_no_group, metric_list,
1248                                               table);
1249                 if (ret == -EINVAL)
1250                         pr_err("Cannot find metric or group `%s'\n", metric_name);
1251
1252                 if (ret)
1253                         break;
1254
1255                 count++;
1256         }
1257         free(list_copy);
1258
1259         if (!ret) {
1260                 /*
1261                  * Warn about nmi_watchdog if any parsed metrics had the
1262                  * NO_NMI_WATCHDOG constraint.
1263                  */
1264                 metricgroup___watchdog_constraint_hint(NULL, true);
1265                 /* No metrics. */
1266                 if (count == 0)
1267                         return -EINVAL;
1268         }
1269         return ret;
1270 }
1271
1272 static void metricgroup__free_metrics(struct list_head *metric_list)
1273 {
1274         struct metric *m, *tmp;
1275
1276         list_for_each_entry_safe (m, tmp, metric_list, nd) {
1277                 list_del_init(&m->nd);
1278                 metric__free(m);
1279         }
1280 }
1281
1282 /**
1283  * find_tool_events - Search for the pressence of tool events in metric_list.
1284  * @metric_list: List to take metrics from.
1285  * @tool_events: Array of false values, indices corresponding to tool events set
1286  *               to true if tool event is found.
1287  */
1288 static void find_tool_events(const struct list_head *metric_list,
1289                              bool tool_events[PERF_TOOL_MAX])
1290 {
1291         struct metric *m;
1292
1293         list_for_each_entry(m, metric_list, nd) {
1294                 int i;
1295
1296                 perf_tool_event__for_each_event(i) {
1297                         struct expr_id_data *data;
1298
1299                         if (!tool_events[i] &&
1300                             !expr__get_id(m->pctx, perf_tool_event__to_str(i), &data))
1301                                 tool_events[i] = true;
1302                 }
1303         }
1304 }
1305
1306 /**
1307  * build_combined_expr_ctx - Make an expr_parse_ctx with all has_constraint
1308  *                           metric IDs, as the IDs are held in a set,
1309  *                           duplicates will be removed.
1310  * @metric_list: List to take metrics from.
1311  * @combined: Out argument for result.
1312  */
1313 static int build_combined_expr_ctx(const struct list_head *metric_list,
1314                                    struct expr_parse_ctx **combined)
1315 {
1316         struct hashmap_entry *cur;
1317         size_t bkt;
1318         struct metric *m;
1319         char *dup;
1320         int ret;
1321
1322         *combined = expr__ctx_new();
1323         if (!*combined)
1324                 return -ENOMEM;
1325
1326         list_for_each_entry(m, metric_list, nd) {
1327                 if (m->has_constraint && !m->modifier) {
1328                         hashmap__for_each_entry(m->pctx->ids, cur, bkt) {
1329                                 dup = strdup(cur->key);
1330                                 if (!dup) {
1331                                         ret = -ENOMEM;
1332                                         goto err_out;
1333                                 }
1334                                 ret = expr__add_id(*combined, dup);
1335                                 if (ret)
1336                                         goto err_out;
1337                         }
1338                 }
1339         }
1340         return 0;
1341 err_out:
1342         expr__ctx_free(*combined);
1343         *combined = NULL;
1344         return ret;
1345 }
1346
1347 /**
1348  * parse_ids - Build the event string for the ids and parse them creating an
1349  *             evlist. The encoded metric_ids are decoded.
1350  * @metric_no_merge: is metric sharing explicitly disabled.
1351  * @fake_pmu: used when testing metrics not supported by the current CPU.
1352  * @ids: the event identifiers parsed from a metric.
1353  * @modifier: any modifiers added to the events.
1354  * @has_constraint: false if events should be placed in a weak group.
1355  * @tool_events: entries set true if the tool event of index could be present in
1356  *               the overall list of metrics.
1357  * @out_evlist: the created list of events.
1358  */
1359 static int parse_ids(bool metric_no_merge, struct perf_pmu *fake_pmu,
1360                      struct expr_parse_ctx *ids, const char *modifier,
1361                      bool has_constraint, const bool tool_events[PERF_TOOL_MAX],
1362                      struct evlist **out_evlist)
1363 {
1364         struct parse_events_error parse_error;
1365         struct evlist *parsed_evlist;
1366         struct strbuf events = STRBUF_INIT;
1367         int ret;
1368
1369         *out_evlist = NULL;
1370         if (!metric_no_merge || hashmap__size(ids->ids) == 0) {
1371                 bool added_event = false;
1372                 int i;
1373                 /*
1374                  * We may fail to share events between metrics because a tool
1375                  * event isn't present in one metric. For example, a ratio of
1376                  * cache misses doesn't need duration_time but the same events
1377                  * may be used for a misses per second. Events without sharing
1378                  * implies multiplexing, that is best avoided, so place
1379                  * all tool events in every group.
1380                  *
1381                  * Also, there may be no ids/events in the expression parsing
1382                  * context because of constant evaluation, e.g.:
1383                  *    event1 if #smt_on else 0
1384                  * Add a tool event to avoid a parse error on an empty string.
1385                  */
1386                 perf_tool_event__for_each_event(i) {
1387                         if (tool_events[i]) {
1388                                 char *tmp = strdup(perf_tool_event__to_str(i));
1389
1390                                 if (!tmp)
1391                                         return -ENOMEM;
1392                                 ids__insert(ids->ids, tmp);
1393                                 added_event = true;
1394                         }
1395                 }
1396                 if (!added_event && hashmap__size(ids->ids) == 0) {
1397                         char *tmp = strdup("duration_time");
1398
1399                         if (!tmp)
1400                                 return -ENOMEM;
1401                         ids__insert(ids->ids, tmp);
1402                 }
1403         }
1404         ret = metricgroup__build_event_string(&events, ids, modifier,
1405                                               has_constraint);
1406         if (ret)
1407                 return ret;
1408
1409         parsed_evlist = evlist__new();
1410         if (!parsed_evlist) {
1411                 ret = -ENOMEM;
1412                 goto err_out;
1413         }
1414         pr_debug("Parsing metric events '%s'\n", events.buf);
1415         parse_events_error__init(&parse_error);
1416         ret = __parse_events(parsed_evlist, events.buf, &parse_error, fake_pmu);
1417         if (ret) {
1418                 parse_events_error__print(&parse_error, events.buf);
1419                 goto err_out;
1420         }
1421         ret = decode_all_metric_ids(parsed_evlist, modifier);
1422         if (ret)
1423                 goto err_out;
1424
1425         *out_evlist = parsed_evlist;
1426         parsed_evlist = NULL;
1427 err_out:
1428         parse_events_error__exit(&parse_error);
1429         evlist__delete(parsed_evlist);
1430         strbuf_release(&events);
1431         return ret;
1432 }
1433
1434 static int parse_groups(struct evlist *perf_evlist, const char *str,
1435                         bool metric_no_group,
1436                         bool metric_no_merge,
1437                         struct perf_pmu *fake_pmu,
1438                         struct rblist *metric_events_list,
1439                         const struct pmu_event *table)
1440 {
1441         struct evlist *combined_evlist = NULL;
1442         LIST_HEAD(metric_list);
1443         struct metric *m;
1444         bool tool_events[PERF_TOOL_MAX] = {false};
1445         int ret;
1446
1447         if (metric_events_list->nr_entries == 0)
1448                 metricgroup__rblist_init(metric_events_list);
1449         ret = metricgroup__add_metric_list(str, metric_no_group,
1450                                            &metric_list, table);
1451         if (ret)
1452                 goto out;
1453
1454         /* Sort metrics from largest to smallest. */
1455         list_sort(NULL, &metric_list, metric_list_cmp);
1456
1457         if (!metric_no_merge) {
1458                 struct expr_parse_ctx *combined = NULL;
1459
1460                 find_tool_events(&metric_list, tool_events);
1461
1462                 ret = build_combined_expr_ctx(&metric_list, &combined);
1463
1464                 if (!ret && combined && hashmap__size(combined->ids)) {
1465                         ret = parse_ids(metric_no_merge, fake_pmu, combined,
1466                                         /*modifier=*/NULL,
1467                                         /*has_constraint=*/true,
1468                                         tool_events,
1469                                         &combined_evlist);
1470                 }
1471                 if (combined)
1472                         expr__ctx_free(combined);
1473
1474                 if (ret)
1475                         goto out;
1476         }
1477
1478         list_for_each_entry(m, &metric_list, nd) {
1479                 struct metric_event *me;
1480                 struct evsel **metric_events;
1481                 struct evlist *metric_evlist = NULL;
1482                 struct metric *n;
1483                 struct metric_expr *expr;
1484
1485                 if (combined_evlist && m->has_constraint) {
1486                         metric_evlist = combined_evlist;
1487                 } else if (!metric_no_merge) {
1488                         /*
1489                          * See if the IDs for this metric are a subset of an
1490                          * earlier metric.
1491                          */
1492                         list_for_each_entry(n, &metric_list, nd) {
1493                                 if (m == n)
1494                                         break;
1495
1496                                 if (n->evlist == NULL)
1497                                         continue;
1498
1499                                 if ((!m->modifier && n->modifier) ||
1500                                     (m->modifier && !n->modifier) ||
1501                                     (m->modifier && n->modifier &&
1502                                             strcmp(m->modifier, n->modifier)))
1503                                         continue;
1504
1505                                 if (expr__subset_of_ids(n->pctx, m->pctx)) {
1506                                         pr_debug("Events in '%s' fully contained within '%s'\n",
1507                                                  m->metric_name, n->metric_name);
1508                                         metric_evlist = n->evlist;
1509                                         break;
1510                                 }
1511
1512                         }
1513                 }
1514                 if (!metric_evlist) {
1515                         ret = parse_ids(metric_no_merge, fake_pmu, m->pctx, m->modifier,
1516                                         m->has_constraint, tool_events, &m->evlist);
1517                         if (ret)
1518                                 goto out;
1519
1520                         metric_evlist = m->evlist;
1521                 }
1522                 ret = setup_metric_events(m->pctx->ids, metric_evlist, &metric_events);
1523                 if (ret) {
1524                         pr_debug("Cannot resolve IDs for %s: %s\n",
1525                                 m->metric_name, m->metric_expr);
1526                         goto out;
1527                 }
1528
1529                 me = metricgroup__lookup(metric_events_list, metric_events[0], true);
1530
1531                 expr = malloc(sizeof(struct metric_expr));
1532                 if (!expr) {
1533                         ret = -ENOMEM;
1534                         free(metric_events);
1535                         goto out;
1536                 }
1537
1538                 expr->metric_refs = m->metric_refs;
1539                 m->metric_refs = NULL;
1540                 expr->metric_expr = m->metric_expr;
1541                 if (m->modifier) {
1542                         char *tmp;
1543
1544                         if (asprintf(&tmp, "%s:%s", m->metric_name, m->modifier) < 0)
1545                                 expr->metric_name = NULL;
1546                         else
1547                                 expr->metric_name = tmp;
1548                 } else
1549                         expr->metric_name = strdup(m->metric_name);
1550
1551                 if (!expr->metric_name) {
1552                         ret = -ENOMEM;
1553                         free(metric_events);
1554                         goto out;
1555                 }
1556                 expr->metric_unit = m->metric_unit;
1557                 expr->metric_events = metric_events;
1558                 expr->runtime = m->pctx->runtime;
1559                 list_add(&expr->nd, &me->head);
1560         }
1561
1562
1563         if (combined_evlist) {
1564                 evlist__splice_list_tail(perf_evlist, &combined_evlist->core.entries);
1565                 evlist__delete(combined_evlist);
1566         }
1567
1568         list_for_each_entry(m, &metric_list, nd) {
1569                 if (m->evlist)
1570                         evlist__splice_list_tail(perf_evlist, &m->evlist->core.entries);
1571         }
1572
1573 out:
1574         metricgroup__free_metrics(&metric_list);
1575         return ret;
1576 }
1577
1578 int metricgroup__parse_groups(const struct option *opt,
1579                               const char *str,
1580                               bool metric_no_group,
1581                               bool metric_no_merge,
1582                               struct rblist *metric_events)
1583 {
1584         struct evlist *perf_evlist = *(struct evlist **)opt->value;
1585         const struct pmu_event *table = pmu_events_table__find();
1586
1587         return parse_groups(perf_evlist, str, metric_no_group,
1588                             metric_no_merge, NULL, metric_events, table);
1589 }
1590
1591 int metricgroup__parse_groups_test(struct evlist *evlist,
1592                                    const struct pmu_event *table,
1593                                    const char *str,
1594                                    bool metric_no_group,
1595                                    bool metric_no_merge,
1596                                    struct rblist *metric_events)
1597 {
1598         return parse_groups(evlist, str, metric_no_group,
1599                             metric_no_merge, &perf_pmu__fake, metric_events, table);
1600 }
1601
1602 bool metricgroup__has_metric(const char *metric)
1603 {
1604         const struct pmu_event *table = pmu_events_table__find();
1605         const struct pmu_event *pe;
1606         int i;
1607
1608         if (!table)
1609                 return false;
1610
1611         for (i = 0; ; i++) {
1612                 pe = &table[i];
1613
1614                 if (!pe->name && !pe->metric_group && !pe->metric_name)
1615                         break;
1616                 if (!pe->metric_expr)
1617                         continue;
1618                 if (match_metric(pe->metric_name, metric))
1619                         return true;
1620         }
1621         return false;
1622 }
1623
1624 int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
1625                                     struct rblist *new_metric_events,
1626                                     struct rblist *old_metric_events)
1627 {
1628         unsigned i;
1629
1630         for (i = 0; i < rblist__nr_entries(old_metric_events); i++) {
1631                 struct rb_node *nd;
1632                 struct metric_event *old_me, *new_me;
1633                 struct metric_expr *old_expr, *new_expr;
1634                 struct evsel *evsel;
1635                 size_t alloc_size;
1636                 int idx, nr;
1637
1638                 nd = rblist__entry(old_metric_events, i);
1639                 old_me = container_of(nd, struct metric_event, nd);
1640
1641                 evsel = evlist__find_evsel(evlist, old_me->evsel->core.idx);
1642                 if (!evsel)
1643                         return -EINVAL;
1644                 new_me = metricgroup__lookup(new_metric_events, evsel, true);
1645                 if (!new_me)
1646                         return -ENOMEM;
1647
1648                 pr_debug("copying metric event for cgroup '%s': %s (idx=%d)\n",
1649                          cgrp ? cgrp->name : "root", evsel->name, evsel->core.idx);
1650
1651                 list_for_each_entry(old_expr, &old_me->head, nd) {
1652                         new_expr = malloc(sizeof(*new_expr));
1653                         if (!new_expr)
1654                                 return -ENOMEM;
1655
1656                         new_expr->metric_expr = old_expr->metric_expr;
1657                         new_expr->metric_name = strdup(old_expr->metric_name);
1658                         if (!new_expr->metric_name)
1659                                 return -ENOMEM;
1660
1661                         new_expr->metric_unit = old_expr->metric_unit;
1662                         new_expr->runtime = old_expr->runtime;
1663
1664                         if (old_expr->metric_refs) {
1665                                 /* calculate number of metric_events */
1666                                 for (nr = 0; old_expr->metric_refs[nr].metric_name; nr++)
1667                                         continue;
1668                                 alloc_size = sizeof(*new_expr->metric_refs);
1669                                 new_expr->metric_refs = calloc(nr + 1, alloc_size);
1670                                 if (!new_expr->metric_refs) {
1671                                         free(new_expr);
1672                                         return -ENOMEM;
1673                                 }
1674
1675                                 memcpy(new_expr->metric_refs, old_expr->metric_refs,
1676                                        nr * alloc_size);
1677                         } else {
1678                                 new_expr->metric_refs = NULL;
1679                         }
1680
1681                         /* calculate number of metric_events */
1682                         for (nr = 0; old_expr->metric_events[nr]; nr++)
1683                                 continue;
1684                         alloc_size = sizeof(*new_expr->metric_events);
1685                         new_expr->metric_events = calloc(nr + 1, alloc_size);
1686                         if (!new_expr->metric_events) {
1687                                 free(new_expr->metric_refs);
1688                                 free(new_expr);
1689                                 return -ENOMEM;
1690                         }
1691
1692                         /* copy evsel in the same position */
1693                         for (idx = 0; idx < nr; idx++) {
1694                                 evsel = old_expr->metric_events[idx];
1695                                 evsel = evlist__find_evsel(evlist, evsel->core.idx);
1696                                 if (evsel == NULL) {
1697                                         free(new_expr->metric_events);
1698                                         free(new_expr->metric_refs);
1699                                         free(new_expr);
1700                                         return -EINVAL;
1701                                 }
1702                                 new_expr->metric_events[idx] = evsel;
1703                         }
1704
1705                         list_add(&new_expr->nd, &new_me->head);
1706                 }
1707         }
1708         return 0;
1709 }