GNU Linux-libre 4.19.268-gnu1
[releases.git] / tools / perf / arch / x86 / util / header.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <sys/types.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #include "../../util/header.h"
10
11 static inline void
12 cpuid(unsigned int op, unsigned int *a, unsigned int *b, unsigned int *c,
13       unsigned int *d)
14 {
15         __asm__ __volatile__ (".byte 0x53\n\tcpuid\n\t"
16                               "movl %%ebx, %%esi\n\t.byte 0x5b"
17                         : "=a" (*a),
18                         "=S" (*b),
19                         "=c" (*c),
20                         "=d" (*d)
21                         : "a" (op));
22 }
23
24 static int
25 __get_cpuid(char *buffer, size_t sz, const char *fmt)
26 {
27         unsigned int a, b, c, d, lvl;
28         int family = -1, model = -1, step = -1;
29         int nb;
30         char vendor[16];
31
32         cpuid(0, &lvl, &b, &c, &d);
33         strncpy(&vendor[0], (char *)(&b), 4);
34         strncpy(&vendor[4], (char *)(&d), 4);
35         strncpy(&vendor[8], (char *)(&c), 4);
36         vendor[12] = '\0';
37
38         if (lvl >= 1) {
39                 cpuid(1, &a, &b, &c, &d);
40
41                 family = (a >> 8) & 0xf;  /* bits 11 - 8 */
42                 model  = (a >> 4) & 0xf;  /* Bits  7 - 4 */
43                 step   = a & 0xf;
44
45                 /* extended family */
46                 if (family == 0xf)
47                         family += (a >> 20) & 0xff;
48
49                 /* extended model */
50                 if (family >= 0x6)
51                         model += ((a >> 16) & 0xf) << 4;
52         }
53         nb = scnprintf(buffer, sz, fmt, vendor, family, model, step);
54
55         /* look for end marker to ensure the entire data fit */
56         if (strchr(buffer, '$')) {
57                 buffer[nb-1] = '\0';
58                 return 0;
59         }
60         return ENOBUFS;
61 }
62
63 int
64 get_cpuid(char *buffer, size_t sz)
65 {
66         return __get_cpuid(buffer, sz, "%s,%u,%u,%u$");
67 }
68
69 char *
70 get_cpuid_str(struct perf_pmu *pmu __maybe_unused)
71 {
72         char *buf = malloc(128);
73
74         if (buf && __get_cpuid(buf, 128, "%s-%u-%X$") < 0) {
75                 free(buf);
76                 return NULL;
77         }
78         return buf;
79 }