cloexec.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <sched.h>
  2. #include "util.h"
  3. #include "../perf.h"
  4. #include "cloexec.h"
  5. #include "asm/bug.h"
  6. #include "debug.h"
  7. #include <unistd.h>
  8. #include <asm/unistd.h>
  9. #include <sys/syscall.h>
  10. static unsigned long flag = PERF_FLAG_FD_CLOEXEC;
  11. int __weak sched_getcpu(void)
  12. {
  13. #ifdef __NR_getcpu
  14. unsigned cpu;
  15. int err = syscall(__NR_getcpu, &cpu, NULL, NULL);
  16. if (!err)
  17. return cpu;
  18. #else
  19. errno = ENOSYS;
  20. #endif
  21. return -1;
  22. }
  23. static int perf_flag_probe(void)
  24. {
  25. /* use 'safest' configuration as used in perf_evsel__fallback() */
  26. struct perf_event_attr attr = {
  27. .type = PERF_TYPE_SOFTWARE,
  28. .config = PERF_COUNT_SW_CPU_CLOCK,
  29. .exclude_kernel = 1,
  30. };
  31. int fd;
  32. int err;
  33. int cpu;
  34. pid_t pid = -1;
  35. char sbuf[STRERR_BUFSIZE];
  36. cpu = sched_getcpu();
  37. if (cpu < 0)
  38. cpu = 0;
  39. /*
  40. * Using -1 for the pid is a workaround to avoid gratuitous jump label
  41. * changes.
  42. */
  43. while (1) {
  44. /* check cloexec flag */
  45. fd = sys_perf_event_open(&attr, pid, cpu, -1,
  46. PERF_FLAG_FD_CLOEXEC);
  47. if (fd < 0 && pid == -1 && errno == EACCES) {
  48. pid = 0;
  49. continue;
  50. }
  51. break;
  52. }
  53. err = errno;
  54. if (fd >= 0) {
  55. close(fd);
  56. return 1;
  57. }
  58. WARN_ONCE(err != EINVAL && err != EBUSY,
  59. "perf_event_open(..., PERF_FLAG_FD_CLOEXEC) failed with unexpected error %d (%s)\n",
  60. err, str_error_r(err, sbuf, sizeof(sbuf)));
  61. /* not supported, confirm error related to PERF_FLAG_FD_CLOEXEC */
  62. while (1) {
  63. fd = sys_perf_event_open(&attr, pid, cpu, -1, 0);
  64. if (fd < 0 && pid == -1 && errno == EACCES) {
  65. pid = 0;
  66. continue;
  67. }
  68. break;
  69. }
  70. err = errno;
  71. if (fd >= 0)
  72. close(fd);
  73. if (WARN_ONCE(fd < 0 && err != EBUSY,
  74. "perf_event_open(..., 0) failed unexpectedly with error %d (%s)\n",
  75. err, str_error_r(err, sbuf, sizeof(sbuf))))
  76. return -1;
  77. return 0;
  78. }
  79. unsigned long perf_event_open_cloexec_flag(void)
  80. {
  81. static bool probed;
  82. if (!probed) {
  83. if (perf_flag_probe() <= 0)
  84. flag = 0;
  85. probed = true;
  86. }
  87. return flag;
  88. }