static int open_and_attach_perf_event()

in profiler/profile.cpp [220:259]


static int open_and_attach_perf_event(int freq, struct bpf_program *prog,
									  struct bpf_link *links[])
{
	struct perf_event_attr attr = {
		.type = PERF_TYPE_SOFTWARE,
		.config = PERF_COUNT_SW_CPU_CLOCK,
		.sample_freq = env.sample_freq,
		.freq = env.freq,
	};
	int i, fd;

	for (i = 0; i < nr_cpus; i++)
	{
		if (env.cpu != -1 && env.cpu != i)
			continue;

		fd = syscall(__NR_perf_event_open, &attr, -1, i, -1, 0);
		if (fd < 0)
		{
			/* Ignore CPU that is offline */
			if (errno == ENODEV)
				continue;
			fprintf(stderr, "failed to init perf sampling: %s\n",
					strerror(errno));
			return -1;
		}
		links[i] = bpf_program__attach_perf_event(prog, fd);
		if (!links[i])
		{
			fprintf(stderr, "failed to attach perf event on cpu: "
							"%d\n",
					i);
			links[i] = NULL;
			close(fd);
			return -1;
		}
	}

	return 0;
}