xref: /linux/tools/perf/util/env.c (revision 6cdecad561fffb7c44241ad35a8bdb6a0ed30b5b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "cpumap.h"
3 #include "dwarf-regs.h"
4 #include "debug.h"
5 #include "env.h"
6 #include "util/header.h"
7 #include "util/rwsem.h"
8 #include <linux/compiler.h>
9 #include <linux/kernel.h>
10 #include <linux/ctype.h>
11 #include <linux/rbtree.h>
12 #include <linux/string.h>
13 #include <linux/zalloc.h>
14 #include "cgroup.h"
15 #include <errno.h>
16 #include <sys/utsname.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include "pmu.h"
20 #include "pmus.h"
21 #include "strbuf.h"
22 #include "trace/beauty/beauty.h"
23 
24 #ifdef HAVE_LIBBPF_SUPPORT
25 #include "bpf-event.h"
26 #include "bpf-utils.h"
27 #include <bpf/libbpf.h>
28 
29 bool perf_env__insert_bpf_prog_info(struct perf_env *env,
30 				    struct bpf_prog_info_node *info_node)
31 {
32 	bool ret;
33 
34 	down_write(&env->bpf_progs.lock);
35 	ret = __perf_env__insert_bpf_prog_info(env, info_node);
36 	up_write(&env->bpf_progs.lock);
37 
38 	return ret;
39 }
40 
41 bool __perf_env__insert_bpf_prog_info(struct perf_env *env, struct bpf_prog_info_node *info_node)
42 {
43 	__u32 prog_id = info_node->info_linear->info.id;
44 	struct bpf_prog_info_node *node;
45 	struct rb_node *parent = NULL;
46 	struct rb_node **p;
47 
48 	p = &env->bpf_progs.infos.rb_node;
49 
50 	while (*p != NULL) {
51 		parent = *p;
52 		node = rb_entry(parent, struct bpf_prog_info_node, rb_node);
53 		if (prog_id < node->info_linear->info.id) {
54 			p = &(*p)->rb_left;
55 		} else if (prog_id > node->info_linear->info.id) {
56 			p = &(*p)->rb_right;
57 		} else {
58 			pr_debug("duplicated bpf prog info %u\n", prog_id);
59 			return false;
60 		}
61 	}
62 
63 	rb_link_node(&info_node->rb_node, parent, p);
64 	rb_insert_color(&info_node->rb_node, &env->bpf_progs.infos);
65 	env->bpf_progs.infos_cnt++;
66 	return true;
67 }
68 
69 struct bpf_prog_info_node *perf_env__find_bpf_prog_info(struct perf_env *env,
70 							__u32 prog_id)
71 {
72 	struct bpf_prog_info_node *node = NULL;
73 	struct rb_node *n;
74 
75 	down_read(&env->bpf_progs.lock);
76 	n = env->bpf_progs.infos.rb_node;
77 
78 	while (n) {
79 		node = rb_entry(n, struct bpf_prog_info_node, rb_node);
80 		if (prog_id < node->info_linear->info.id)
81 			n = n->rb_left;
82 		else if (prog_id > node->info_linear->info.id)
83 			n = n->rb_right;
84 		else
85 			goto out;
86 	}
87 	node = NULL;
88 
89 out:
90 	up_read(&env->bpf_progs.lock);
91 	return node;
92 }
93 
94 void perf_env__iterate_bpf_prog_info(struct perf_env *env,
95 				     void (*cb)(struct bpf_prog_info_node *node,
96 						void *data),
97 				     void *data)
98 {
99 	struct rb_node *first;
100 
101 	down_read(&env->bpf_progs.lock);
102 	first = rb_first(&env->bpf_progs.infos);
103 	for (struct rb_node *node = first; node != NULL; node = rb_next(node))
104 		(*cb)(rb_entry(node, struct bpf_prog_info_node, rb_node), data);
105 	up_read(&env->bpf_progs.lock);
106 }
107 
108 bool perf_env__insert_btf(struct perf_env *env, struct btf_node *btf_node)
109 {
110 	bool ret;
111 
112 	down_write(&env->bpf_progs.lock);
113 	ret = __perf_env__insert_btf(env, btf_node);
114 	up_write(&env->bpf_progs.lock);
115 	return ret;
116 }
117 
118 bool __perf_env__insert_btf(struct perf_env *env, struct btf_node *btf_node)
119 {
120 	struct rb_node *parent = NULL;
121 	__u32 btf_id = btf_node->id;
122 	struct btf_node *node;
123 	struct rb_node **p;
124 
125 	p = &env->bpf_progs.btfs.rb_node;
126 
127 	while (*p != NULL) {
128 		parent = *p;
129 		node = rb_entry(parent, struct btf_node, rb_node);
130 		if (btf_id < node->id) {
131 			p = &(*p)->rb_left;
132 		} else if (btf_id > node->id) {
133 			p = &(*p)->rb_right;
134 		} else {
135 			pr_debug("duplicated btf %u\n", btf_id);
136 			return false;
137 		}
138 	}
139 
140 	rb_link_node(&btf_node->rb_node, parent, p);
141 	rb_insert_color(&btf_node->rb_node, &env->bpf_progs.btfs);
142 	env->bpf_progs.btfs_cnt++;
143 	return true;
144 }
145 
146 struct btf_node *perf_env__find_btf(struct perf_env *env, __u32 btf_id)
147 {
148 	struct btf_node *res;
149 
150 	down_read(&env->bpf_progs.lock);
151 	res = __perf_env__find_btf(env, btf_id);
152 	up_read(&env->bpf_progs.lock);
153 	return res;
154 }
155 
156 struct btf_node *__perf_env__find_btf(struct perf_env *env, __u32 btf_id)
157 {
158 	struct btf_node *node = NULL;
159 	struct rb_node *n;
160 
161 	n = env->bpf_progs.btfs.rb_node;
162 
163 	while (n) {
164 		node = rb_entry(n, struct btf_node, rb_node);
165 		if (btf_id < node->id)
166 			n = n->rb_left;
167 		else if (btf_id > node->id)
168 			n = n->rb_right;
169 		else
170 			return node;
171 	}
172 	return NULL;
173 }
174 
175 /* purge data in bpf_progs.infos tree */
176 static void perf_env__purge_bpf(struct perf_env *env)
177 {
178 	struct rb_root *root;
179 	struct rb_node *next;
180 
181 	down_write(&env->bpf_progs.lock);
182 
183 	root = &env->bpf_progs.infos;
184 	next = rb_first(root);
185 
186 	while (next) {
187 		struct bpf_prog_info_node *node;
188 
189 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
190 		next = rb_next(&node->rb_node);
191 		rb_erase(&node->rb_node, root);
192 		zfree(&node->info_linear);
193 		bpf_metadata_free(node->metadata);
194 		free(node);
195 	}
196 
197 	env->bpf_progs.infos_cnt = 0;
198 
199 	root = &env->bpf_progs.btfs;
200 	next = rb_first(root);
201 
202 	while (next) {
203 		struct btf_node *node;
204 
205 		node = rb_entry(next, struct btf_node, rb_node);
206 		next = rb_next(&node->rb_node);
207 		rb_erase(&node->rb_node, root);
208 		free(node);
209 	}
210 
211 	env->bpf_progs.btfs_cnt = 0;
212 
213 	up_write(&env->bpf_progs.lock);
214 }
215 #else // HAVE_LIBBPF_SUPPORT
216 static void perf_env__purge_bpf(struct perf_env *env __maybe_unused)
217 {
218 }
219 #endif // HAVE_LIBBPF_SUPPORT
220 
221 void free_cpu_domain_info(struct cpu_domain_map **cd_map, u32 schedstat_version, u32 nr)
222 {
223 	if (!cd_map)
224 		return;
225 
226 	for (u32 i = 0; i < nr; i++) {
227 		if (!cd_map[i])
228 			continue;
229 
230 		for (u32 j = 0; j < cd_map[i]->nr_domains; j++) {
231 			struct domain_info *d_info = cd_map[i]->domains[j];
232 
233 			if (!d_info)
234 				continue;
235 
236 			if (schedstat_version >= 17)
237 				zfree(&d_info->dname);
238 
239 			zfree(&d_info->cpumask);
240 			zfree(&d_info->cpulist);
241 			zfree(&d_info);
242 		}
243 		zfree(&cd_map[i]->domains);
244 		zfree(&cd_map[i]);
245 	}
246 	zfree(&cd_map);
247 }
248 
249 void perf_env__exit(struct perf_env *env)
250 {
251 	int i, j;
252 
253 	mutex_destroy(&env->lock);
254 
255 	perf_env__purge_bpf(env);
256 	perf_env__purge_cgroups(env);
257 	zfree(&env->hostname);
258 	zfree(&env->os_release);
259 	zfree(&env->version);
260 	zfree(&env->arch);
261 	zfree(&env->cpu_desc);
262 	zfree(&env->cpuid);
263 	zfree(&env->cmdline);
264 	zfree(&env->cmdline_argv);
265 	zfree(&env->sibling_dies);
266 	zfree(&env->sibling_cores);
267 	zfree(&env->sibling_threads);
268 	zfree(&env->pmu_mappings);
269 	zfree(&env->cpu);
270 	for (i = 0; i < env->nr_cpu_pmu_caps; i++)
271 		zfree(&env->cpu_pmu_caps[i]);
272 	zfree(&env->cpu_pmu_caps);
273 	zfree(&env->numa_map);
274 
275 	for (i = 0; i < env->nr_numa_nodes; i++)
276 		perf_cpu_map__put(env->numa_nodes[i].map);
277 	zfree(&env->numa_nodes);
278 
279 	for (i = 0; i < env->caches_cnt; i++)
280 		cpu_cache_level__free(&env->caches[i]);
281 	zfree(&env->caches);
282 
283 	for (i = 0; i < env->nr_memory_nodes; i++)
284 		zfree(&env->memory_nodes[i].set);
285 	zfree(&env->memory_nodes);
286 
287 	for (i = 0; i < env->nr_hybrid_nodes; i++) {
288 		zfree(&env->hybrid_nodes[i].pmu_name);
289 		zfree(&env->hybrid_nodes[i].cpus);
290 	}
291 	zfree(&env->hybrid_nodes);
292 
293 	for (i = 0; i < env->nr_pmus_with_caps; i++) {
294 		for (j = 0; j < env->pmu_caps[i].nr_caps; j++)
295 			zfree(&env->pmu_caps[i].caps[j]);
296 		zfree(&env->pmu_caps[i].caps);
297 		zfree(&env->pmu_caps[i].pmu_name);
298 	}
299 	zfree(&env->pmu_caps);
300 	zfree(&env->memory_ranges);
301 	free_cpu_domain_info(env->cpu_domain, env->schedstat_version, env->nr_cpus_avail);
302 }
303 
304 void perf_env__init(struct perf_env *env)
305 {
306 	memset(env, 0, sizeof(*env));
307 #ifdef HAVE_LIBBPF_SUPPORT
308 	env->bpf_progs.infos = RB_ROOT;
309 	env->bpf_progs.btfs = RB_ROOT;
310 	init_rwsem(&env->bpf_progs.lock);
311 #endif
312 	env->kernel_is_64_bit = -1;
313 	mutex_init(&env->lock);
314 }
315 
316 static void perf_env__init_kernel_mode(struct perf_env *env)
317 {
318 	const char *arch = env->arch;
319 
320 	if (!arch) {
321 		static struct utsname uts = { .machine[0] = '\0', };
322 
323 		if (uts.machine[0] == '\0')
324 			uname(&uts);
325 		if (uts.machine[0] != '\0')
326 			arch = uts.machine;
327 	}
328 
329 	if (arch) {
330 		if (strstr(arch, "64") || strstr(arch, "s390x"))
331 			env->kernel_is_64_bit = 1;
332 		else
333 			env->kernel_is_64_bit = 0;
334 		return;
335 	}
336 
337 	/* Fallback if completely unresolvable (assume host-bitness) */
338 	env->kernel_is_64_bit = (sizeof(void *) == 8) ? 1 : 0;
339 }
340 
341 int perf_env__kernel_is_64_bit(struct perf_env *env)
342 {
343 	if (env->kernel_is_64_bit == -1)
344 		perf_env__init_kernel_mode(env);
345 
346 	return env->kernel_is_64_bit;
347 }
348 
349 bool perf_arch_is_big_endian(const char *arch)
350 {
351 	if (!arch)
352 		return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
353 
354 	if (str_ends_with(arch, "_be") || !strcmp(arch, "sparc") || !strcmp(arch, "sparc64") ||
355 	    !strcmp(arch, "s390") || !strcmp(arch, "s390x") || !strcmp(arch, "powerpc") ||
356 	    !strcmp(arch, "ppc") || !strcmp(arch, "ppc64") ||
357 	    !strcmp(arch, "mips") || !strcmp(arch, "mips64") || !strcmp(arch, "parisc") ||
358 	    !strcmp(arch, "parisc64") || !strcmp(arch, "m68k") ||
359 	    !strcmp(arch, "armeb") || !strcmp(arch, "mipseb") || !strcmp(arch, "mips64eb"))
360 		return true;
361 
362 	return false;
363 }
364 
365 const char *perf_env__os_release(struct perf_env *env)
366 {
367 	struct utsname uts;
368 	int ret;
369 	const char *release;
370 
371 	if (!env)
372 		return perf_version_string;
373 
374 	mutex_lock(&env->lock);
375 	if (env->os_release) {
376 		release = env->os_release;
377 		goto out;
378 	}
379 
380 	/*
381 	 * If env->arch is set, this is an offline target environment.
382 	 * If the os_release is not populated in the file, we do not want
383 	 * to poison it with the host's release which would break guest checks.
384 	 */
385 	if (env->arch) {
386 		release = NULL;
387 		goto out;
388 	}
389 
390 	/*
391 	 * The os_release is being accessed but wasn't initialized from a data
392 	 * file, assume this is 'live' mode and use the release from uname. If
393 	 * uname or strdup fails then use the current perf tool version.
394 	 */
395 	ret = uname(&uts);
396 	env->os_release = strdup(ret < 0 ? perf_version_string : uts.release);
397 	release = env->os_release ?: perf_version_string;
398 out:
399 	mutex_unlock(&env->lock);
400 	return release;
401 }
402 
403 int perf_env__set_cmdline(struct perf_env *env, int argc, const char *argv[])
404 {
405 	int i;
406 
407 	/* do not include NULL termination */
408 	env->cmdline_argv = calloc(argc, sizeof(char *));
409 	if (env->cmdline_argv == NULL)
410 		goto out_enomem;
411 
412 	/*
413 	 * Must copy argv contents because it gets moved around during option
414 	 * parsing:
415 	 */
416 	for (i = 0; i < argc ; i++) {
417 		env->cmdline_argv[i] = argv[i];
418 		if (env->cmdline_argv[i] == NULL)
419 			goto out_free;
420 	}
421 
422 	env->nr_cmdline = argc;
423 
424 	return 0;
425 out_free:
426 	zfree(&env->cmdline_argv);
427 out_enomem:
428 	return -ENOMEM;
429 }
430 
431 int perf_env__read_cpu_topology_map(struct perf_env *env)
432 {
433 	int idx, nr_cpus;
434 
435 	if (env->cpu != NULL)
436 		return 0;
437 
438 	if (env->nr_cpus_avail == 0)
439 		env->nr_cpus_avail = cpu__max_present_cpu().cpu;
440 
441 	nr_cpus = env->nr_cpus_avail;
442 	if (nr_cpus == -1)
443 		return -EINVAL;
444 
445 	env->cpu = calloc(nr_cpus, sizeof(env->cpu[0]));
446 	if (env->cpu == NULL)
447 		return -ENOMEM;
448 
449 	for (idx = 0; idx < nr_cpus; ++idx) {
450 		struct perf_cpu cpu = { .cpu = idx };
451 		int core_id   = cpu__get_core_id(cpu);
452 		int socket_id = cpu__get_socket_id(cpu);
453 		int die_id    = cpu__get_die_id(cpu);
454 
455 		env->cpu[idx].core_id	= core_id >= 0 ? core_id : -1;
456 		env->cpu[idx].socket_id	= socket_id >= 0 ? socket_id : -1;
457 		env->cpu[idx].die_id	= die_id >= 0 ? die_id : -1;
458 	}
459 
460 	env->nr_cpus_avail = nr_cpus;
461 	return 0;
462 }
463 
464 int perf_env__read_pmu_mappings(struct perf_env *env)
465 {
466 	struct perf_pmu *pmu = NULL;
467 	u32 pmu_num = 0;
468 	struct strbuf sb;
469 
470 	while ((pmu = perf_pmus__scan(pmu)))
471 		pmu_num++;
472 
473 	if (!pmu_num) {
474 		pr_debug("pmu mappings not available\n");
475 		return -ENOENT;
476 	}
477 	env->nr_pmu_mappings = pmu_num;
478 
479 	if (strbuf_init(&sb, 128 * pmu_num) < 0)
480 		return -ENOMEM;
481 
482 	while ((pmu = perf_pmus__scan(pmu))) {
483 		if (strbuf_addf(&sb, "%u:%s", pmu->type, pmu->name) < 0)
484 			goto error;
485 		/* include a NULL character at the end */
486 		if (strbuf_add(&sb, "", 1) < 0)
487 			goto error;
488 	}
489 
490 	env->pmu_mappings = strbuf_detach(&sb, NULL);
491 
492 	return 0;
493 
494 error:
495 	strbuf_release(&sb);
496 	return -1;
497 }
498 
499 int perf_env__read_cpuid(struct perf_env *env)
500 {
501 	char cpuid[128];
502 	struct perf_cpu cpu = {-1};
503 	int err = get_cpuid(cpuid, sizeof(cpuid), cpu);
504 
505 	if (err)
506 		return err;
507 
508 	free(env->cpuid);
509 	env->cpuid = strdup(cpuid);
510 	if (env->cpuid == NULL)
511 		return ENOMEM;
512 	return 0;
513 }
514 
515 static int perf_env__read_nr_cpus_avail(struct perf_env *env)
516 {
517 	if (env->nr_cpus_avail == 0)
518 		env->nr_cpus_avail = cpu__max_present_cpu().cpu;
519 
520 	return env->nr_cpus_avail ? 0 : -ENOENT;
521 }
522 
523 static int __perf_env__read_core_pmu_caps(const struct perf_pmu *pmu,
524 					  int *nr_caps, char ***caps,
525 					  unsigned int *max_branches,
526 					  unsigned int *br_cntr_nr,
527 					  unsigned int *br_cntr_width)
528 {
529 	struct perf_pmu_caps *pcaps = NULL;
530 	char *ptr, **tmp;
531 	int ret = 0;
532 
533 	*nr_caps = 0;
534 	*caps = NULL;
535 
536 	if (!pmu->nr_caps)
537 		return 0;
538 
539 	*caps = calloc(pmu->nr_caps, sizeof(char *));
540 	if (!*caps)
541 		return -ENOMEM;
542 
543 	tmp = *caps;
544 	list_for_each_entry(pcaps, &pmu->caps, list) {
545 		if (asprintf(&ptr, "%s=%s", pcaps->name, pcaps->value) < 0) {
546 			ret = -ENOMEM;
547 			goto error;
548 		}
549 
550 		*tmp++ = ptr;
551 
552 		if (!strcmp(pcaps->name, "branches"))
553 			*max_branches = atoi(pcaps->value);
554 		else if (!strcmp(pcaps->name, "branch_counter_nr"))
555 			*br_cntr_nr = atoi(pcaps->value);
556 		else if (!strcmp(pcaps->name, "branch_counter_width"))
557 			*br_cntr_width = atoi(pcaps->value);
558 	}
559 	*nr_caps = pmu->nr_caps;
560 	return 0;
561 error:
562 	while (tmp-- != *caps)
563 		zfree(tmp);
564 	zfree(caps);
565 	*nr_caps = 0;
566 	return ret;
567 }
568 
569 int perf_env__read_core_pmu_caps(struct perf_env *env)
570 {
571 	struct pmu_caps *pmu_caps;
572 	struct perf_pmu *pmu = NULL;
573 	int nr_pmu, i = 0, j;
574 	int ret;
575 
576 	nr_pmu = perf_pmus__num_core_pmus();
577 
578 	if (!nr_pmu)
579 		return -ENODEV;
580 
581 	if (nr_pmu == 1) {
582 		pmu = perf_pmus__find_core_pmu();
583 		if (!pmu)
584 			return -ENODEV;
585 		ret = perf_pmu__caps_parse(pmu);
586 		if (ret < 0)
587 			return ret;
588 		return __perf_env__read_core_pmu_caps(pmu, &env->nr_cpu_pmu_caps,
589 						      &env->cpu_pmu_caps,
590 						      &env->max_branches,
591 						      &env->br_cntr_nr,
592 						      &env->br_cntr_width);
593 	}
594 
595 	pmu_caps = calloc(nr_pmu, sizeof(*pmu_caps));
596 	if (!pmu_caps)
597 		return -ENOMEM;
598 
599 	while ((pmu = perf_pmus__scan_core(pmu)) != NULL) {
600 		if (perf_pmu__caps_parse(pmu) <= 0)
601 			continue;
602 		ret = __perf_env__read_core_pmu_caps(pmu, &pmu_caps[i].nr_caps,
603 						     &pmu_caps[i].caps,
604 						     &pmu_caps[i].max_branches,
605 						     &pmu_caps[i].br_cntr_nr,
606 						     &pmu_caps[i].br_cntr_width);
607 		if (ret)
608 			goto error;
609 
610 		pmu_caps[i].pmu_name = strdup(pmu->name);
611 		if (!pmu_caps[i].pmu_name) {
612 			ret = -ENOMEM;
613 			goto error;
614 		}
615 		i++;
616 	}
617 
618 	env->nr_pmus_with_caps = nr_pmu;
619 	env->pmu_caps = pmu_caps;
620 
621 	return 0;
622 error:
623 	for (i = 0; i < nr_pmu; i++) {
624 		for (j = 0; j < pmu_caps[i].nr_caps; j++)
625 			zfree(&pmu_caps[i].caps[j]);
626 		zfree(&pmu_caps[i].caps);
627 		zfree(&pmu_caps[i].pmu_name);
628 	}
629 	zfree(&pmu_caps);
630 	return ret;
631 }
632 
633 int perf_env__nr_cpus_avail(struct perf_env *env)
634 {
635 	return env && !perf_env__read_nr_cpus_avail(env) ? env->nr_cpus_avail : 0;
636 }
637 
638 void cpu_cache_level__free(struct cpu_cache_level *cache)
639 {
640 	zfree(&cache->type);
641 	zfree(&cache->map);
642 	zfree(&cache->size);
643 }
644 
645 struct arch_to_e_machine {
646 	const char *prefix;
647 	uint16_t e_machine;
648 };
649 
650 /*
651  * A mapping from an arch prefix string to an ELF machine that can be used in a
652  * bsearch. Some arch prefixes are shared an need additional processing as
653  * marked next to the architecture. The prefixes handle both perf's architecture
654  * naming and those from uname.
655  */
656 static const struct arch_to_e_machine prefix_to_e_machine[] = {
657 	{"aarch64", EM_AARCH64},
658 	{"alpha", EM_ALPHA},
659 	{"arc", EM_ARC},
660 	{"arm", EM_ARM}, /* Check also for EM_AARCH64. */
661 	{"avr", EM_AVR},  /* Check also for EM_AVR32. */
662 	{"bfin", EM_BLACKFIN},
663 	{"blackfin", EM_BLACKFIN},
664 	{"cris", EM_CRIS},
665 	{"csky", EM_CSKY},
666 	{"hppa", EM_PARISC},
667 	{"i386", EM_386},
668 	{"i486", EM_386},
669 	{"i586", EM_386},
670 	{"i686", EM_386},
671 	{"loongarch", EM_LOONGARCH},
672 	{"m32r", EM_M32R},
673 	{"m68k", EM_68K},
674 	{"microblaze", EM_MICROBLAZE},
675 	{"mips", EM_MIPS},
676 	{"msp430", EM_MSP430},
677 	{"parisc", EM_PARISC},
678 	{"powerpc", EM_PPC}, /* Check also for EM_PPC64. */
679 	{"ppc", EM_PPC}, /* Check also for EM_PPC64. */
680 	{"riscv", EM_RISCV},
681 	{"s390", EM_S390},
682 	{"sa110", EM_ARM},
683 	{"sh", EM_SH},
684 	{"sparc", EM_SPARC}, /* Check also for EM_SPARCV9. */
685 	{"sun4u", EM_SPARC},
686 	{"x86", EM_X86_64}, /* Check also for EM_386. */
687 	{"xtensa", EM_XTENSA},
688 };
689 
690 static int compare_prefix(const void *key, const void *element)
691 {
692 	const char *search_key = key;
693 	const struct arch_to_e_machine *map_element = element;
694 	size_t prefix_len = strlen(map_element->prefix);
695 
696 	return strncmp(search_key, map_element->prefix, prefix_len);
697 }
698 
699 static uint16_t perf_arch_to_e_machine(const char *perf_arch, int is_64_bit)
700 {
701 	/* Binary search for a matching prefix. */
702 	const struct arch_to_e_machine *result;
703 
704 	if (!perf_arch)
705 		return EM_HOST;
706 
707 	result = bsearch(perf_arch,
708 			 prefix_to_e_machine, ARRAY_SIZE(prefix_to_e_machine),
709 			 sizeof(prefix_to_e_machine[0]),
710 			 compare_prefix);
711 
712 	if (!result) {
713 		pr_debug("Unknown perf arch for ELF machine mapping: %s\n", perf_arch);
714 		return EM_NONE;
715 	}
716 
717 	/*
718 	 * Handle conflicting prefixes. If the is_64_bit is unknown (-1) then
719 	 * assume 64-bit. We can't use perf_env__kernel_is_64_bit as that
720 	 * depends on the arch string.
721 	 */
722 	switch (result->e_machine) {
723 	case EM_ARM:
724 		return !strcmp(perf_arch, "arm64") || !strcmp(perf_arch, "aarch64")
725 			? EM_AARCH64 : EM_ARM;
726 	case EM_AVR:
727 		return !strcmp(perf_arch, "avr32") ? EM_AVR32 : EM_AVR;
728 	case EM_PPC:
729 		if (is_64_bit == 1)
730 			return EM_PPC64;
731 		if (is_64_bit == 0)
732 			return EM_PPC;
733 		return strstarts(perf_arch, "ppc64") ? EM_PPC64 : EM_PPC;
734 	case EM_SPARC:
735 		if (is_64_bit == 1)
736 			return EM_SPARCV9;
737 		if (is_64_bit == 0)
738 			return EM_SPARC;
739 		return !strcmp(perf_arch, "sparc64") || !strcmp(perf_arch, "sun4u")
740 			? EM_SPARCV9 : EM_SPARC;
741 	case EM_X86_64:
742 		if (is_64_bit == 1)
743 			return EM_X86_64;
744 		if (is_64_bit == 0)
745 			return EM_386;
746 		return !strcmp(perf_arch, "x86_64") || !strcmp(perf_arch, "x86")
747 			? EM_X86_64 : EM_386;
748 	default:
749 		return result->e_machine;
750 	}
751 }
752 
753 static const char *e_machine_to_perf_arch(uint16_t e_machine)
754 {
755 	/*
756 	 * Table for if either the perf arch string differs from uname or there
757 	 * are >1 ELF machine with the prefix.
758 	 */
759 	static const struct arch_to_e_machine extras[] = {
760 		{"arm64", EM_AARCH64},
761 		{"avr32", EM_AVR32},
762 		{"powerpc", EM_PPC},
763 		{"powerpc", EM_PPC64},
764 		{"sparc", EM_SPARCV9},
765 		{"x86", EM_386},
766 		{"x86", EM_X86_64},
767 		{"none", EM_NONE},
768 	};
769 
770 	for (size_t i = 0; i < ARRAY_SIZE(extras); i++) {
771 		if (extras[i].e_machine == e_machine)
772 			return extras[i].prefix;
773 	}
774 
775 	for (size_t i = 0; i < ARRAY_SIZE(prefix_to_e_machine); i++) {
776 		if (prefix_to_e_machine[i].e_machine == e_machine)
777 			return prefix_to_e_machine[i].prefix;
778 
779 	}
780 	return "unknown";
781 }
782 
783 uint16_t perf_env__e_machine_nocache(struct perf_env *env, uint32_t *e_flags)
784 {
785 	uint16_t e_machine = EM_NONE;
786 	const char *arch = NULL;
787 	int is_64_bit = -1;
788 
789 	if (e_flags)
790 		*e_flags = 0;
791 
792 	if (env) {
793 		arch = env->arch;
794 		is_64_bit = env->kernel_is_64_bit;
795 	}
796 
797 	if (!arch) {
798 		static struct utsname uts = { .machine[0] = '\0', };
799 
800 		if (uts.machine[0] == '\0')
801 			uname(&uts);
802 		if (uts.machine[0] != '\0')
803 			arch = uts.machine;
804 	}
805 
806 	e_machine = perf_arch_to_e_machine(arch, is_64_bit);
807 
808 	if (e_flags)
809 		*e_flags = (e_machine == EM_HOST) ? EF_HOST : 0;
810 
811 	return e_machine;
812 }
813 
814 uint16_t perf_env__e_machine(struct perf_env *env, uint32_t *e_flags)
815 {
816 	uint16_t e_machine;
817 	uint32_t local_e_flags = 0;
818 
819 	if (env && env->e_machine != EM_NONE) {
820 		if (e_flags)
821 			*e_flags = env->e_flags;
822 
823 		return env->e_machine;
824 	}
825 	e_machine = perf_env__e_machine_nocache(env, &local_e_flags);
826 	/*
827 	 * Only cache the e_machine in perf_env if env->arch is not NULL.
828 	 * If env->arch is NULL, the e_machine is just a fallback to EM_HOST.
829 	 * Caching it permanently would prevent dynamic, more accurate
830 	 * thread-based session e_machine scanning later in
831 	 * perf_session__e_machine().
832 	 */
833 	if (env && env->arch) {
834 		env->e_machine = e_machine;
835 		env->e_flags = local_e_flags;
836 	}
837 	if (e_flags)
838 		*e_flags = local_e_flags;
839 
840 	return e_machine;
841 }
842 
843 const char *perf_env__arch(struct perf_env *env)
844 {
845 	uint16_t e_machine;
846 	const char *arch;
847 
848 	if (!env) {
849 		static struct utsname uts = { .machine[0] = '\0', };
850 		uint16_t host_e_machine;
851 
852 		if (uts.machine[0] == '\0')
853 			uname(&uts);
854 		if (uts.machine[0] != '\0') {
855 			host_e_machine = perf_arch_to_e_machine(uts.machine, -1);
856 			return e_machine_to_perf_arch(host_e_machine);
857 		}
858 		return e_machine_to_perf_arch(EM_HOST);
859 	}
860 
861 	/*
862 	 * Lazily compute/allocate arch. The e_machine may have been
863 	 * read from a data file and so may not be EM_HOST.
864 	 */
865 	e_machine = perf_env__e_machine(env, /*e_flags=*/NULL);
866 	arch = e_machine_to_perf_arch(e_machine);
867 
868 	if (e_machine == EM_RISCV && perf_env__kernel_is_64_bit(env) == 1)
869 		arch = "riscv64";
870 	else if (e_machine == EM_MIPS && perf_env__kernel_is_64_bit(env) == 1)
871 		arch = "mips64";
872 	else if (e_machine == EM_PARISC && perf_env__kernel_is_64_bit(env) == 1)
873 		arch = "parisc64";
874 
875 	return arch;
876 }
877 
878 const char *arch_syscalls__strerrno(uint16_t e_machine, int err);
879 
880 const char *perf_env__arch_strerrno(uint16_t e_machine, int err)
881 {
882 	return arch_syscalls__strerrno(e_machine, err);
883 }
884 
885 const char *perf_env__cpuid(struct perf_env *env)
886 {
887 	int status;
888 
889 	if (!env->cpuid) { /* Assume local operation */
890 		status = perf_env__read_cpuid(env);
891 		if (status)
892 			return NULL;
893 	}
894 
895 	return env->cpuid;
896 }
897 
898 int perf_env__nr_pmu_mappings(struct perf_env *env)
899 {
900 	int status;
901 
902 	if (!env->nr_pmu_mappings) { /* Assume local operation */
903 		status = perf_env__read_pmu_mappings(env);
904 		if (status)
905 			return 0;
906 	}
907 
908 	return env->nr_pmu_mappings;
909 }
910 
911 const char *perf_env__pmu_mappings(struct perf_env *env)
912 {
913 	int status;
914 
915 	if (!env->pmu_mappings) { /* Assume local operation */
916 		status = perf_env__read_pmu_mappings(env);
917 		if (status)
918 			return NULL;
919 	}
920 
921 	return env->pmu_mappings;
922 }
923 
924 int perf_env__numa_node(struct perf_env *env, struct perf_cpu cpu)
925 {
926 	if (!env->nr_numa_map) {
927 		struct numa_node *nn;
928 		int i, nr = 0;
929 
930 		for (i = 0; i < env->nr_numa_nodes; i++) {
931 			nn = &env->numa_nodes[i];
932 			nr = max(nr, (int)perf_cpu_map__max(nn->map).cpu);
933 		}
934 
935 		nr++;
936 
937 		/*
938 		 * We initialize the numa_map array to prepare
939 		 * it for missing cpus, which return node -1
940 		 */
941 		env->numa_map = malloc(nr * sizeof(int));
942 		if (!env->numa_map)
943 			return -1;
944 
945 		for (i = 0; i < nr; i++)
946 			env->numa_map[i] = -1;
947 
948 		env->nr_numa_map = nr;
949 
950 		for (i = 0; i < env->nr_numa_nodes; i++) {
951 			struct perf_cpu tmp;
952 			unsigned int j;
953 
954 			nn = &env->numa_nodes[i];
955 			perf_cpu_map__for_each_cpu(tmp, j, nn->map)
956 				env->numa_map[tmp.cpu] = i;
957 		}
958 	}
959 
960 	return cpu.cpu >= 0 && cpu.cpu < env->nr_numa_map ? env->numa_map[cpu.cpu] : -1;
961 }
962 
963 bool perf_env__has_pmu_mapping(struct perf_env *env, const char *pmu_name)
964 {
965 	char *pmu_mapping = env->pmu_mappings, *colon;
966 
967 	for (int i = 0; i < env->nr_pmu_mappings; ++i) {
968 		if (strtoul(pmu_mapping, &colon, 0) == ULONG_MAX || *colon != ':')
969 			goto out_error;
970 
971 		pmu_mapping = colon + 1;
972 		if (strcmp(pmu_mapping, pmu_name) == 0)
973 			return true;
974 
975 		pmu_mapping += strlen(pmu_mapping) + 1;
976 	}
977 out_error:
978 	return false;
979 }
980 
981 char *perf_env__find_pmu_cap(struct perf_env *env, const char *pmu_name,
982 			     const char *cap)
983 {
984 	char *cap_eq;
985 	int cap_size;
986 	char **ptr;
987 	int i, j;
988 
989 	if (!pmu_name || !cap)
990 		return NULL;
991 
992 	cap_size = strlen(cap);
993 	cap_eq = zalloc(cap_size + 2);
994 	if (!cap_eq)
995 		return NULL;
996 
997 	memcpy(cap_eq, cap, cap_size);
998 	cap_eq[cap_size] = '=';
999 
1000 	if (!strcmp(pmu_name, "cpu")) {
1001 		for (i = 0; i < env->nr_cpu_pmu_caps; i++) {
1002 			if (!strncmp(env->cpu_pmu_caps[i], cap_eq, cap_size + 1)) {
1003 				free(cap_eq);
1004 				return &env->cpu_pmu_caps[i][cap_size + 1];
1005 			}
1006 		}
1007 		goto out;
1008 	}
1009 
1010 	for (i = 0; i < env->nr_pmus_with_caps; i++) {
1011 		if (strcmp(env->pmu_caps[i].pmu_name, pmu_name))
1012 			continue;
1013 
1014 		ptr = env->pmu_caps[i].caps;
1015 
1016 		for (j = 0; j < env->pmu_caps[i].nr_caps; j++) {
1017 			if (!strncmp(ptr[j], cap_eq, cap_size + 1)) {
1018 				free(cap_eq);
1019 				return &ptr[j][cap_size + 1];
1020 			}
1021 		}
1022 	}
1023 
1024 out:
1025 	free(cap_eq);
1026 	return NULL;
1027 }
1028 
1029 void perf_env__find_br_cntr_info(struct perf_env *env,
1030 				 unsigned int *nr,
1031 				 unsigned int *width)
1032 {
1033 	if (nr) {
1034 		*nr = env->cpu_pmu_caps ? env->br_cntr_nr :
1035 					  env->pmu_caps->br_cntr_nr;
1036 	}
1037 
1038 	if (width) {
1039 		*width = env->cpu_pmu_caps ? env->br_cntr_width :
1040 					     env->pmu_caps->br_cntr_width;
1041 	}
1042 }
1043 
1044 bool perf_env__is_x86_amd_cpu(struct perf_env *env)
1045 {
1046 	static int is_amd; /* 0: Uninitialized, 1: Yes, -1: No */
1047 
1048 	if (is_amd == 0)
1049 		is_amd = env->cpuid && strstarts(env->cpuid, "AuthenticAMD") ? 1 : -1;
1050 
1051 	return is_amd >= 1 ? true : false;
1052 }
1053 
1054 bool x86__is_amd_cpu(void)
1055 {
1056 	struct perf_env env = { .total_mem = 0, };
1057 	bool is_amd;
1058 
1059 	perf_env__init(&env);
1060 	perf_env__cpuid(&env);
1061 	is_amd = perf_env__is_x86_amd_cpu(&env);
1062 	perf_env__exit(&env);
1063 
1064 	return is_amd;
1065 }
1066 
1067 bool perf_env__is_x86_intel_cpu(struct perf_env *env)
1068 {
1069 	static int is_intel; /* 0: Uninitialized, 1: Yes, -1: No */
1070 
1071 	if (is_intel == 0)
1072 		is_intel = env->cpuid && strstarts(env->cpuid, "GenuineIntel") ? 1 : -1;
1073 
1074 	return is_intel >= 1 ? true : false;
1075 }
1076 
1077 bool x86__is_intel_cpu(void)
1078 {
1079 	struct perf_env env = { .total_mem = 0, };
1080 	bool is_intel;
1081 
1082 	perf_env__init(&env);
1083 	perf_env__cpuid(&env);
1084 	is_intel = perf_env__is_x86_intel_cpu(&env);
1085 	perf_env__exit(&env);
1086 
1087 	return is_intel;
1088 }
1089