cloexec.c 2.0 KB

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