header.c 1.6 KB

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