cloexec.c 1.7 KB
Newer Older
1
#include <sched.h>
2 3 4 5
#include "util.h"
#include "../perf.h"
#include "cloexec.h"
#include "asm/bug.h"
6
#include "debug.h"
7 8 9 10 11 12 13

static unsigned long flag = PERF_FLAG_FD_CLOEXEC;

static int perf_flag_probe(void)
{
	/* use 'safest' configuration as used in perf_evsel__fallback() */
	struct perf_event_attr attr = {
14
		.type = PERF_TYPE_SOFTWARE,
15
		.config = PERF_COUNT_SW_CPU_CLOCK,
16
		.exclude_kernel = 1,
17 18 19
	};
	int fd;
	int err;
20 21
	int cpu;
	pid_t pid = -1;
22
	char sbuf[STRERR_BUFSIZE];
23

24 25 26 27
	cpu = sched_getcpu();
	if (cpu < 0)
		cpu = 0;

28 29 30 31
	/*
	 * Using -1 for the pid is a workaround to avoid gratuitous jump label
	 * changes.
	 */
32 33 34 35 36 37 38 39 40 41
	while (1) {
		/* check cloexec flag */
		fd = sys_perf_event_open(&attr, pid, cpu, -1,
					 PERF_FLAG_FD_CLOEXEC);
		if (fd < 0 && pid == -1 && errno == EACCES) {
			pid = 0;
			continue;
		}
		break;
	}
42 43 44 45 46 47 48
	err = errno;

	if (fd >= 0) {
		close(fd);
		return 1;
	}

49
	WARN_ONCE(err != EINVAL && err != EBUSY,
50
		  "perf_event_open(..., PERF_FLAG_FD_CLOEXEC) failed with unexpected error %d (%s)\n",
51
		  err, strerror_r(err, sbuf, sizeof(sbuf)));
52 53

	/* not supported, confirm error related to PERF_FLAG_FD_CLOEXEC */
54 55 56 57 58 59 60 61
	while (1) {
		fd = sys_perf_event_open(&attr, pid, cpu, -1, 0);
		if (fd < 0 && pid == -1 && errno == EACCES) {
			pid = 0;
			continue;
		}
		break;
	}
62 63
	err = errno;

64 65 66
	if (fd >= 0)
		close(fd);

67
	if (WARN_ONCE(fd < 0 && err != EBUSY,
68
		      "perf_event_open(..., 0) failed unexpectedly with error %d (%s)\n",
69
		      err, strerror_r(err, sbuf, sizeof(sbuf))))
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
		return -1;

	return 0;
}

unsigned long perf_event_open_cloexec_flag(void)
{
	static bool probed;

	if (!probed) {
		if (perf_flag_probe() <= 0)
			flag = 0;
		probed = true;
	}

	return flag;
}