perf metric: Free metric when it failed to resolve
[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 "expr.h"
15 #include "rblist.h"
16 #include <string.h>
17 #include <errno.h>
18 #include "pmu-events/pmu-events.h"
19 #include "strlist.h"
20 #include <assert.h>
21 #include <linux/ctype.h>
22 #include <linux/string.h>
23 #include <linux/zalloc.h>
24 #include <subcmd/parse-options.h>
25 #include <api/fs/fs.h>
26 #include "util.h"
27 #include <asm/bug.h>
28
29 struct metric_event *metricgroup__lookup(struct rblist *metric_events,
30                                          struct evsel *evsel,
31                                          bool create)
32 {
33         struct rb_node *nd;
34         struct metric_event me = {
35                 .evsel = evsel
36         };
37
38         if (!metric_events)
39                 return NULL;
40
41         nd = rblist__find(metric_events, &me);
42         if (nd)
43                 return container_of(nd, struct metric_event, nd);
44         if (create) {
45                 rblist__add_node(metric_events, &me);
46                 nd = rblist__find(metric_events, &me);
47                 if (nd)
48                         return container_of(nd, struct metric_event, nd);
49         }
50         return NULL;
51 }
52
53 static int metric_event_cmp(struct rb_node *rb_node, const void *entry)
54 {
55         struct metric_event *a = container_of(rb_node,
56                                               struct metric_event,
57                                               nd);
58         const struct metric_event *b = entry;
59
60         if (a->evsel == b->evsel)
61                 return 0;
62         if ((char *)a->evsel < (char *)b->evsel)
63                 return -1;
64         return +1;
65 }
66
67 static struct rb_node *metric_event_new(struct rblist *rblist __maybe_unused,
68                                         const void *entry)
69 {
70         struct metric_event *me = malloc(sizeof(struct metric_event));
71
72         if (!me)
73                 return NULL;
74         memcpy(me, entry, sizeof(struct metric_event));
75         me->evsel = ((struct metric_event *)entry)->evsel;
76         INIT_LIST_HEAD(&me->head);
77         return &me->nd;
78 }
79
80 static void metric_event_delete(struct rblist *rblist __maybe_unused,
81                                 struct rb_node *rb_node)
82 {
83         struct metric_event *me = container_of(rb_node, struct metric_event, nd);
84         struct metric_expr *expr, *tmp;
85
86         list_for_each_entry_safe(expr, tmp, &me->head, nd) {
87                 free(expr->metric_refs);
88                 free(expr->metric_events);
89                 free(expr);
90         }
91
92         free(me);
93 }
94
95 static void metricgroup__rblist_init(struct rblist *metric_events)
96 {
97         rblist__init(metric_events);
98         metric_events->node_cmp = metric_event_cmp;
99         metric_events->node_new = metric_event_new;
100         metric_events->node_delete = metric_event_delete;
101 }
102
103 void metricgroup__rblist_exit(struct rblist *metric_events)
104 {
105         rblist__exit(metric_events);
106 }
107
108 /*
109  * A node in the list of referenced metrics. metric_expr
110  * is held as a convenience to avoid a search through the
111  * metric list.
112  */
113 struct metric_ref_node {
114         const char *metric_name;
115         const char *metric_expr;
116         struct list_head list;
117 };
118
119 struct metric {
120         struct list_head nd;
121         struct expr_parse_ctx pctx;
122         const char *metric_name;
123         const char *metric_expr;
124         const char *metric_unit;
125         struct list_head metric_refs;
126         int metric_refs_cnt;
127         int runtime;
128         bool has_constraint;
129 };
130
131 #define RECURSION_ID_MAX 1000
132
133 struct expr_ids {
134         struct expr_id  id[RECURSION_ID_MAX];
135         int             cnt;
136 };
137
138 static struct expr_id *expr_ids__alloc(struct expr_ids *ids)
139 {
140         if (ids->cnt >= RECURSION_ID_MAX)
141                 return NULL;
142         return &ids->id[ids->cnt++];
143 }
144
145 static void expr_ids__exit(struct expr_ids *ids)
146 {
147         int i;
148
149         for (i = 0; i < ids->cnt; i++)
150                 free(ids->id[i].id);
151 }
152
153 /**
154  * Find a group of events in perf_evlist that correpond to those from a parsed
155  * metric expression. Note, as find_evsel_group is called in the same order as
156  * perf_evlist was constructed, metric_no_merge doesn't need to test for
157  * underfilling a group.
158  * @perf_evlist: a list of events something like: {metric1 leader, metric1
159  * sibling, metric1 sibling}:W,duration_time,{metric2 leader, metric2 sibling,
160  * metric2 sibling}:W,duration_time
161  * @pctx: the parse context for the metric expression.
162  * @metric_no_merge: don't attempt to share events for the metric with other
163  * metrics.
164  * @has_constraint: is there a contraint on the group of events? In which case
165  * the events won't be grouped.
166  * @metric_events: out argument, null terminated array of evsel's associated
167  * with the metric.
168  * @evlist_used: in/out argument, bitmap tracking which evlist events are used.
169  * @return the first metric event or NULL on failure.
170  */
171 static struct evsel *find_evsel_group(struct evlist *perf_evlist,
172                                       struct expr_parse_ctx *pctx,
173                                       bool metric_no_merge,
174                                       bool has_constraint,
175                                       struct evsel **metric_events,
176                                       unsigned long *evlist_used)
177 {
178         struct evsel *ev, *current_leader = NULL;
179         struct expr_id_data *val_ptr;
180         int i = 0, matched_events = 0, events_to_match;
181         const int idnum = (int)hashmap__size(&pctx->ids);
182
183         /* duration_time is grouped separately. */
184         if (!has_constraint &&
185             hashmap__find(&pctx->ids, "duration_time", (void **)&val_ptr))
186                 events_to_match = idnum - 1;
187         else
188                 events_to_match = idnum;
189
190         evlist__for_each_entry (perf_evlist, ev) {
191                 /*
192                  * Events with a constraint aren't grouped and match the first
193                  * events available.
194                  */
195                 if (has_constraint && ev->weak_group)
196                         continue;
197                 /* Ignore event if already used and merging is disabled. */
198                 if (metric_no_merge && test_bit(ev->idx, evlist_used))
199                         continue;
200                 if (!has_constraint && ev->leader != current_leader) {
201                         /*
202                          * Start of a new group, discard the whole match and
203                          * start again.
204                          */
205                         matched_events = 0;
206                         memset(metric_events, 0,
207                                 sizeof(struct evsel *) * idnum);
208                         current_leader = ev->leader;
209                 }
210                 if (hashmap__find(&pctx->ids, ev->name, (void **)&val_ptr)) {
211                         if (has_constraint) {
212                                 /*
213                                  * Events aren't grouped, ensure the same event
214                                  * isn't matched from two groups.
215                                  */
216                                 for (i = 0; i < matched_events; i++) {
217                                         if (!strcmp(ev->name,
218                                                     metric_events[i]->name)) {
219                                                 break;
220                                         }
221                                 }
222                                 if (i != matched_events)
223                                         continue;
224                         }
225                         metric_events[matched_events++] = ev;
226                 }
227                 if (matched_events == events_to_match)
228                         break;
229         }
230
231         if (events_to_match != idnum) {
232                 /* Add the first duration_time. */
233                 evlist__for_each_entry(perf_evlist, ev) {
234                         if (!strcmp(ev->name, "duration_time")) {
235                                 metric_events[matched_events++] = ev;
236                                 break;
237                         }
238                 }
239         }
240
241         if (matched_events != idnum) {
242                 /* Not whole match */
243                 return NULL;
244         }
245
246         metric_events[idnum] = NULL;
247
248         for (i = 0; i < idnum; i++) {
249                 ev = metric_events[i];
250                 ev->metric_leader = ev;
251                 set_bit(ev->idx, evlist_used);
252         }
253
254         return metric_events[0];
255 }
256
257 static int metricgroup__setup_events(struct list_head *groups,
258                                      bool metric_no_merge,
259                                      struct evlist *perf_evlist,
260                                      struct rblist *metric_events_list)
261 {
262         struct metric_event *me;
263         struct metric_expr *expr;
264         int i = 0;
265         int ret = 0;
266         struct metric *m;
267         struct evsel *evsel, *tmp;
268         unsigned long *evlist_used;
269
270         evlist_used = bitmap_alloc(perf_evlist->core.nr_entries);
271         if (!evlist_used)
272                 return -ENOMEM;
273
274         list_for_each_entry (m, groups, nd) {
275                 struct evsel **metric_events;
276                 struct metric_ref *metric_refs = NULL;
277
278                 metric_events = calloc(sizeof(void *),
279                                 hashmap__size(&m->pctx.ids) + 1);
280                 if (!metric_events) {
281                         ret = -ENOMEM;
282                         break;
283                 }
284                 evsel = find_evsel_group(perf_evlist, &m->pctx,
285                                          metric_no_merge,
286                                          m->has_constraint, metric_events,
287                                          evlist_used);
288                 if (!evsel) {
289                         pr_debug("Cannot resolve %s: %s\n",
290                                         m->metric_name, m->metric_expr);
291                         free(metric_events);
292                         continue;
293                 }
294                 for (i = 0; metric_events[i]; i++)
295                         metric_events[i]->collect_stat = true;
296                 me = metricgroup__lookup(metric_events_list, evsel, true);
297                 if (!me) {
298                         ret = -ENOMEM;
299                         free(metric_events);
300                         break;
301                 }
302                 expr = malloc(sizeof(struct metric_expr));
303                 if (!expr) {
304                         ret = -ENOMEM;
305                         free(metric_events);
306                         break;
307                 }
308
309                 /*
310                  * Collect and store collected nested expressions
311                  * for metric processing.
312                  */
313                 if (m->metric_refs_cnt) {
314                         struct metric_ref_node *ref;
315
316                         metric_refs = zalloc(sizeof(struct metric_ref) * (m->metric_refs_cnt + 1));
317                         if (!metric_refs) {
318                                 ret = -ENOMEM;
319                                 free(metric_events);
320                                 free(expr);
321                                 break;
322                         }
323
324                         i = 0;
325                         list_for_each_entry(ref, &m->metric_refs, list) {
326                                 /*
327                                  * Intentionally passing just const char pointers,
328                                  * originally from 'struct pmu_event' object.
329                                  * We don't need to change them, so there's no
330                                  * need to create our own copy.
331                                  */
332                                 metric_refs[i].metric_name = ref->metric_name;
333                                 metric_refs[i].metric_expr = ref->metric_expr;
334                                 i++;
335                         }
336                 };
337
338                 expr->metric_refs = metric_refs;
339                 expr->metric_expr = m->metric_expr;
340                 expr->metric_name = m->metric_name;
341                 expr->metric_unit = m->metric_unit;
342                 expr->metric_events = metric_events;
343                 expr->runtime = m->runtime;
344                 list_add(&expr->nd, &me->head);
345         }
346
347         evlist__for_each_entry_safe(perf_evlist, tmp, evsel) {
348                 if (!test_bit(evsel->idx, evlist_used)) {
349                         evlist__remove(perf_evlist, evsel);
350                         evsel__delete(evsel);
351                 }
352         }
353         bitmap_free(evlist_used);
354
355         return ret;
356 }
357
358 static bool match_metric(const char *n, const char *list)
359 {
360         int len;
361         char *m;
362
363         if (!list)
364                 return false;
365         if (!strcmp(list, "all"))
366                 return true;
367         if (!n)
368                 return !strcasecmp(list, "No_group");
369         len = strlen(list);
370         m = strcasestr(n, list);
371         if (!m)
372                 return false;
373         if ((m == n || m[-1] == ';' || m[-1] == ' ') &&
374             (m[len] == 0 || m[len] == ';'))
375                 return true;
376         return false;
377 }
378
379 struct mep {
380         struct rb_node nd;
381         const char *name;
382         struct strlist *metrics;
383 };
384
385 static int mep_cmp(struct rb_node *rb_node, const void *entry)
386 {
387         struct mep *a = container_of(rb_node, struct mep, nd);
388         struct mep *b = (struct mep *)entry;
389
390         return strcmp(a->name, b->name);
391 }
392
393 static struct rb_node *mep_new(struct rblist *rl __maybe_unused,
394                                         const void *entry)
395 {
396         struct mep *me = malloc(sizeof(struct mep));
397
398         if (!me)
399                 return NULL;
400         memcpy(me, entry, sizeof(struct mep));
401         me->name = strdup(me->name);
402         if (!me->name)
403                 goto out_me;
404         me->metrics = strlist__new(NULL, NULL);
405         if (!me->metrics)
406                 goto out_name;
407         return &me->nd;
408 out_name:
409         zfree(&me->name);
410 out_me:
411         free(me);
412         return NULL;
413 }
414
415 static struct mep *mep_lookup(struct rblist *groups, const char *name)
416 {
417         struct rb_node *nd;
418         struct mep me = {
419                 .name = name
420         };
421         nd = rblist__find(groups, &me);
422         if (nd)
423                 return container_of(nd, struct mep, nd);
424         rblist__add_node(groups, &me);
425         nd = rblist__find(groups, &me);
426         if (nd)
427                 return container_of(nd, struct mep, nd);
428         return NULL;
429 }
430
431 static void mep_delete(struct rblist *rl __maybe_unused,
432                        struct rb_node *nd)
433 {
434         struct mep *me = container_of(nd, struct mep, nd);
435
436         strlist__delete(me->metrics);
437         zfree(&me->name);
438         free(me);
439 }
440
441 static void metricgroup__print_strlist(struct strlist *metrics, bool raw)
442 {
443         struct str_node *sn;
444         int n = 0;
445
446         strlist__for_each_entry (sn, metrics) {
447                 if (raw)
448                         printf("%s%s", n > 0 ? " " : "", sn->s);
449                 else
450                         printf("  %s\n", sn->s);
451                 n++;
452         }
453         if (raw)
454                 putchar('\n');
455 }
456
457 void metricgroup__print(bool metrics, bool metricgroups, char *filter,
458                         bool raw, bool details)
459 {
460         struct pmu_events_map *map = perf_pmu__find_map(NULL);
461         struct pmu_event *pe;
462         int i;
463         struct rblist groups;
464         struct rb_node *node, *next;
465         struct strlist *metriclist = NULL;
466
467         if (!map)
468                 return;
469
470         if (!metricgroups) {
471                 metriclist = strlist__new(NULL, NULL);
472                 if (!metriclist)
473                         return;
474         }
475
476         rblist__init(&groups);
477         groups.node_new = mep_new;
478         groups.node_cmp = mep_cmp;
479         groups.node_delete = mep_delete;
480         for (i = 0; ; i++) {
481                 const char *g;
482                 pe = &map->table[i];
483
484                 if (!pe->name && !pe->metric_group && !pe->metric_name)
485                         break;
486                 if (!pe->metric_expr)
487                         continue;
488                 g = pe->metric_group;
489                 if (!g && pe->metric_name) {
490                         if (pe->name)
491                                 continue;
492                         g = "No_group";
493                 }
494                 if (g) {
495                         char *omg;
496                         char *mg = strdup(g);
497
498                         if (!mg)
499                                 return;
500                         omg = mg;
501                         while ((g = strsep(&mg, ";")) != NULL) {
502                                 struct mep *me;
503                                 char *s;
504
505                                 g = skip_spaces(g);
506                                 if (*g == 0)
507                                         g = "No_group";
508                                 if (filter && !strstr(g, filter))
509                                         continue;
510                                 if (raw)
511                                         s = (char *)pe->metric_name;
512                                 else {
513                                         if (asprintf(&s, "%s\n%*s%s]",
514                                                      pe->metric_name, 8, "[", pe->desc) < 0)
515                                                 return;
516
517                                         if (details) {
518                                                 if (asprintf(&s, "%s\n%*s%s]",
519                                                              s, 8, "[", pe->metric_expr) < 0)
520                                                         return;
521                                         }
522                                 }
523
524                                 if (!s)
525                                         continue;
526
527                                 if (!metricgroups) {
528                                         strlist__add(metriclist, s);
529                                 } else {
530                                         me = mep_lookup(&groups, g);
531                                         if (!me)
532                                                 continue;
533                                         strlist__add(me->metrics, s);
534                                 }
535
536                                 if (!raw)
537                                         free(s);
538                         }
539                         free(omg);
540                 }
541         }
542
543         if (metricgroups && !raw)
544                 printf("\nMetric Groups:\n\n");
545         else if (metrics && !raw)
546                 printf("\nMetrics:\n\n");
547
548         for (node = rb_first_cached(&groups.entries); node; node = next) {
549                 struct mep *me = container_of(node, struct mep, nd);
550
551                 if (metricgroups)
552                         printf("%s%s%s", me->name, metrics && !raw ? ":" : "", raw ? " " : "\n");
553                 if (metrics)
554                         metricgroup__print_strlist(me->metrics, raw);
555                 next = rb_next(node);
556                 rblist__remove_node(&groups, node);
557         }
558         if (!metricgroups)
559                 metricgroup__print_strlist(metriclist, raw);
560         strlist__delete(metriclist);
561 }
562
563 static void metricgroup__add_metric_weak_group(struct strbuf *events,
564                                                struct expr_parse_ctx *ctx)
565 {
566         struct hashmap_entry *cur;
567         size_t bkt;
568         bool no_group = true, has_duration = false;
569
570         hashmap__for_each_entry((&ctx->ids), cur, bkt) {
571                 pr_debug("found event %s\n", (const char *)cur->key);
572                 /*
573                  * Duration time maps to a software event and can make
574                  * groups not count. Always use it outside a
575                  * group.
576                  */
577                 if (!strcmp(cur->key, "duration_time")) {
578                         has_duration = true;
579                         continue;
580                 }
581                 strbuf_addf(events, "%s%s",
582                         no_group ? "{" : ",",
583                         (const char *)cur->key);
584                 no_group = false;
585         }
586         if (!no_group) {
587                 strbuf_addf(events, "}:W");
588                 if (has_duration)
589                         strbuf_addf(events, ",duration_time");
590         } else if (has_duration)
591                 strbuf_addf(events, "duration_time");
592 }
593
594 static void metricgroup__add_metric_non_group(struct strbuf *events,
595                                               struct expr_parse_ctx *ctx)
596 {
597         struct hashmap_entry *cur;
598         size_t bkt;
599         bool first = true;
600
601         hashmap__for_each_entry((&ctx->ids), cur, bkt) {
602                 if (!first)
603                         strbuf_addf(events, ",");
604                 strbuf_addf(events, "%s", (const char *)cur->key);
605                 first = false;
606         }
607 }
608
609 static void metricgroup___watchdog_constraint_hint(const char *name, bool foot)
610 {
611         static bool violate_nmi_constraint;
612
613         if (!foot) {
614                 pr_warning("Splitting metric group %s into standalone metrics.\n", name);
615                 violate_nmi_constraint = true;
616                 return;
617         }
618
619         if (!violate_nmi_constraint)
620                 return;
621
622         pr_warning("Try disabling the NMI watchdog to comply NO_NMI_WATCHDOG metric constraint:\n"
623                    "    echo 0 > /proc/sys/kernel/nmi_watchdog\n"
624                    "    perf stat ...\n"
625                    "    echo 1 > /proc/sys/kernel/nmi_watchdog\n");
626 }
627
628 static bool metricgroup__has_constraint(struct pmu_event *pe)
629 {
630         if (!pe->metric_constraint)
631                 return false;
632
633         if (!strcmp(pe->metric_constraint, "NO_NMI_WATCHDOG") &&
634             sysctl__nmi_watchdog_enabled()) {
635                 metricgroup___watchdog_constraint_hint(pe->metric_name, false);
636                 return true;
637         }
638
639         return false;
640 }
641
642 int __weak arch_get_runtimeparam(void)
643 {
644         return 1;
645 }
646
647 static int __add_metric(struct list_head *metric_list,
648                         struct pmu_event *pe,
649                         bool metric_no_group,
650                         int runtime,
651                         struct metric **mp,
652                         struct expr_id *parent,
653                         struct expr_ids *ids)
654 {
655         struct metric_ref_node *ref;
656         struct metric *m;
657
658         if (*mp == NULL) {
659                 /*
660                  * We got in here for the parent group,
661                  * allocate it and put it on the list.
662                  */
663                 m = zalloc(sizeof(*m));
664                 if (!m)
665                         return -ENOMEM;
666
667                 expr__ctx_init(&m->pctx);
668                 m->metric_name = pe->metric_name;
669                 m->metric_expr = pe->metric_expr;
670                 m->metric_unit = pe->unit;
671                 m->runtime = runtime;
672                 m->has_constraint = metric_no_group || metricgroup__has_constraint(pe);
673                 INIT_LIST_HEAD(&m->metric_refs);
674                 m->metric_refs_cnt = 0;
675                 *mp = m;
676
677                 parent = expr_ids__alloc(ids);
678                 if (!parent) {
679                         free(m);
680                         return -EINVAL;
681                 }
682
683                 parent->id = strdup(pe->metric_name);
684                 if (!parent->id) {
685                         free(m);
686                         return -ENOMEM;
687                 }
688         } else {
689                 /*
690                  * We got here for the referenced metric, via the
691                  * recursive metricgroup__add_metric call, add
692                  * it to the parent group.
693                  */
694                 m = *mp;
695
696                 ref = malloc(sizeof(*ref));
697                 if (!ref)
698                         return -ENOMEM;
699
700                 /*
701                  * Intentionally passing just const char pointers,
702                  * from 'pe' object, so they never go away. We don't
703                  * need to change them, so there's no need to create
704                  * our own copy.
705                  */
706                 ref->metric_name = pe->metric_name;
707                 ref->metric_expr = pe->metric_expr;
708
709                 list_add(&ref->list, &m->metric_refs);
710                 m->metric_refs_cnt++;
711         }
712
713         /* Force all found IDs in metric to have us as parent ID. */
714         WARN_ON_ONCE(!parent);
715         m->pctx.parent = parent;
716
717         /*
718          * For both the parent and referenced metrics, we parse
719          * all the metric's IDs and add it to the parent context.
720          */
721         if (expr__find_other(pe->metric_expr, NULL, &m->pctx, runtime) < 0) {
722                 expr__ctx_clear(&m->pctx);
723                 free(m);
724                 return -EINVAL;
725         }
726
727         /*
728          * We add new group only in the 'parent' call,
729          * so bail out for referenced metric case.
730          */
731         if (m->metric_refs_cnt)
732                 return 0;
733
734         if (list_empty(metric_list))
735                 list_add(&m->nd, metric_list);
736         else {
737                 struct list_head *pos;
738
739                 /* Place the largest groups at the front. */
740                 list_for_each_prev(pos, metric_list) {
741                         struct metric *old = list_entry(pos, struct metric, nd);
742
743                         if (hashmap__size(&m->pctx.ids) <=
744                             hashmap__size(&old->pctx.ids))
745                                 break;
746                 }
747                 list_add(&m->nd, pos);
748         }
749
750         return 0;
751 }
752
753 #define map_for_each_event(__pe, __idx, __map)                          \
754         for (__idx = 0, __pe = &__map->table[__idx];                    \
755              __pe->name || __pe->metric_group || __pe->metric_name;     \
756              __pe = &__map->table[++__idx])
757
758 #define map_for_each_metric(__pe, __idx, __map, __metric)               \
759         map_for_each_event(__pe, __idx, __map)                          \
760                 if (__pe->metric_expr &&                                \
761                     (match_metric(__pe->metric_group, __metric) ||      \
762                      match_metric(__pe->metric_name, __metric)))
763
764 static struct pmu_event *find_metric(const char *metric, struct pmu_events_map *map)
765 {
766         struct pmu_event *pe;
767         int i;
768
769         map_for_each_event(pe, i, map) {
770                 if (match_metric(pe->metric_name, metric))
771                         return pe;
772         }
773
774         return NULL;
775 }
776
777 static int recursion_check(struct metric *m, const char *id, struct expr_id **parent,
778                            struct expr_ids *ids)
779 {
780         struct expr_id_data *data;
781         struct expr_id *p;
782         int ret;
783
784         /*
785          * We get the parent referenced by 'id' argument and
786          * traverse through all the parent object IDs to check
787          * if we already processed 'id', if we did, it's recursion
788          * and we fail.
789          */
790         ret = expr__get_id(&m->pctx, id, &data);
791         if (ret)
792                 return ret;
793
794         p = data->parent;
795
796         while (p->parent) {
797                 if (!strcmp(p->id, id)) {
798                         pr_err("failed: recursion detected for %s\n", id);
799                         return -1;
800                 }
801                 p = p->parent;
802         }
803
804         /*
805          * If we are over the limit of static entris, the metric
806          * is too difficult/nested to process, fail as well.
807          */
808         p = expr_ids__alloc(ids);
809         if (!p) {
810                 pr_err("failed: too many nested metrics\n");
811                 return -EINVAL;
812         }
813
814         p->id     = strdup(id);
815         p->parent = data->parent;
816         *parent   = p;
817
818         return p->id ? 0 : -ENOMEM;
819 }
820
821 static int add_metric(struct list_head *metric_list,
822                       struct pmu_event *pe,
823                       bool metric_no_group,
824                       struct metric **mp,
825                       struct expr_id *parent,
826                       struct expr_ids *ids);
827
828 static int __resolve_metric(struct metric *m,
829                             bool metric_no_group,
830                             struct list_head *metric_list,
831                             struct pmu_events_map *map,
832                             struct expr_ids *ids)
833 {
834         struct hashmap_entry *cur;
835         size_t bkt;
836         bool all;
837         int ret;
838
839         /*
840          * Iterate all the parsed IDs and if there's metric,
841          * add it to the context.
842          */
843         do {
844                 all = true;
845                 hashmap__for_each_entry((&m->pctx.ids), cur, bkt) {
846                         struct expr_id *parent;
847                         struct pmu_event *pe;
848
849                         pe = find_metric(cur->key, map);
850                         if (!pe)
851                                 continue;
852
853                         ret = recursion_check(m, cur->key, &parent, ids);
854                         if (ret)
855                                 return ret;
856
857                         all = false;
858                         /* The metric key itself needs to go out.. */
859                         expr__del_id(&m->pctx, cur->key);
860
861                         /* ... and it gets resolved to the parent context. */
862                         ret = add_metric(metric_list, pe, metric_no_group, &m, parent, ids);
863                         if (ret)
864                                 return ret;
865
866                         /*
867                          * We added new metric to hashmap, so we need
868                          * to break the iteration and start over.
869                          */
870                         break;
871                 }
872         } while (!all);
873
874         return 0;
875 }
876
877 static int resolve_metric(bool metric_no_group,
878                           struct list_head *metric_list,
879                           struct pmu_events_map *map,
880                           struct expr_ids *ids)
881 {
882         struct metric *m;
883         int err;
884
885         list_for_each_entry(m, metric_list, nd) {
886                 err = __resolve_metric(m, metric_no_group, metric_list, map, ids);
887                 if (err)
888                         return err;
889         }
890         return 0;
891 }
892
893 static int add_metric(struct list_head *metric_list,
894                       struct pmu_event *pe,
895                       bool metric_no_group,
896                       struct metric **m,
897                       struct expr_id *parent,
898                       struct expr_ids *ids)
899 {
900         struct metric *orig = *m;
901         int ret = 0;
902
903         pr_debug("metric expr %s for %s\n", pe->metric_expr, pe->metric_name);
904
905         if (!strstr(pe->metric_expr, "?")) {
906                 ret = __add_metric(metric_list, pe, metric_no_group, 1, m, parent, ids);
907         } else {
908                 int j, count;
909
910                 count = arch_get_runtimeparam();
911
912                 /* This loop is added to create multiple
913                  * events depend on count value and add
914                  * those events to metric_list.
915                  */
916
917                 for (j = 0; j < count && !ret; j++, *m = orig)
918                         ret = __add_metric(metric_list, pe, metric_no_group, j, m, parent, ids);
919         }
920
921         return ret;
922 }
923
924 static int metricgroup__add_metric(const char *metric, bool metric_no_group,
925                                    struct strbuf *events,
926                                    struct list_head *metric_list,
927                                    struct pmu_events_map *map)
928 {
929         struct expr_ids ids = { .cnt = 0, };
930         struct pmu_event *pe;
931         struct metric *m;
932         LIST_HEAD(list);
933         int i, ret;
934         bool has_match = false;
935
936         map_for_each_metric(pe, i, map, metric) {
937                 has_match = true;
938                 m = NULL;
939
940                 ret = add_metric(&list, pe, metric_no_group, &m, NULL, &ids);
941                 if (ret)
942                         goto out;
943
944                 /*
945                  * Process any possible referenced metrics
946                  * included in the expression.
947                  */
948                 ret = resolve_metric(metric_no_group,
949                                      &list, map, &ids);
950                 if (ret)
951                         goto out;
952         }
953
954         /* End of pmu events. */
955         if (!has_match) {
956                 ret = -EINVAL;
957                 goto out;
958         }
959
960         list_for_each_entry(m, &list, nd) {
961                 if (events->len > 0)
962                         strbuf_addf(events, ",");
963
964                 if (m->has_constraint) {
965                         metricgroup__add_metric_non_group(events,
966                                                           &m->pctx);
967                 } else {
968                         metricgroup__add_metric_weak_group(events,
969                                                            &m->pctx);
970                 }
971         }
972
973 out:
974         /*
975          * add to metric_list so that they can be released
976          * even if it's failed
977          */
978         list_splice(&list, metric_list);
979         expr_ids__exit(&ids);
980         return ret;
981 }
982
983 static int metricgroup__add_metric_list(const char *list, bool metric_no_group,
984                                         struct strbuf *events,
985                                         struct list_head *metric_list,
986                                         struct pmu_events_map *map)
987 {
988         char *llist, *nlist, *p;
989         int ret = -EINVAL;
990
991         nlist = strdup(list);
992         if (!nlist)
993                 return -ENOMEM;
994         llist = nlist;
995
996         strbuf_init(events, 100);
997         strbuf_addf(events, "%s", "");
998
999         while ((p = strsep(&llist, ",")) != NULL) {
1000                 ret = metricgroup__add_metric(p, metric_no_group, events,
1001                                               metric_list, map);
1002                 if (ret == -EINVAL) {
1003                         fprintf(stderr, "Cannot find metric or group `%s'\n",
1004                                         p);
1005                         break;
1006                 }
1007         }
1008         free(nlist);
1009
1010         if (!ret)
1011                 metricgroup___watchdog_constraint_hint(NULL, true);
1012
1013         return ret;
1014 }
1015
1016 static void metric__free_refs(struct metric *metric)
1017 {
1018         struct metric_ref_node *ref, *tmp;
1019
1020         list_for_each_entry_safe(ref, tmp, &metric->metric_refs, list) {
1021                 list_del(&ref->list);
1022                 free(ref);
1023         }
1024 }
1025
1026 static void metricgroup__free_metrics(struct list_head *metric_list)
1027 {
1028         struct metric *m, *tmp;
1029
1030         list_for_each_entry_safe (m, tmp, metric_list, nd) {
1031                 metric__free_refs(m);
1032                 expr__ctx_clear(&m->pctx);
1033                 list_del_init(&m->nd);
1034                 free(m);
1035         }
1036 }
1037
1038 static int parse_groups(struct evlist *perf_evlist, const char *str,
1039                         bool metric_no_group,
1040                         bool metric_no_merge,
1041                         struct perf_pmu *fake_pmu,
1042                         struct rblist *metric_events,
1043                         struct pmu_events_map *map)
1044 {
1045         struct parse_events_error parse_error;
1046         struct strbuf extra_events;
1047         LIST_HEAD(metric_list);
1048         int ret;
1049
1050         if (metric_events->nr_entries == 0)
1051                 metricgroup__rblist_init(metric_events);
1052         ret = metricgroup__add_metric_list(str, metric_no_group,
1053                                            &extra_events, &metric_list, map);
1054         if (ret)
1055                 goto out;
1056         pr_debug("adding %s\n", extra_events.buf);
1057         bzero(&parse_error, sizeof(parse_error));
1058         ret = __parse_events(perf_evlist, extra_events.buf, &parse_error, fake_pmu);
1059         if (ret) {
1060                 parse_events_print_error(&parse_error, extra_events.buf);
1061                 goto out;
1062         }
1063         ret = metricgroup__setup_events(&metric_list, metric_no_merge,
1064                                         perf_evlist, metric_events);
1065 out:
1066         metricgroup__free_metrics(&metric_list);
1067         strbuf_release(&extra_events);
1068         return ret;
1069 }
1070
1071 int metricgroup__parse_groups(const struct option *opt,
1072                               const char *str,
1073                               bool metric_no_group,
1074                               bool metric_no_merge,
1075                               struct rblist *metric_events)
1076 {
1077         struct evlist *perf_evlist = *(struct evlist **)opt->value;
1078         struct pmu_events_map *map = perf_pmu__find_map(NULL);
1079
1080         if (!map)
1081                 return 0;
1082
1083         return parse_groups(perf_evlist, str, metric_no_group,
1084                             metric_no_merge, NULL, metric_events, map);
1085 }
1086
1087 int metricgroup__parse_groups_test(struct evlist *evlist,
1088                                    struct pmu_events_map *map,
1089                                    const char *str,
1090                                    bool metric_no_group,
1091                                    bool metric_no_merge,
1092                                    struct rblist *metric_events)
1093 {
1094         return parse_groups(evlist, str, metric_no_group,
1095                             metric_no_merge, &perf_pmu__fake, metric_events, map);
1096 }
1097
1098 bool metricgroup__has_metric(const char *metric)
1099 {
1100         struct pmu_events_map *map = perf_pmu__find_map(NULL);
1101         struct pmu_event *pe;
1102         int i;
1103
1104         if (!map)
1105                 return false;
1106
1107         for (i = 0; ; i++) {
1108                 pe = &map->table[i];
1109
1110                 if (!pe->name && !pe->metric_group && !pe->metric_name)
1111                         break;
1112                 if (!pe->metric_expr)
1113                         continue;
1114                 if (match_metric(pe->metric_name, metric))
1115                         return true;
1116         }
1117         return false;
1118 }