header.c 1.6 KB

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