GNU Linux-libre 4.19.211-gnu1
[releases.git] / tools / perf / util / bpf-loader.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * bpf-loader.c
4  *
5  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
6  * Copyright (C) 2015 Huawei Inc.
7  */
8
9 #include <linux/bpf.h>
10 #include <bpf/libbpf.h>
11 #include <bpf/bpf.h>
12 #include <linux/err.h>
13 #include <linux/kernel.h>
14 #include <linux/string.h>
15 #include <errno.h>
16 #include "perf.h"
17 #include "debug.h"
18 #include "bpf-loader.h"
19 #include "bpf-prologue.h"
20 #include "probe-event.h"
21 #include "probe-finder.h" // for MAX_PROBES
22 #include "parse-events.h"
23 #include "strfilter.h"
24 #include "llvm-utils.h"
25 #include "c++/clang-c.h"
26
27 #define DEFINE_PRINT_FN(name, level) \
28 static int libbpf_##name(const char *fmt, ...)  \
29 {                                               \
30         va_list args;                           \
31         int ret;                                \
32                                                 \
33         va_start(args, fmt);                    \
34         ret = veprintf(level, verbose, pr_fmt(fmt), args);\
35         va_end(args);                           \
36         return ret;                             \
37 }
38
39 DEFINE_PRINT_FN(warning, 1)
40 DEFINE_PRINT_FN(info, 1)
41 DEFINE_PRINT_FN(debug, 1)
42
43 struct bpf_prog_priv {
44         bool is_tp;
45         char *sys_name;
46         char *evt_name;
47         struct perf_probe_event pev;
48         bool need_prologue;
49         struct bpf_insn *insns_buf;
50         int nr_types;
51         int *type_mapping;
52 };
53
54 static bool libbpf_initialized;
55
56 struct bpf_object *
57 bpf__prepare_load_buffer(void *obj_buf, size_t obj_buf_sz, const char *name)
58 {
59         struct bpf_object *obj;
60
61         if (!libbpf_initialized) {
62                 libbpf_set_print(libbpf_warning,
63                                  libbpf_info,
64                                  libbpf_debug);
65                 libbpf_initialized = true;
66         }
67
68         obj = bpf_object__open_buffer(obj_buf, obj_buf_sz, name);
69         if (IS_ERR_OR_NULL(obj)) {
70                 pr_debug("bpf: failed to load buffer\n");
71                 return ERR_PTR(-EINVAL);
72         }
73
74         return obj;
75 }
76
77 struct bpf_object *bpf__prepare_load(const char *filename, bool source)
78 {
79         struct bpf_object *obj;
80
81         if (!libbpf_initialized) {
82                 libbpf_set_print(libbpf_warning,
83                                  libbpf_info,
84                                  libbpf_debug);
85                 libbpf_initialized = true;
86         }
87
88         if (source) {
89                 int err;
90                 void *obj_buf;
91                 size_t obj_buf_sz;
92
93                 perf_clang__init();
94                 err = perf_clang__compile_bpf(filename, &obj_buf, &obj_buf_sz);
95                 perf_clang__cleanup();
96                 if (err) {
97                         pr_debug("bpf: builtin compilation failed: %d, try external compiler\n", err);
98                         err = llvm__compile_bpf(filename, &obj_buf, &obj_buf_sz);
99                         if (err)
100                                 return ERR_PTR(-BPF_LOADER_ERRNO__COMPILE);
101                 } else
102                         pr_debug("bpf: successfull builtin compilation\n");
103                 obj = bpf_object__open_buffer(obj_buf, obj_buf_sz, filename);
104
105                 if (!IS_ERR_OR_NULL(obj) && llvm_param.dump_obj)
106                         llvm__dump_obj(filename, obj_buf, obj_buf_sz);
107
108                 free(obj_buf);
109         } else
110                 obj = bpf_object__open(filename);
111
112         if (IS_ERR_OR_NULL(obj)) {
113                 pr_debug("bpf: failed to load %s\n", filename);
114                 return obj;
115         }
116
117         return obj;
118 }
119
120 void bpf__clear(void)
121 {
122         struct bpf_object *obj, *tmp;
123
124         bpf_object__for_each_safe(obj, tmp) {
125                 bpf__unprobe(obj);
126                 bpf_object__close(obj);
127         }
128 }
129
130 static void
131 clear_prog_priv(struct bpf_program *prog __maybe_unused,
132                 void *_priv)
133 {
134         struct bpf_prog_priv *priv = _priv;
135
136         cleanup_perf_probe_events(&priv->pev, 1);
137         zfree(&priv->insns_buf);
138         zfree(&priv->type_mapping);
139         zfree(&priv->sys_name);
140         zfree(&priv->evt_name);
141         free(priv);
142 }
143
144 static int
145 prog_config__exec(const char *value, struct perf_probe_event *pev)
146 {
147         pev->uprobes = true;
148         pev->target = strdup(value);
149         if (!pev->target)
150                 return -ENOMEM;
151         return 0;
152 }
153
154 static int
155 prog_config__module(const char *value, struct perf_probe_event *pev)
156 {
157         pev->uprobes = false;
158         pev->target = strdup(value);
159         if (!pev->target)
160                 return -ENOMEM;
161         return 0;
162 }
163
164 static int
165 prog_config__bool(const char *value, bool *pbool, bool invert)
166 {
167         int err;
168         bool bool_value;
169
170         if (!pbool)
171                 return -EINVAL;
172
173         err = strtobool(value, &bool_value);
174         if (err)
175                 return err;
176
177         *pbool = invert ? !bool_value : bool_value;
178         return 0;
179 }
180
181 static int
182 prog_config__inlines(const char *value,
183                      struct perf_probe_event *pev __maybe_unused)
184 {
185         return prog_config__bool(value, &probe_conf.no_inlines, true);
186 }
187
188 static int
189 prog_config__force(const char *value,
190                    struct perf_probe_event *pev __maybe_unused)
191 {
192         return prog_config__bool(value, &probe_conf.force_add, false);
193 }
194
195 static struct {
196         const char *key;
197         const char *usage;
198         const char *desc;
199         int (*func)(const char *, struct perf_probe_event *);
200 } bpf_prog_config_terms[] = {
201         {
202                 .key    = "exec",
203                 .usage  = "exec=<full path of file>",
204                 .desc   = "Set uprobe target",
205                 .func   = prog_config__exec,
206         },
207         {
208                 .key    = "module",
209                 .usage  = "module=<module name>    ",
210                 .desc   = "Set kprobe module",
211                 .func   = prog_config__module,
212         },
213         {
214                 .key    = "inlines",
215                 .usage  = "inlines=[yes|no]        ",
216                 .desc   = "Probe at inline symbol",
217                 .func   = prog_config__inlines,
218         },
219         {
220                 .key    = "force",
221                 .usage  = "force=[yes|no]          ",
222                 .desc   = "Forcibly add events with existing name",
223                 .func   = prog_config__force,
224         },
225 };
226
227 static int
228 do_prog_config(const char *key, const char *value,
229                struct perf_probe_event *pev)
230 {
231         unsigned int i;
232
233         pr_debug("config bpf program: %s=%s\n", key, value);
234         for (i = 0; i < ARRAY_SIZE(bpf_prog_config_terms); i++)
235                 if (strcmp(key, bpf_prog_config_terms[i].key) == 0)
236                         return bpf_prog_config_terms[i].func(value, pev);
237
238         pr_debug("BPF: ERROR: invalid program config option: %s=%s\n",
239                  key, value);
240
241         pr_debug("\nHint: Valid options are:\n");
242         for (i = 0; i < ARRAY_SIZE(bpf_prog_config_terms); i++)
243                 pr_debug("\t%s:\t%s\n", bpf_prog_config_terms[i].usage,
244                          bpf_prog_config_terms[i].desc);
245         pr_debug("\n");
246
247         return -BPF_LOADER_ERRNO__PROGCONF_TERM;
248 }
249
250 static const char *
251 parse_prog_config_kvpair(const char *config_str, struct perf_probe_event *pev)
252 {
253         char *text = strdup(config_str);
254         char *sep, *line;
255         const char *main_str = NULL;
256         int err = 0;
257
258         if (!text) {
259                 pr_debug("Not enough memory: dup config_str failed\n");
260                 return ERR_PTR(-ENOMEM);
261         }
262
263         line = text;
264         while ((sep = strchr(line, ';'))) {
265                 char *equ;
266
267                 *sep = '\0';
268                 equ = strchr(line, '=');
269                 if (!equ) {
270                         pr_warning("WARNING: invalid config in BPF object: %s\n",
271                                    line);
272                         pr_warning("\tShould be 'key=value'.\n");
273                         goto nextline;
274                 }
275                 *equ = '\0';
276
277                 err = do_prog_config(line, equ + 1, pev);
278                 if (err)
279                         break;
280 nextline:
281                 line = sep + 1;
282         }
283
284         if (!err)
285                 main_str = config_str + (line - text);
286         free(text);
287
288         return err ? ERR_PTR(err) : main_str;
289 }
290
291 static int
292 parse_prog_config(const char *config_str, const char **p_main_str,
293                   bool *is_tp, struct perf_probe_event *pev)
294 {
295         int err;
296         const char *main_str = parse_prog_config_kvpair(config_str, pev);
297
298         if (IS_ERR(main_str))
299                 return PTR_ERR(main_str);
300
301         *p_main_str = main_str;
302         if (!strchr(main_str, '=')) {
303                 /* Is a tracepoint event? */
304                 const char *s = strchr(main_str, ':');
305
306                 if (!s) {
307                         pr_debug("bpf: '%s' is not a valid tracepoint\n",
308                                  config_str);
309                         return -BPF_LOADER_ERRNO__CONFIG;
310                 }
311
312                 *is_tp = true;
313                 return 0;
314         }
315
316         *is_tp = false;
317         err = parse_perf_probe_command(main_str, pev);
318         if (err < 0) {
319                 pr_debug("bpf: '%s' is not a valid config string\n",
320                          config_str);
321                 /* parse failed, don't need clear pev. */
322                 return -BPF_LOADER_ERRNO__CONFIG;
323         }
324         return 0;
325 }
326
327 static int
328 config_bpf_program(struct bpf_program *prog)
329 {
330         struct perf_probe_event *pev = NULL;
331         struct bpf_prog_priv *priv = NULL;
332         const char *config_str, *main_str;
333         bool is_tp = false;
334         int err;
335
336         /* Initialize per-program probing setting */
337         probe_conf.no_inlines = false;
338         probe_conf.force_add = false;
339
340         config_str = bpf_program__title(prog, false);
341         if (IS_ERR(config_str)) {
342                 pr_debug("bpf: unable to get title for program\n");
343                 return PTR_ERR(config_str);
344         }
345
346         priv = calloc(sizeof(*priv), 1);
347         if (!priv) {
348                 pr_debug("bpf: failed to alloc priv\n");
349                 return -ENOMEM;
350         }
351         pev = &priv->pev;
352
353         pr_debug("bpf: config program '%s'\n", config_str);
354         err = parse_prog_config(config_str, &main_str, &is_tp, pev);
355         if (err)
356                 goto errout;
357
358         if (is_tp) {
359                 char *s = strchr(main_str, ':');
360
361                 priv->is_tp = true;
362                 priv->sys_name = strndup(main_str, s - main_str);
363                 priv->evt_name = strdup(s + 1);
364                 goto set_priv;
365         }
366
367         if (pev->group && strcmp(pev->group, PERF_BPF_PROBE_GROUP)) {
368                 pr_debug("bpf: '%s': group for event is set and not '%s'.\n",
369                          config_str, PERF_BPF_PROBE_GROUP);
370                 err = -BPF_LOADER_ERRNO__GROUP;
371                 goto errout;
372         } else if (!pev->group)
373                 pev->group = strdup(PERF_BPF_PROBE_GROUP);
374
375         if (!pev->group) {
376                 pr_debug("bpf: strdup failed\n");
377                 err = -ENOMEM;
378                 goto errout;
379         }
380
381         if (!pev->event) {
382                 pr_debug("bpf: '%s': event name is missing. Section name should be 'key=value'\n",
383                          config_str);
384                 err = -BPF_LOADER_ERRNO__EVENTNAME;
385                 goto errout;
386         }
387         pr_debug("bpf: config '%s' is ok\n", config_str);
388
389 set_priv:
390         err = bpf_program__set_priv(prog, priv, clear_prog_priv);
391         if (err) {
392                 pr_debug("Failed to set priv for program '%s'\n", config_str);
393                 goto errout;
394         }
395
396         return 0;
397
398 errout:
399         if (pev)
400                 clear_perf_probe_event(pev);
401         free(priv);
402         return err;
403 }
404
405 static int bpf__prepare_probe(void)
406 {
407         static int err = 0;
408         static bool initialized = false;
409
410         /*
411          * Make err static, so if init failed the first, bpf__prepare_probe()
412          * fails each time without calling init_probe_symbol_maps multiple
413          * times.
414          */
415         if (initialized)
416                 return err;
417
418         initialized = true;
419         err = init_probe_symbol_maps(false);
420         if (err < 0)
421                 pr_debug("Failed to init_probe_symbol_maps\n");
422         probe_conf.max_probes = MAX_PROBES;
423         return err;
424 }
425
426 static int
427 preproc_gen_prologue(struct bpf_program *prog, int n,
428                      struct bpf_insn *orig_insns, int orig_insns_cnt,
429                      struct bpf_prog_prep_result *res)
430 {
431         struct bpf_prog_priv *priv = bpf_program__priv(prog);
432         struct probe_trace_event *tev;
433         struct perf_probe_event *pev;
434         struct bpf_insn *buf;
435         size_t prologue_cnt = 0;
436         int i, err;
437
438         if (IS_ERR(priv) || !priv || priv->is_tp)
439                 goto errout;
440
441         pev = &priv->pev;
442
443         if (n < 0 || n >= priv->nr_types)
444                 goto errout;
445
446         /* Find a tev belongs to that type */
447         for (i = 0; i < pev->ntevs; i++) {
448                 if (priv->type_mapping[i] == n)
449                         break;
450         }
451
452         if (i >= pev->ntevs) {
453                 pr_debug("Internal error: prologue type %d not found\n", n);
454                 return -BPF_LOADER_ERRNO__PROLOGUE;
455         }
456
457         tev = &pev->tevs[i];
458
459         buf = priv->insns_buf;
460         err = bpf__gen_prologue(tev->args, tev->nargs,
461                                 buf, &prologue_cnt,
462                                 BPF_MAXINSNS - orig_insns_cnt);
463         if (err) {
464                 const char *title;
465
466                 title = bpf_program__title(prog, false);
467                 if (!title)
468                         title = "[unknown]";
469
470                 pr_debug("Failed to generate prologue for program %s\n",
471                          title);
472                 return err;
473         }
474
475         memcpy(&buf[prologue_cnt], orig_insns,
476                sizeof(struct bpf_insn) * orig_insns_cnt);
477
478         res->new_insn_ptr = buf;
479         res->new_insn_cnt = prologue_cnt + orig_insns_cnt;
480         res->pfd = NULL;
481         return 0;
482
483 errout:
484         pr_debug("Internal error in preproc_gen_prologue\n");
485         return -BPF_LOADER_ERRNO__PROLOGUE;
486 }
487
488 /*
489  * compare_tev_args is reflexive, transitive and antisymmetric.
490  * I can proof it but this margin is too narrow to contain.
491  */
492 static int compare_tev_args(const void *ptev1, const void *ptev2)
493 {
494         int i, ret;
495         const struct probe_trace_event *tev1 =
496                 *(const struct probe_trace_event **)ptev1;
497         const struct probe_trace_event *tev2 =
498                 *(const struct probe_trace_event **)ptev2;
499
500         ret = tev2->nargs - tev1->nargs;
501         if (ret)
502                 return ret;
503
504         for (i = 0; i < tev1->nargs; i++) {
505                 struct probe_trace_arg *arg1, *arg2;
506                 struct probe_trace_arg_ref *ref1, *ref2;
507
508                 arg1 = &tev1->args[i];
509                 arg2 = &tev2->args[i];
510
511                 ret = strcmp(arg1->value, arg2->value);
512                 if (ret)
513                         return ret;
514
515                 ref1 = arg1->ref;
516                 ref2 = arg2->ref;
517
518                 while (ref1 && ref2) {
519                         ret = ref2->offset - ref1->offset;
520                         if (ret)
521                                 return ret;
522
523                         ref1 = ref1->next;
524                         ref2 = ref2->next;
525                 }
526
527                 if (ref1 || ref2)
528                         return ref2 ? 1 : -1;
529         }
530
531         return 0;
532 }
533
534 /*
535  * Assign a type number to each tevs in a pev.
536  * mapping is an array with same slots as tevs in that pev.
537  * nr_types will be set to number of types.
538  */
539 static int map_prologue(struct perf_probe_event *pev, int *mapping,
540                         int *nr_types)
541 {
542         int i, type = 0;
543         struct probe_trace_event **ptevs;
544
545         size_t array_sz = sizeof(*ptevs) * pev->ntevs;
546
547         ptevs = malloc(array_sz);
548         if (!ptevs) {
549                 pr_debug("Not enough memory: alloc ptevs failed\n");
550                 return -ENOMEM;
551         }
552
553         pr_debug("In map_prologue, ntevs=%d\n", pev->ntevs);
554         for (i = 0; i < pev->ntevs; i++)
555                 ptevs[i] = &pev->tevs[i];
556
557         qsort(ptevs, pev->ntevs, sizeof(*ptevs),
558               compare_tev_args);
559
560         for (i = 0; i < pev->ntevs; i++) {
561                 int n;
562
563                 n = ptevs[i] - pev->tevs;
564                 if (i == 0) {
565                         mapping[n] = type;
566                         pr_debug("mapping[%d]=%d\n", n, type);
567                         continue;
568                 }
569
570                 if (compare_tev_args(ptevs + i, ptevs + i - 1) == 0)
571                         mapping[n] = type;
572                 else
573                         mapping[n] = ++type;
574
575                 pr_debug("mapping[%d]=%d\n", n, mapping[n]);
576         }
577         free(ptevs);
578         *nr_types = type + 1;
579
580         return 0;
581 }
582
583 static int hook_load_preprocessor(struct bpf_program *prog)
584 {
585         struct bpf_prog_priv *priv = bpf_program__priv(prog);
586         struct perf_probe_event *pev;
587         bool need_prologue = false;
588         int err, i;
589
590         if (IS_ERR(priv) || !priv) {
591                 pr_debug("Internal error when hook preprocessor\n");
592                 return -BPF_LOADER_ERRNO__INTERNAL;
593         }
594
595         if (priv->is_tp) {
596                 priv->need_prologue = false;
597                 return 0;
598         }
599
600         pev = &priv->pev;
601         for (i = 0; i < pev->ntevs; i++) {
602                 struct probe_trace_event *tev = &pev->tevs[i];
603
604                 if (tev->nargs > 0) {
605                         need_prologue = true;
606                         break;
607                 }
608         }
609
610         /*
611          * Since all tevs don't have argument, we don't need generate
612          * prologue.
613          */
614         if (!need_prologue) {
615                 priv->need_prologue = false;
616                 return 0;
617         }
618
619         priv->need_prologue = true;
620         priv->insns_buf = malloc(sizeof(struct bpf_insn) * BPF_MAXINSNS);
621         if (!priv->insns_buf) {
622                 pr_debug("Not enough memory: alloc insns_buf failed\n");
623                 return -ENOMEM;
624         }
625
626         priv->type_mapping = malloc(sizeof(int) * pev->ntevs);
627         if (!priv->type_mapping) {
628                 pr_debug("Not enough memory: alloc type_mapping failed\n");
629                 return -ENOMEM;
630         }
631         memset(priv->type_mapping, -1,
632                sizeof(int) * pev->ntevs);
633
634         err = map_prologue(pev, priv->type_mapping, &priv->nr_types);
635         if (err)
636                 return err;
637
638         err = bpf_program__set_prep(prog, priv->nr_types,
639                                     preproc_gen_prologue);
640         return err;
641 }
642
643 int bpf__probe(struct bpf_object *obj)
644 {
645         int err = 0;
646         struct bpf_program *prog;
647         struct bpf_prog_priv *priv;
648         struct perf_probe_event *pev;
649
650         err = bpf__prepare_probe();
651         if (err) {
652                 pr_debug("bpf__prepare_probe failed\n");
653                 return err;
654         }
655
656         bpf_object__for_each_program(prog, obj) {
657                 err = config_bpf_program(prog);
658                 if (err)
659                         goto out;
660
661                 priv = bpf_program__priv(prog);
662                 if (IS_ERR(priv) || !priv) {
663                         err = PTR_ERR(priv);
664                         goto out;
665                 }
666
667                 if (priv->is_tp) {
668                         bpf_program__set_tracepoint(prog);
669                         continue;
670                 }
671
672                 bpf_program__set_kprobe(prog);
673                 pev = &priv->pev;
674
675                 err = convert_perf_probe_events(pev, 1);
676                 if (err < 0) {
677                         pr_debug("bpf_probe: failed to convert perf probe events\n");
678                         goto out;
679                 }
680
681                 err = apply_perf_probe_events(pev, 1);
682                 if (err < 0) {
683                         pr_debug("bpf_probe: failed to apply perf probe events\n");
684                         goto out;
685                 }
686
687                 /*
688                  * After probing, let's consider prologue, which
689                  * adds program fetcher to BPF programs.
690                  *
691                  * hook_load_preprocessorr() hooks pre-processor
692                  * to bpf_program, let it generate prologue
693                  * dynamically during loading.
694                  */
695                 err = hook_load_preprocessor(prog);
696                 if (err)
697                         goto out;
698         }
699 out:
700         return err < 0 ? err : 0;
701 }
702
703 #define EVENTS_WRITE_BUFSIZE  4096
704 int bpf__unprobe(struct bpf_object *obj)
705 {
706         int err, ret = 0;
707         struct bpf_program *prog;
708
709         bpf_object__for_each_program(prog, obj) {
710                 struct bpf_prog_priv *priv = bpf_program__priv(prog);
711                 int i;
712
713                 if (IS_ERR(priv) || !priv || priv->is_tp)
714                         continue;
715
716                 for (i = 0; i < priv->pev.ntevs; i++) {
717                         struct probe_trace_event *tev = &priv->pev.tevs[i];
718                         char name_buf[EVENTS_WRITE_BUFSIZE];
719                         struct strfilter *delfilter;
720
721                         snprintf(name_buf, EVENTS_WRITE_BUFSIZE,
722                                  "%s:%s", tev->group, tev->event);
723                         name_buf[EVENTS_WRITE_BUFSIZE - 1] = '\0';
724
725                         delfilter = strfilter__new(name_buf, NULL);
726                         if (!delfilter) {
727                                 pr_debug("Failed to create filter for unprobing\n");
728                                 ret = -ENOMEM;
729                                 continue;
730                         }
731
732                         err = del_perf_probe_events(delfilter);
733                         strfilter__delete(delfilter);
734                         if (err) {
735                                 pr_debug("Failed to delete %s\n", name_buf);
736                                 ret = err;
737                                 continue;
738                         }
739                 }
740         }
741         return ret;
742 }
743
744 int bpf__load(struct bpf_object *obj)
745 {
746         int err;
747
748         err = bpf_object__load(obj);
749         if (err) {
750                 char bf[128];
751                 libbpf_strerror(err, bf, sizeof(bf));
752                 pr_debug("bpf: load objects failed: err=%d: (%s)\n", err, bf);
753                 return err;
754         }
755         return 0;
756 }
757
758 int bpf__foreach_event(struct bpf_object *obj,
759                        bpf_prog_iter_callback_t func,
760                        void *arg)
761 {
762         struct bpf_program *prog;
763         int err;
764
765         bpf_object__for_each_program(prog, obj) {
766                 struct bpf_prog_priv *priv = bpf_program__priv(prog);
767                 struct probe_trace_event *tev;
768                 struct perf_probe_event *pev;
769                 int i, fd;
770
771                 if (IS_ERR(priv) || !priv) {
772                         pr_debug("bpf: failed to get private field\n");
773                         return -BPF_LOADER_ERRNO__INTERNAL;
774                 }
775
776                 if (priv->is_tp) {
777                         fd = bpf_program__fd(prog);
778                         err = (*func)(priv->sys_name, priv->evt_name, fd, arg);
779                         if (err) {
780                                 pr_debug("bpf: tracepoint call back failed, stop iterate\n");
781                                 return err;
782                         }
783                         continue;
784                 }
785
786                 pev = &priv->pev;
787                 for (i = 0; i < pev->ntevs; i++) {
788                         tev = &pev->tevs[i];
789
790                         if (priv->need_prologue) {
791                                 int type = priv->type_mapping[i];
792
793                                 fd = bpf_program__nth_fd(prog, type);
794                         } else {
795                                 fd = bpf_program__fd(prog);
796                         }
797
798                         if (fd < 0) {
799                                 pr_debug("bpf: failed to get file descriptor\n");
800                                 return fd;
801                         }
802
803                         err = (*func)(tev->group, tev->event, fd, arg);
804                         if (err) {
805                                 pr_debug("bpf: call back failed, stop iterate\n");
806                                 return err;
807                         }
808                 }
809         }
810         return 0;
811 }
812
813 enum bpf_map_op_type {
814         BPF_MAP_OP_SET_VALUE,
815         BPF_MAP_OP_SET_EVSEL,
816 };
817
818 enum bpf_map_key_type {
819         BPF_MAP_KEY_ALL,
820         BPF_MAP_KEY_RANGES,
821 };
822
823 struct bpf_map_op {
824         struct list_head list;
825         enum bpf_map_op_type op_type;
826         enum bpf_map_key_type key_type;
827         union {
828                 struct parse_events_array array;
829         } k;
830         union {
831                 u64 value;
832                 struct perf_evsel *evsel;
833         } v;
834 };
835
836 struct bpf_map_priv {
837         struct list_head ops_list;
838 };
839
840 static void
841 bpf_map_op__delete(struct bpf_map_op *op)
842 {
843         if (!list_empty(&op->list))
844                 list_del(&op->list);
845         if (op->key_type == BPF_MAP_KEY_RANGES)
846                 parse_events__clear_array(&op->k.array);
847         free(op);
848 }
849
850 static void
851 bpf_map_priv__purge(struct bpf_map_priv *priv)
852 {
853         struct bpf_map_op *pos, *n;
854
855         list_for_each_entry_safe(pos, n, &priv->ops_list, list) {
856                 list_del_init(&pos->list);
857                 bpf_map_op__delete(pos);
858         }
859 }
860
861 static void
862 bpf_map_priv__clear(struct bpf_map *map __maybe_unused,
863                     void *_priv)
864 {
865         struct bpf_map_priv *priv = _priv;
866
867         bpf_map_priv__purge(priv);
868         free(priv);
869 }
870
871 static int
872 bpf_map_op_setkey(struct bpf_map_op *op, struct parse_events_term *term)
873 {
874         op->key_type = BPF_MAP_KEY_ALL;
875         if (!term)
876                 return 0;
877
878         if (term->array.nr_ranges) {
879                 size_t memsz = term->array.nr_ranges *
880                                 sizeof(op->k.array.ranges[0]);
881
882                 op->k.array.ranges = memdup(term->array.ranges, memsz);
883                 if (!op->k.array.ranges) {
884                         pr_debug("Not enough memory to alloc indices for map\n");
885                         return -ENOMEM;
886                 }
887                 op->key_type = BPF_MAP_KEY_RANGES;
888                 op->k.array.nr_ranges = term->array.nr_ranges;
889         }
890         return 0;
891 }
892
893 static struct bpf_map_op *
894 bpf_map_op__new(struct parse_events_term *term)
895 {
896         struct bpf_map_op *op;
897         int err;
898
899         op = zalloc(sizeof(*op));
900         if (!op) {
901                 pr_debug("Failed to alloc bpf_map_op\n");
902                 return ERR_PTR(-ENOMEM);
903         }
904         INIT_LIST_HEAD(&op->list);
905
906         err = bpf_map_op_setkey(op, term);
907         if (err) {
908                 free(op);
909                 return ERR_PTR(err);
910         }
911         return op;
912 }
913
914 static struct bpf_map_op *
915 bpf_map_op__clone(struct bpf_map_op *op)
916 {
917         struct bpf_map_op *newop;
918
919         newop = memdup(op, sizeof(*op));
920         if (!newop) {
921                 pr_debug("Failed to alloc bpf_map_op\n");
922                 return NULL;
923         }
924
925         INIT_LIST_HEAD(&newop->list);
926         if (op->key_type == BPF_MAP_KEY_RANGES) {
927                 size_t memsz = op->k.array.nr_ranges *
928                                sizeof(op->k.array.ranges[0]);
929
930                 newop->k.array.ranges = memdup(op->k.array.ranges, memsz);
931                 if (!newop->k.array.ranges) {
932                         pr_debug("Failed to alloc indices for map\n");
933                         free(newop);
934                         return NULL;
935                 }
936         }
937
938         return newop;
939 }
940
941 static struct bpf_map_priv *
942 bpf_map_priv__clone(struct bpf_map_priv *priv)
943 {
944         struct bpf_map_priv *newpriv;
945         struct bpf_map_op *pos, *newop;
946
947         newpriv = zalloc(sizeof(*newpriv));
948         if (!newpriv) {
949                 pr_debug("Not enough memory to alloc map private\n");
950                 return NULL;
951         }
952         INIT_LIST_HEAD(&newpriv->ops_list);
953
954         list_for_each_entry(pos, &priv->ops_list, list) {
955                 newop = bpf_map_op__clone(pos);
956                 if (!newop) {
957                         bpf_map_priv__purge(newpriv);
958                         return NULL;
959                 }
960                 list_add_tail(&newop->list, &newpriv->ops_list);
961         }
962
963         return newpriv;
964 }
965
966 static int
967 bpf_map__add_op(struct bpf_map *map, struct bpf_map_op *op)
968 {
969         const char *map_name = bpf_map__name(map);
970         struct bpf_map_priv *priv = bpf_map__priv(map);
971
972         if (IS_ERR(priv)) {
973                 pr_debug("Failed to get private from map %s\n", map_name);
974                 return PTR_ERR(priv);
975         }
976
977         if (!priv) {
978                 priv = zalloc(sizeof(*priv));
979                 if (!priv) {
980                         pr_debug("Not enough memory to alloc map private\n");
981                         return -ENOMEM;
982                 }
983                 INIT_LIST_HEAD(&priv->ops_list);
984
985                 if (bpf_map__set_priv(map, priv, bpf_map_priv__clear)) {
986                         free(priv);
987                         return -BPF_LOADER_ERRNO__INTERNAL;
988                 }
989         }
990
991         list_add_tail(&op->list, &priv->ops_list);
992         return 0;
993 }
994
995 static struct bpf_map_op *
996 bpf_map__add_newop(struct bpf_map *map, struct parse_events_term *term)
997 {
998         struct bpf_map_op *op;
999         int err;
1000
1001         op = bpf_map_op__new(term);
1002         if (IS_ERR(op))
1003                 return op;
1004
1005         err = bpf_map__add_op(map, op);
1006         if (err) {
1007                 bpf_map_op__delete(op);
1008                 return ERR_PTR(err);
1009         }
1010         return op;
1011 }
1012
1013 static int
1014 __bpf_map__config_value(struct bpf_map *map,
1015                         struct parse_events_term *term)
1016 {
1017         struct bpf_map_op *op;
1018         const char *map_name = bpf_map__name(map);
1019         const struct bpf_map_def *def = bpf_map__def(map);
1020
1021         if (IS_ERR(def)) {
1022                 pr_debug("Unable to get map definition from '%s'\n",
1023                          map_name);
1024                 return -BPF_LOADER_ERRNO__INTERNAL;
1025         }
1026
1027         if (def->type != BPF_MAP_TYPE_ARRAY) {
1028                 pr_debug("Map %s type is not BPF_MAP_TYPE_ARRAY\n",
1029                          map_name);
1030                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE;
1031         }
1032         if (def->key_size < sizeof(unsigned int)) {
1033                 pr_debug("Map %s has incorrect key size\n", map_name);
1034                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_KEYSIZE;
1035         }
1036         switch (def->value_size) {
1037         case 1:
1038         case 2:
1039         case 4:
1040         case 8:
1041                 break;
1042         default:
1043                 pr_debug("Map %s has incorrect value size\n", map_name);
1044                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUESIZE;
1045         }
1046
1047         op = bpf_map__add_newop(map, term);
1048         if (IS_ERR(op))
1049                 return PTR_ERR(op);
1050         op->op_type = BPF_MAP_OP_SET_VALUE;
1051         op->v.value = term->val.num;
1052         return 0;
1053 }
1054
1055 static int
1056 bpf_map__config_value(struct bpf_map *map,
1057                       struct parse_events_term *term,
1058                       struct perf_evlist *evlist __maybe_unused)
1059 {
1060         if (!term->err_val) {
1061                 pr_debug("Config value not set\n");
1062                 return -BPF_LOADER_ERRNO__OBJCONF_CONF;
1063         }
1064
1065         if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM) {
1066                 pr_debug("ERROR: wrong value type for 'value'\n");
1067                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE;
1068         }
1069
1070         return __bpf_map__config_value(map, term);
1071 }
1072
1073 static int
1074 __bpf_map__config_event(struct bpf_map *map,
1075                         struct parse_events_term *term,
1076                         struct perf_evlist *evlist)
1077 {
1078         struct perf_evsel *evsel;
1079         const struct bpf_map_def *def;
1080         struct bpf_map_op *op;
1081         const char *map_name = bpf_map__name(map);
1082
1083         evsel = perf_evlist__find_evsel_by_str(evlist, term->val.str);
1084         if (!evsel) {
1085                 pr_debug("Event (for '%s') '%s' doesn't exist\n",
1086                          map_name, term->val.str);
1087                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_NOEVT;
1088         }
1089
1090         def = bpf_map__def(map);
1091         if (IS_ERR(def)) {
1092                 pr_debug("Unable to get map definition from '%s'\n",
1093                          map_name);
1094                 return PTR_ERR(def);
1095         }
1096
1097         /*
1098          * No need to check key_size and value_size:
1099          * kernel has already checked them.
1100          */
1101         if (def->type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
1102                 pr_debug("Map %s type is not BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
1103                          map_name);
1104                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE;
1105         }
1106
1107         op = bpf_map__add_newop(map, term);
1108         if (IS_ERR(op))
1109                 return PTR_ERR(op);
1110         op->op_type = BPF_MAP_OP_SET_EVSEL;
1111         op->v.evsel = evsel;
1112         return 0;
1113 }
1114
1115 static int
1116 bpf_map__config_event(struct bpf_map *map,
1117                       struct parse_events_term *term,
1118                       struct perf_evlist *evlist)
1119 {
1120         if (!term->err_val) {
1121                 pr_debug("Config value not set\n");
1122                 return -BPF_LOADER_ERRNO__OBJCONF_CONF;
1123         }
1124
1125         if (term->type_val != PARSE_EVENTS__TERM_TYPE_STR) {
1126                 pr_debug("ERROR: wrong value type for 'event'\n");
1127                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE;
1128         }
1129
1130         return __bpf_map__config_event(map, term, evlist);
1131 }
1132
1133 struct bpf_obj_config__map_func {
1134         const char *config_opt;
1135         int (*config_func)(struct bpf_map *, struct parse_events_term *,
1136                            struct perf_evlist *);
1137 };
1138
1139 struct bpf_obj_config__map_func bpf_obj_config__map_funcs[] = {
1140         {"value", bpf_map__config_value},
1141         {"event", bpf_map__config_event},
1142 };
1143
1144 static int
1145 config_map_indices_range_check(struct parse_events_term *term,
1146                                struct bpf_map *map,
1147                                const char *map_name)
1148 {
1149         struct parse_events_array *array = &term->array;
1150         const struct bpf_map_def *def;
1151         unsigned int i;
1152
1153         if (!array->nr_ranges)
1154                 return 0;
1155         if (!array->ranges) {
1156                 pr_debug("ERROR: map %s: array->nr_ranges is %d but range array is NULL\n",
1157                          map_name, (int)array->nr_ranges);
1158                 return -BPF_LOADER_ERRNO__INTERNAL;
1159         }
1160
1161         def = bpf_map__def(map);
1162         if (IS_ERR(def)) {
1163                 pr_debug("ERROR: Unable to get map definition from '%s'\n",
1164                          map_name);
1165                 return -BPF_LOADER_ERRNO__INTERNAL;
1166         }
1167
1168         for (i = 0; i < array->nr_ranges; i++) {
1169                 unsigned int start = array->ranges[i].start;
1170                 size_t length = array->ranges[i].length;
1171                 unsigned int idx = start + length - 1;
1172
1173                 if (idx >= def->max_entries) {
1174                         pr_debug("ERROR: index %d too large\n", idx);
1175                         return -BPF_LOADER_ERRNO__OBJCONF_MAP_IDX2BIG;
1176                 }
1177         }
1178         return 0;
1179 }
1180
1181 static int
1182 bpf__obj_config_map(struct bpf_object *obj,
1183                     struct parse_events_term *term,
1184                     struct perf_evlist *evlist,
1185                     int *key_scan_pos)
1186 {
1187         /* key is "map:<mapname>.<config opt>" */
1188         char *map_name = strdup(term->config + sizeof("map:") - 1);
1189         struct bpf_map *map;
1190         int err = -BPF_LOADER_ERRNO__OBJCONF_OPT;
1191         char *map_opt;
1192         size_t i;
1193
1194         if (!map_name)
1195                 return -ENOMEM;
1196
1197         map_opt = strchr(map_name, '.');
1198         if (!map_opt) {
1199                 pr_debug("ERROR: Invalid map config: %s\n", map_name);
1200                 goto out;
1201         }
1202
1203         *map_opt++ = '\0';
1204         if (*map_opt == '\0') {
1205                 pr_debug("ERROR: Invalid map option: %s\n", term->config);
1206                 goto out;
1207         }
1208
1209         map = bpf_object__find_map_by_name(obj, map_name);
1210         if (!map) {
1211                 pr_debug("ERROR: Map %s doesn't exist\n", map_name);
1212                 err = -BPF_LOADER_ERRNO__OBJCONF_MAP_NOTEXIST;
1213                 goto out;
1214         }
1215
1216         *key_scan_pos += strlen(map_opt);
1217         err = config_map_indices_range_check(term, map, map_name);
1218         if (err)
1219                 goto out;
1220         *key_scan_pos -= strlen(map_opt);
1221
1222         for (i = 0; i < ARRAY_SIZE(bpf_obj_config__map_funcs); i++) {
1223                 struct bpf_obj_config__map_func *func =
1224                                 &bpf_obj_config__map_funcs[i];
1225
1226                 if (strcmp(map_opt, func->config_opt) == 0) {
1227                         err = func->config_func(map, term, evlist);
1228                         goto out;
1229                 }
1230         }
1231
1232         pr_debug("ERROR: Invalid map config option '%s'\n", map_opt);
1233         err = -BPF_LOADER_ERRNO__OBJCONF_MAP_OPT;
1234 out:
1235         free(map_name);
1236         if (!err)
1237                 key_scan_pos += strlen(map_opt);
1238         return err;
1239 }
1240
1241 int bpf__config_obj(struct bpf_object *obj,
1242                     struct parse_events_term *term,
1243                     struct perf_evlist *evlist,
1244                     int *error_pos)
1245 {
1246         int key_scan_pos = 0;
1247         int err;
1248
1249         if (!obj || !term || !term->config)
1250                 return -EINVAL;
1251
1252         if (strstarts(term->config, "map:")) {
1253                 key_scan_pos = sizeof("map:") - 1;
1254                 err = bpf__obj_config_map(obj, term, evlist, &key_scan_pos);
1255                 goto out;
1256         }
1257         err = -BPF_LOADER_ERRNO__OBJCONF_OPT;
1258 out:
1259         if (error_pos)
1260                 *error_pos = key_scan_pos;
1261         return err;
1262
1263 }
1264
1265 typedef int (*map_config_func_t)(const char *name, int map_fd,
1266                                  const struct bpf_map_def *pdef,
1267                                  struct bpf_map_op *op,
1268                                  void *pkey, void *arg);
1269
1270 static int
1271 foreach_key_array_all(map_config_func_t func,
1272                       void *arg, const char *name,
1273                       int map_fd, const struct bpf_map_def *pdef,
1274                       struct bpf_map_op *op)
1275 {
1276         unsigned int i;
1277         int err;
1278
1279         for (i = 0; i < pdef->max_entries; i++) {
1280                 err = func(name, map_fd, pdef, op, &i, arg);
1281                 if (err) {
1282                         pr_debug("ERROR: failed to insert value to %s[%u]\n",
1283                                  name, i);
1284                         return err;
1285                 }
1286         }
1287         return 0;
1288 }
1289
1290 static int
1291 foreach_key_array_ranges(map_config_func_t func, void *arg,
1292                          const char *name, int map_fd,
1293                          const struct bpf_map_def *pdef,
1294                          struct bpf_map_op *op)
1295 {
1296         unsigned int i, j;
1297         int err;
1298
1299         for (i = 0; i < op->k.array.nr_ranges; i++) {
1300                 unsigned int start = op->k.array.ranges[i].start;
1301                 size_t length = op->k.array.ranges[i].length;
1302
1303                 for (j = 0; j < length; j++) {
1304                         unsigned int idx = start + j;
1305
1306                         err = func(name, map_fd, pdef, op, &idx, arg);
1307                         if (err) {
1308                                 pr_debug("ERROR: failed to insert value to %s[%u]\n",
1309                                          name, idx);
1310                                 return err;
1311                         }
1312                 }
1313         }
1314         return 0;
1315 }
1316
1317 static int
1318 bpf_map_config_foreach_key(struct bpf_map *map,
1319                            map_config_func_t func,
1320                            void *arg)
1321 {
1322         int err, map_fd;
1323         struct bpf_map_op *op;
1324         const struct bpf_map_def *def;
1325         const char *name = bpf_map__name(map);
1326         struct bpf_map_priv *priv = bpf_map__priv(map);
1327
1328         if (IS_ERR(priv)) {
1329                 pr_debug("ERROR: failed to get private from map %s\n", name);
1330                 return -BPF_LOADER_ERRNO__INTERNAL;
1331         }
1332         if (!priv || list_empty(&priv->ops_list)) {
1333                 pr_debug("INFO: nothing to config for map %s\n", name);
1334                 return 0;
1335         }
1336
1337         def = bpf_map__def(map);
1338         if (IS_ERR(def)) {
1339                 pr_debug("ERROR: failed to get definition from map %s\n", name);
1340                 return -BPF_LOADER_ERRNO__INTERNAL;
1341         }
1342         map_fd = bpf_map__fd(map);
1343         if (map_fd < 0) {
1344                 pr_debug("ERROR: failed to get fd from map %s\n", name);
1345                 return map_fd;
1346         }
1347
1348         list_for_each_entry(op, &priv->ops_list, list) {
1349                 switch (def->type) {
1350                 case BPF_MAP_TYPE_ARRAY:
1351                 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1352                         switch (op->key_type) {
1353                         case BPF_MAP_KEY_ALL:
1354                                 err = foreach_key_array_all(func, arg, name,
1355                                                             map_fd, def, op);
1356                                 break;
1357                         case BPF_MAP_KEY_RANGES:
1358                                 err = foreach_key_array_ranges(func, arg, name,
1359                                                                map_fd, def,
1360                                                                op);
1361                                 break;
1362                         default:
1363                                 pr_debug("ERROR: keytype for map '%s' invalid\n",
1364                                          name);
1365                                 return -BPF_LOADER_ERRNO__INTERNAL;
1366                         }
1367                         if (err)
1368                                 return err;
1369                         break;
1370                 default:
1371                         pr_debug("ERROR: type of '%s' incorrect\n", name);
1372                         return -BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE;
1373                 }
1374         }
1375
1376         return 0;
1377 }
1378
1379 static int
1380 apply_config_value_for_key(int map_fd, void *pkey,
1381                            size_t val_size, u64 val)
1382 {
1383         int err = 0;
1384
1385         switch (val_size) {
1386         case 1: {
1387                 u8 _val = (u8)(val);
1388                 err = bpf_map_update_elem(map_fd, pkey, &_val, BPF_ANY);
1389                 break;
1390         }
1391         case 2: {
1392                 u16 _val = (u16)(val);
1393                 err = bpf_map_update_elem(map_fd, pkey, &_val, BPF_ANY);
1394                 break;
1395         }
1396         case 4: {
1397                 u32 _val = (u32)(val);
1398                 err = bpf_map_update_elem(map_fd, pkey, &_val, BPF_ANY);
1399                 break;
1400         }
1401         case 8: {
1402                 err = bpf_map_update_elem(map_fd, pkey, &val, BPF_ANY);
1403                 break;
1404         }
1405         default:
1406                 pr_debug("ERROR: invalid value size\n");
1407                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUESIZE;
1408         }
1409         if (err && errno)
1410                 err = -errno;
1411         return err;
1412 }
1413
1414 static int
1415 apply_config_evsel_for_key(const char *name, int map_fd, void *pkey,
1416                            struct perf_evsel *evsel)
1417 {
1418         struct xyarray *xy = evsel->fd;
1419         struct perf_event_attr *attr;
1420         unsigned int key, events;
1421         bool check_pass = false;
1422         int *evt_fd;
1423         int err;
1424
1425         if (!xy) {
1426                 pr_debug("ERROR: evsel not ready for map %s\n", name);
1427                 return -BPF_LOADER_ERRNO__INTERNAL;
1428         }
1429
1430         if (xy->row_size / xy->entry_size != 1) {
1431                 pr_debug("ERROR: Dimension of target event is incorrect for map %s\n",
1432                          name);
1433                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_EVTDIM;
1434         }
1435
1436         attr = &evsel->attr;
1437         if (attr->inherit) {
1438                 pr_debug("ERROR: Can't put inherit event into map %s\n", name);
1439                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_EVTINH;
1440         }
1441
1442         if (perf_evsel__is_bpf_output(evsel))
1443                 check_pass = true;
1444         if (attr->type == PERF_TYPE_RAW)
1445                 check_pass = true;
1446         if (attr->type == PERF_TYPE_HARDWARE)
1447                 check_pass = true;
1448         if (!check_pass) {
1449                 pr_debug("ERROR: Event type is wrong for map %s\n", name);
1450                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_EVTTYPE;
1451         }
1452
1453         events = xy->entries / (xy->row_size / xy->entry_size);
1454         key = *((unsigned int *)pkey);
1455         if (key >= events) {
1456                 pr_debug("ERROR: there is no event %d for map %s\n",
1457                          key, name);
1458                 return -BPF_LOADER_ERRNO__OBJCONF_MAP_MAPSIZE;
1459         }
1460         evt_fd = xyarray__entry(xy, key, 0);
1461         err = bpf_map_update_elem(map_fd, pkey, evt_fd, BPF_ANY);
1462         if (err && errno)
1463                 err = -errno;
1464         return err;
1465 }
1466
1467 static int
1468 apply_obj_config_map_for_key(const char *name, int map_fd,
1469                              const struct bpf_map_def *pdef,
1470                              struct bpf_map_op *op,
1471                              void *pkey, void *arg __maybe_unused)
1472 {
1473         int err;
1474
1475         switch (op->op_type) {
1476         case BPF_MAP_OP_SET_VALUE:
1477                 err = apply_config_value_for_key(map_fd, pkey,
1478                                                  pdef->value_size,
1479                                                  op->v.value);
1480                 break;
1481         case BPF_MAP_OP_SET_EVSEL:
1482                 err = apply_config_evsel_for_key(name, map_fd, pkey,
1483                                                  op->v.evsel);
1484                 break;
1485         default:
1486                 pr_debug("ERROR: unknown value type for '%s'\n", name);
1487                 err = -BPF_LOADER_ERRNO__INTERNAL;
1488         }
1489         return err;
1490 }
1491
1492 static int
1493 apply_obj_config_map(struct bpf_map *map)
1494 {
1495         return bpf_map_config_foreach_key(map,
1496                                           apply_obj_config_map_for_key,
1497                                           NULL);
1498 }
1499
1500 static int
1501 apply_obj_config_object(struct bpf_object *obj)
1502 {
1503         struct bpf_map *map;
1504         int err;
1505
1506         bpf_map__for_each(map, obj) {
1507                 err = apply_obj_config_map(map);
1508                 if (err)
1509                         return err;
1510         }
1511         return 0;
1512 }
1513
1514 int bpf__apply_obj_config(void)
1515 {
1516         struct bpf_object *obj, *tmp;
1517         int err;
1518
1519         bpf_object__for_each_safe(obj, tmp) {
1520                 err = apply_obj_config_object(obj);
1521                 if (err)
1522                         return err;
1523         }
1524
1525         return 0;
1526 }
1527
1528 #define bpf__for_each_map(pos, obj, objtmp)     \
1529         bpf_object__for_each_safe(obj, objtmp)  \
1530                 bpf_map__for_each(pos, obj)
1531
1532 #define bpf__for_each_map_named(pos, obj, objtmp, name) \
1533         bpf__for_each_map(pos, obj, objtmp)             \
1534                 if (bpf_map__name(pos) &&               \
1535                         (strcmp(name,                   \
1536                                 bpf_map__name(pos)) == 0))
1537
1538 struct perf_evsel *bpf__setup_output_event(struct perf_evlist *evlist, const char *name)
1539 {
1540         struct bpf_map_priv *tmpl_priv = NULL;
1541         struct bpf_object *obj, *tmp;
1542         struct perf_evsel *evsel = NULL;
1543         struct bpf_map *map;
1544         int err;
1545         bool need_init = false;
1546
1547         bpf__for_each_map_named(map, obj, tmp, name) {
1548                 struct bpf_map_priv *priv = bpf_map__priv(map);
1549
1550                 if (IS_ERR(priv))
1551                         return ERR_PTR(-BPF_LOADER_ERRNO__INTERNAL);
1552
1553                 /*
1554                  * No need to check map type: type should have been
1555                  * verified by kernel.
1556                  */
1557                 if (!need_init && !priv)
1558                         need_init = !priv;
1559                 if (!tmpl_priv && priv)
1560                         tmpl_priv = priv;
1561         }
1562
1563         if (!need_init)
1564                 return NULL;
1565
1566         if (!tmpl_priv) {
1567                 char *event_definition = NULL;
1568
1569                 if (asprintf(&event_definition, "bpf-output/no-inherit=1,name=%s/", name) < 0)
1570                         return ERR_PTR(-ENOMEM);
1571
1572                 err = parse_events(evlist, event_definition, NULL);
1573                 free(event_definition);
1574
1575                 if (err) {
1576                         pr_debug("ERROR: failed to create the \"%s\" bpf-output event\n", name);
1577                         return ERR_PTR(-err);
1578                 }
1579
1580                 evsel = perf_evlist__last(evlist);
1581         }
1582
1583         bpf__for_each_map_named(map, obj, tmp, name) {
1584                 struct bpf_map_priv *priv = bpf_map__priv(map);
1585
1586                 if (IS_ERR(priv))
1587                         return ERR_PTR(-BPF_LOADER_ERRNO__INTERNAL);
1588                 if (priv)
1589                         continue;
1590
1591                 if (tmpl_priv) {
1592                         priv = bpf_map_priv__clone(tmpl_priv);
1593                         if (!priv)
1594                                 return ERR_PTR(-ENOMEM);
1595
1596                         err = bpf_map__set_priv(map, priv, bpf_map_priv__clear);
1597                         if (err) {
1598                                 bpf_map_priv__clear(map, priv);
1599                                 return ERR_PTR(err);
1600                         }
1601                 } else if (evsel) {
1602                         struct bpf_map_op *op;
1603
1604                         op = bpf_map__add_newop(map, NULL);
1605                         if (IS_ERR(op))
1606                                 return ERR_PTR(PTR_ERR(op));
1607                         op->op_type = BPF_MAP_OP_SET_EVSEL;
1608                         op->v.evsel = evsel;
1609                 }
1610         }
1611
1612         return evsel;
1613 }
1614
1615 int bpf__setup_stdout(struct perf_evlist *evlist)
1616 {
1617         struct perf_evsel *evsel = bpf__setup_output_event(evlist, "__bpf_stdout__");
1618         return IS_ERR(evsel) ? PTR_ERR(evsel) : 0;
1619 }
1620
1621 #define ERRNO_OFFSET(e)         ((e) - __BPF_LOADER_ERRNO__START)
1622 #define ERRCODE_OFFSET(c)       ERRNO_OFFSET(BPF_LOADER_ERRNO__##c)
1623 #define NR_ERRNO        (__BPF_LOADER_ERRNO__END - __BPF_LOADER_ERRNO__START)
1624
1625 static const char *bpf_loader_strerror_table[NR_ERRNO] = {
1626         [ERRCODE_OFFSET(CONFIG)]        = "Invalid config string",
1627         [ERRCODE_OFFSET(GROUP)]         = "Invalid group name",
1628         [ERRCODE_OFFSET(EVENTNAME)]     = "No event name found in config string",
1629         [ERRCODE_OFFSET(INTERNAL)]      = "BPF loader internal error",
1630         [ERRCODE_OFFSET(COMPILE)]       = "Error when compiling BPF scriptlet",
1631         [ERRCODE_OFFSET(PROGCONF_TERM)] = "Invalid program config term in config string",
1632         [ERRCODE_OFFSET(PROLOGUE)]      = "Failed to generate prologue",
1633         [ERRCODE_OFFSET(PROLOGUE2BIG)]  = "Prologue too big for program",
1634         [ERRCODE_OFFSET(PROLOGUEOOB)]   = "Offset out of bound for prologue",
1635         [ERRCODE_OFFSET(OBJCONF_OPT)]   = "Invalid object config option",
1636         [ERRCODE_OFFSET(OBJCONF_CONF)]  = "Config value not set (missing '=')",
1637         [ERRCODE_OFFSET(OBJCONF_MAP_OPT)]       = "Invalid object map config option",
1638         [ERRCODE_OFFSET(OBJCONF_MAP_NOTEXIST)]  = "Target map doesn't exist",
1639         [ERRCODE_OFFSET(OBJCONF_MAP_VALUE)]     = "Incorrect value type for map",
1640         [ERRCODE_OFFSET(OBJCONF_MAP_TYPE)]      = "Incorrect map type",
1641         [ERRCODE_OFFSET(OBJCONF_MAP_KEYSIZE)]   = "Incorrect map key size",
1642         [ERRCODE_OFFSET(OBJCONF_MAP_VALUESIZE)] = "Incorrect map value size",
1643         [ERRCODE_OFFSET(OBJCONF_MAP_NOEVT)]     = "Event not found for map setting",
1644         [ERRCODE_OFFSET(OBJCONF_MAP_MAPSIZE)]   = "Invalid map size for event setting",
1645         [ERRCODE_OFFSET(OBJCONF_MAP_EVTDIM)]    = "Event dimension too large",
1646         [ERRCODE_OFFSET(OBJCONF_MAP_EVTINH)]    = "Doesn't support inherit event",
1647         [ERRCODE_OFFSET(OBJCONF_MAP_EVTTYPE)]   = "Wrong event type for map",
1648         [ERRCODE_OFFSET(OBJCONF_MAP_IDX2BIG)]   = "Index too large",
1649 };
1650
1651 static int
1652 bpf_loader_strerror(int err, char *buf, size_t size)
1653 {
1654         char sbuf[STRERR_BUFSIZE];
1655         const char *msg;
1656
1657         if (!buf || !size)
1658                 return -1;
1659
1660         err = err > 0 ? err : -err;
1661
1662         if (err >= __LIBBPF_ERRNO__START)
1663                 return libbpf_strerror(err, buf, size);
1664
1665         if (err >= __BPF_LOADER_ERRNO__START && err < __BPF_LOADER_ERRNO__END) {
1666                 msg = bpf_loader_strerror_table[ERRNO_OFFSET(err)];
1667                 snprintf(buf, size, "%s", msg);
1668                 buf[size - 1] = '\0';
1669                 return 0;
1670         }
1671
1672         if (err >= __BPF_LOADER_ERRNO__END)
1673                 snprintf(buf, size, "Unknown bpf loader error %d", err);
1674         else
1675                 snprintf(buf, size, "%s",
1676                          str_error_r(err, sbuf, sizeof(sbuf)));
1677
1678         buf[size - 1] = '\0';
1679         return -1;
1680 }
1681
1682 #define bpf__strerror_head(err, buf, size) \
1683         char sbuf[STRERR_BUFSIZE], *emsg;\
1684         if (!size)\
1685                 return 0;\
1686         if (err < 0)\
1687                 err = -err;\
1688         bpf_loader_strerror(err, sbuf, sizeof(sbuf));\
1689         emsg = sbuf;\
1690         switch (err) {\
1691         default:\
1692                 scnprintf(buf, size, "%s", emsg);\
1693                 break;
1694
1695 #define bpf__strerror_entry(val, fmt...)\
1696         case val: {\
1697                 scnprintf(buf, size, fmt);\
1698                 break;\
1699         }
1700
1701 #define bpf__strerror_end(buf, size)\
1702         }\
1703         buf[size - 1] = '\0';
1704
1705 int bpf__strerror_prepare_load(const char *filename, bool source,
1706                                int err, char *buf, size_t size)
1707 {
1708         size_t n;
1709         int ret;
1710
1711         n = snprintf(buf, size, "Failed to load %s%s: ",
1712                          filename, source ? " from source" : "");
1713         if (n >= size) {
1714                 buf[size - 1] = '\0';
1715                 return 0;
1716         }
1717         buf += n;
1718         size -= n;
1719
1720         ret = bpf_loader_strerror(err, buf, size);
1721         buf[size - 1] = '\0';
1722         return ret;
1723 }
1724
1725 int bpf__strerror_probe(struct bpf_object *obj __maybe_unused,
1726                         int err, char *buf, size_t size)
1727 {
1728         bpf__strerror_head(err, buf, size);
1729         case BPF_LOADER_ERRNO__PROGCONF_TERM: {
1730                 scnprintf(buf, size, "%s (add -v to see detail)", emsg);
1731                 break;
1732         }
1733         bpf__strerror_entry(EEXIST, "Probe point exist. Try 'perf probe -d \"*\"' and set 'force=yes'");
1734         bpf__strerror_entry(EACCES, "You need to be root");
1735         bpf__strerror_entry(EPERM, "You need to be root, and /proc/sys/kernel/kptr_restrict should be 0");
1736         bpf__strerror_entry(ENOENT, "You need to check probing points in BPF file");
1737         bpf__strerror_end(buf, size);
1738         return 0;
1739 }
1740
1741 int bpf__strerror_load(struct bpf_object *obj,
1742                        int err, char *buf, size_t size)
1743 {
1744         bpf__strerror_head(err, buf, size);
1745         case LIBBPF_ERRNO__KVER: {
1746                 unsigned int obj_kver = bpf_object__kversion(obj);
1747                 unsigned int real_kver;
1748
1749                 if (fetch_kernel_version(&real_kver, NULL, 0)) {
1750                         scnprintf(buf, size, "Unable to fetch kernel version");
1751                         break;
1752                 }
1753
1754                 if (obj_kver != real_kver) {
1755                         scnprintf(buf, size,
1756                                   "'version' ("KVER_FMT") doesn't match running kernel ("KVER_FMT")",
1757                                   KVER_PARAM(obj_kver),
1758                                   KVER_PARAM(real_kver));
1759                         break;
1760                 }
1761
1762                 scnprintf(buf, size, "Failed to load program for unknown reason");
1763                 break;
1764         }
1765         bpf__strerror_end(buf, size);
1766         return 0;
1767 }
1768
1769 int bpf__strerror_config_obj(struct bpf_object *obj __maybe_unused,
1770                              struct parse_events_term *term __maybe_unused,
1771                              struct perf_evlist *evlist __maybe_unused,
1772                              int *error_pos __maybe_unused, int err,
1773                              char *buf, size_t size)
1774 {
1775         bpf__strerror_head(err, buf, size);
1776         bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE,
1777                             "Can't use this config term with this map type");
1778         bpf__strerror_end(buf, size);
1779         return 0;
1780 }
1781
1782 int bpf__strerror_apply_obj_config(int err, char *buf, size_t size)
1783 {
1784         bpf__strerror_head(err, buf, size);
1785         bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_EVTDIM,
1786                             "Cannot set event to BPF map in multi-thread tracing");
1787         bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_EVTINH,
1788                             "%s (Hint: use -i to turn off inherit)", emsg);
1789         bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_EVTTYPE,
1790                             "Can only put raw, hardware and BPF output event into a BPF map");
1791         bpf__strerror_end(buf, size);
1792         return 0;
1793 }
1794
1795 int bpf__strerror_setup_output_event(struct perf_evlist *evlist __maybe_unused,
1796                                      int err, char *buf, size_t size)
1797 {
1798         bpf__strerror_head(err, buf, size);
1799         bpf__strerror_end(buf, size);
1800         return 0;
1801 }