example.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (c) 2021, Microsoft Corporation.
  4. *
  5. * Authors:
  6. * Beau Belgrave <[email protected]>
  7. */
  8. #include <errno.h>
  9. #include <sys/ioctl.h>
  10. #include <sys/mman.h>
  11. #include <fcntl.h>
  12. #include <stdio.h>
  13. #include <unistd.h>
  14. #include <asm/bitsperlong.h>
  15. #include <endian.h>
  16. #include <linux/user_events.h>
  17. #if __BITS_PER_LONG == 64
  18. #define endian_swap(x) htole64(x)
  19. #else
  20. #define endian_swap(x) htole32(x)
  21. #endif
  22. /* Assumes debugfs is mounted */
  23. const char *data_file = "/sys/kernel/debug/tracing/user_events_data";
  24. const char *status_file = "/sys/kernel/debug/tracing/user_events_status";
  25. static int event_status(long **status)
  26. {
  27. int fd = open(status_file, O_RDONLY);
  28. *status = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ,
  29. MAP_SHARED, fd, 0);
  30. close(fd);
  31. if (*status == MAP_FAILED)
  32. return -1;
  33. return 0;
  34. }
  35. static int event_reg(int fd, const char *command, long *index, long *mask,
  36. int *write)
  37. {
  38. struct user_reg reg = {0};
  39. reg.size = sizeof(reg);
  40. reg.name_args = (__u64)command;
  41. if (ioctl(fd, DIAG_IOCSREG, &reg) == -1)
  42. return -1;
  43. *index = reg.status_bit / __BITS_PER_LONG;
  44. *mask = endian_swap(1L << (reg.status_bit % __BITS_PER_LONG));
  45. *write = reg.write_index;
  46. return 0;
  47. }
  48. int main(int argc, char **argv)
  49. {
  50. int data_fd, write;
  51. long index, mask;
  52. long *status_page;
  53. struct iovec io[2];
  54. __u32 count = 0;
  55. if (event_status(&status_page) == -1)
  56. return errno;
  57. data_fd = open(data_file, O_RDWR);
  58. if (event_reg(data_fd, "test u32 count", &index, &mask, &write) == -1)
  59. return errno;
  60. /* Setup iovec */
  61. io[0].iov_base = &write;
  62. io[0].iov_len = sizeof(write);
  63. io[1].iov_base = &count;
  64. io[1].iov_len = sizeof(count);
  65. ask:
  66. printf("Press enter to check status...\n");
  67. getchar();
  68. /* Check if anyone is listening */
  69. if (status_page[index] & mask) {
  70. /* Yep, trace out our data */
  71. writev(data_fd, (const struct iovec *)io, 2);
  72. /* Increase the count */
  73. count++;
  74. printf("Something was attached, wrote data\n");
  75. }
  76. goto ask;
  77. return 0;
  78. }