Merge branch 'CR_2862_gt9xx_ts_515_changhuang.liang' into 'vf2-515-devel'
[platform/kernel/linux-starfive.git] / tools / perf / arch / riscv / util / header.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <api/fs/fs.h>
4 #include <errno.h>
5 #include "../../util/debug.h"
6 #include "../../util/header.h"
7
8 #define STR_LEN 1024
9 #define ID_SIZE 64
10
11 static int _get_cpuid(char *buf, size_t sz)
12 {
13         const char *sysfs = sysfs__mountpoint();
14         u64 id = 0;
15         char path[PATH_MAX];
16         FILE *file;
17
18         if (!sysfs || sz < ID_SIZE)
19                 return -EINVAL;
20
21         scnprintf(path, PATH_MAX, "%s/devices/platform/riscv-pmu/id",
22                         sysfs);
23
24         file = fopen(path, "r");
25         if (!file) {
26                 pr_debug("fopen failed for file %s\n", path);
27                 return -EINVAL;
28         }
29         if (!fgets(buf, ID_SIZE, file)) {
30                 fclose(file);
31                 return -EINVAL;
32         }
33
34         fclose(file);
35
36         /*Check if value is numeric and remove special characters*/
37         id = strtoul(buf, NULL, 16);
38         if (!id)
39                 return -EINVAL;
40         scnprintf(buf, ID_SIZE, "0x%lx", id);
41
42         return 0;
43 }
44
45 char *get_cpuid_str(struct perf_pmu *pmu __maybe_unused)
46 {
47         char *buf = NULL;
48         int res;
49
50         if (!pmu)
51                 return NULL;
52
53         buf = malloc(ID_SIZE);
54         if (!buf)
55                 return NULL;
56
57         /* read id */
58         res = _get_cpuid(buf, ID_SIZE);
59         if (res) {
60                 pr_err("failed to get cpuid string for PMU %s\n", pmu->name);
61                 free(buf);
62                 buf = NULL;
63         }
64
65         return buf;
66 }