builtin-record.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /*
  2. * builtin-record.c
  3. *
  4. * Builtin record command: Record the profile of a workload
  5. * (or a CPU, or a PID) into the perf.data output file - for
  6. * later analysis via perf report.
  7. */
  8. #include "builtin.h"
  9. #include "perf.h"
  10. #include "util/util.h"
  11. #include "util/parse-options.h"
  12. #include "util/parse-events.h"
  13. #include "util/string.h"
  14. #include "util/header.h"
  15. #include "util/event.h"
  16. #include "util/debug.h"
  17. #include <unistd.h>
  18. #include <sched.h>
  19. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  20. static long default_interval = 0;
  21. static int nr_cpus = 0;
  22. static unsigned int page_size;
  23. static unsigned int mmap_pages = 128;
  24. static int freq = 1000;
  25. static int output;
  26. static const char *output_name = "perf.data";
  27. static int group = 0;
  28. static unsigned int realtime_prio = 0;
  29. static int raw_samples = 0;
  30. static int system_wide = 0;
  31. static int profile_cpu = -1;
  32. static pid_t target_pid = -1;
  33. static pid_t child_pid = -1;
  34. static int inherit = 1;
  35. static int force = 0;
  36. static int append_file = 0;
  37. static int call_graph = 0;
  38. static int inherit_stat = 0;
  39. static int no_samples = 0;
  40. static int sample_address = 0;
  41. static int multiplex = 0;
  42. static int multiplex_fd = -1;
  43. static long samples = 0;
  44. static struct timeval last_read;
  45. static struct timeval this_read;
  46. static u64 bytes_written = 0;
  47. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  48. static int nr_poll = 0;
  49. static int nr_cpu = 0;
  50. static int file_new = 1;
  51. struct perf_header *header = NULL;
  52. struct mmap_data {
  53. int counter;
  54. void *base;
  55. unsigned int mask;
  56. unsigned int prev;
  57. };
  58. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  59. static unsigned long mmap_read_head(struct mmap_data *md)
  60. {
  61. struct perf_event_mmap_page *pc = md->base;
  62. long head;
  63. head = pc->data_head;
  64. rmb();
  65. return head;
  66. }
  67. static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
  68. {
  69. struct perf_event_mmap_page *pc = md->base;
  70. /*
  71. * ensure all reads are done before we write the tail out.
  72. */
  73. /* mb(); */
  74. pc->data_tail = tail;
  75. }
  76. static void write_output(void *buf, size_t size)
  77. {
  78. while (size) {
  79. int ret = write(output, buf, size);
  80. if (ret < 0)
  81. die("failed to write");
  82. size -= ret;
  83. buf += ret;
  84. bytes_written += ret;
  85. }
  86. }
  87. static int process_synthesized_event(event_t *event)
  88. {
  89. write_output(event, event->header.size);
  90. return 0;
  91. }
  92. static void mmap_read(struct mmap_data *md)
  93. {
  94. unsigned int head = mmap_read_head(md);
  95. unsigned int old = md->prev;
  96. unsigned char *data = md->base + page_size;
  97. unsigned long size;
  98. void *buf;
  99. int diff;
  100. gettimeofday(&this_read, NULL);
  101. /*
  102. * If we're further behind than half the buffer, there's a chance
  103. * the writer will bite our tail and mess up the samples under us.
  104. *
  105. * If we somehow ended up ahead of the head, we got messed up.
  106. *
  107. * In either case, truncate and restart at head.
  108. */
  109. diff = head - old;
  110. if (diff < 0) {
  111. struct timeval iv;
  112. unsigned long msecs;
  113. timersub(&this_read, &last_read, &iv);
  114. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  115. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  116. " Last read %lu msecs ago.\n", msecs);
  117. /*
  118. * head points to a known good entry, start there.
  119. */
  120. old = head;
  121. }
  122. last_read = this_read;
  123. if (old != head)
  124. samples++;
  125. size = head - old;
  126. if ((old & md->mask) + size != (head & md->mask)) {
  127. buf = &data[old & md->mask];
  128. size = md->mask + 1 - (old & md->mask);
  129. old += size;
  130. write_output(buf, size);
  131. }
  132. buf = &data[old & md->mask];
  133. size = head - old;
  134. old += size;
  135. write_output(buf, size);
  136. md->prev = old;
  137. mmap_write_tail(md, old);
  138. }
  139. static volatile int done = 0;
  140. static volatile int signr = -1;
  141. static void sig_handler(int sig)
  142. {
  143. done = 1;
  144. signr = sig;
  145. }
  146. static void sig_atexit(void)
  147. {
  148. if (child_pid != -1)
  149. kill(child_pid, SIGTERM);
  150. if (signr == -1)
  151. return;
  152. signal(signr, SIG_DFL);
  153. kill(getpid(), signr);
  154. }
  155. static int group_fd;
  156. static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
  157. {
  158. struct perf_header_attr *h_attr;
  159. if (nr < header->attrs) {
  160. h_attr = header->attr[nr];
  161. } else {
  162. h_attr = perf_header_attr__new(a);
  163. perf_header__add_attr(header, h_attr);
  164. }
  165. return h_attr;
  166. }
  167. static void create_counter(int counter, int cpu, pid_t pid)
  168. {
  169. char *filter = filters[counter];
  170. struct perf_event_attr *attr = attrs + counter;
  171. struct perf_header_attr *h_attr;
  172. int track = !counter; /* only the first counter needs these */
  173. int ret;
  174. struct {
  175. u64 count;
  176. u64 time_enabled;
  177. u64 time_running;
  178. u64 id;
  179. } read_data;
  180. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  181. PERF_FORMAT_TOTAL_TIME_RUNNING |
  182. PERF_FORMAT_ID;
  183. attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  184. if (freq) {
  185. attr->sample_type |= PERF_SAMPLE_PERIOD;
  186. attr->freq = 1;
  187. attr->sample_freq = freq;
  188. }
  189. if (no_samples)
  190. attr->sample_freq = 0;
  191. if (inherit_stat)
  192. attr->inherit_stat = 1;
  193. if (sample_address)
  194. attr->sample_type |= PERF_SAMPLE_ADDR;
  195. if (call_graph)
  196. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  197. if (raw_samples) {
  198. attr->sample_type |= PERF_SAMPLE_TIME;
  199. attr->sample_type |= PERF_SAMPLE_RAW;
  200. attr->sample_type |= PERF_SAMPLE_CPU;
  201. }
  202. attr->mmap = track;
  203. attr->comm = track;
  204. attr->inherit = (cpu < 0) && inherit;
  205. attr->disabled = 1;
  206. try_again:
  207. fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
  208. if (fd[nr_cpu][counter] < 0) {
  209. int err = errno;
  210. if (err == EPERM)
  211. die("Permission error - are you root?\n");
  212. else if (err == ENODEV && profile_cpu != -1)
  213. die("No such device - did you specify an out-of-range profile CPU?\n");
  214. /*
  215. * If it's cycles then fall back to hrtimer
  216. * based cpu-clock-tick sw counter, which
  217. * is always available even if no PMU support:
  218. */
  219. if (attr->type == PERF_TYPE_HARDWARE
  220. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  221. if (verbose)
  222. warning(" ... trying to fall back to cpu-clock-ticks\n");
  223. attr->type = PERF_TYPE_SOFTWARE;
  224. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  225. goto try_again;
  226. }
  227. printf("\n");
  228. error("perfcounter syscall returned with %d (%s)\n",
  229. fd[nr_cpu][counter], strerror(err));
  230. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  231. exit(-1);
  232. }
  233. h_attr = get_header_attr(attr, counter);
  234. if (!file_new) {
  235. if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
  236. fprintf(stderr, "incompatible append\n");
  237. exit(-1);
  238. }
  239. }
  240. if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
  241. perror("Unable to read perf file descriptor\n");
  242. exit(-1);
  243. }
  244. perf_header_attr__add_id(h_attr, read_data.id);
  245. assert(fd[nr_cpu][counter] >= 0);
  246. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  247. /*
  248. * First counter acts as the group leader:
  249. */
  250. if (group && group_fd == -1)
  251. group_fd = fd[nr_cpu][counter];
  252. if (multiplex && multiplex_fd == -1)
  253. multiplex_fd = fd[nr_cpu][counter];
  254. if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
  255. ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
  256. assert(ret != -1);
  257. } else {
  258. event_array[nr_poll].fd = fd[nr_cpu][counter];
  259. event_array[nr_poll].events = POLLIN;
  260. nr_poll++;
  261. mmap_array[nr_cpu][counter].counter = counter;
  262. mmap_array[nr_cpu][counter].prev = 0;
  263. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  264. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  265. PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
  266. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  267. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  268. exit(-1);
  269. }
  270. }
  271. if (filter != NULL) {
  272. ret = ioctl(fd[nr_cpu][counter],
  273. PERF_EVENT_IOC_SET_FILTER, filter);
  274. if (ret) {
  275. error("failed to set filter with %d (%s)\n", errno,
  276. strerror(errno));
  277. exit(-1);
  278. }
  279. }
  280. ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
  281. }
  282. static void open_counters(int cpu, pid_t pid)
  283. {
  284. int counter;
  285. group_fd = -1;
  286. for (counter = 0; counter < nr_counters; counter++)
  287. create_counter(counter, cpu, pid);
  288. nr_cpu++;
  289. }
  290. static void atexit_header(void)
  291. {
  292. header->data_size += bytes_written;
  293. perf_header__write(header, output);
  294. }
  295. static int __cmd_record(int argc, const char **argv)
  296. {
  297. int i, counter;
  298. struct stat st;
  299. pid_t pid = 0;
  300. int flags;
  301. int ret;
  302. unsigned long waking = 0;
  303. page_size = sysconf(_SC_PAGE_SIZE);
  304. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  305. assert(nr_cpus <= MAX_NR_CPUS);
  306. assert(nr_cpus >= 0);
  307. atexit(sig_atexit);
  308. signal(SIGCHLD, sig_handler);
  309. signal(SIGINT, sig_handler);
  310. if (!stat(output_name, &st) && st.st_size) {
  311. if (!force && !append_file) {
  312. fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
  313. output_name);
  314. exit(-1);
  315. }
  316. } else {
  317. append_file = 0;
  318. }
  319. flags = O_CREAT|O_RDWR;
  320. if (append_file)
  321. file_new = 0;
  322. else
  323. flags |= O_TRUNC;
  324. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  325. if (output < 0) {
  326. perror("failed to create output file");
  327. exit(-1);
  328. }
  329. if (!file_new)
  330. header = perf_header__read(output);
  331. else
  332. header = perf_header__new();
  333. if (raw_samples) {
  334. perf_header__feat_trace_info(header);
  335. } else {
  336. for (i = 0; i < nr_counters; i++) {
  337. if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
  338. perf_header__feat_trace_info(header);
  339. break;
  340. }
  341. }
  342. }
  343. atexit(atexit_header);
  344. if (!system_wide) {
  345. pid = target_pid;
  346. if (pid == -1)
  347. pid = getpid();
  348. open_counters(profile_cpu, pid);
  349. } else {
  350. if (profile_cpu != -1) {
  351. open_counters(profile_cpu, target_pid);
  352. } else {
  353. for (i = 0; i < nr_cpus; i++)
  354. open_counters(i, target_pid);
  355. }
  356. }
  357. if (file_new)
  358. perf_header__write(header, output);
  359. if (!system_wide)
  360. event__synthesize_thread(pid, process_synthesized_event);
  361. else
  362. event__synthesize_threads(process_synthesized_event);
  363. if (target_pid == -1 && argc) {
  364. pid = fork();
  365. if (pid < 0)
  366. perror("failed to fork");
  367. if (!pid) {
  368. if (execvp(argv[0], (char **)argv)) {
  369. perror(argv[0]);
  370. exit(-1);
  371. }
  372. }
  373. child_pid = pid;
  374. }
  375. if (realtime_prio) {
  376. struct sched_param param;
  377. param.sched_priority = realtime_prio;
  378. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  379. pr_err("Could not set realtime priority.\n");
  380. exit(-1);
  381. }
  382. }
  383. for (;;) {
  384. int hits = samples;
  385. for (i = 0; i < nr_cpu; i++) {
  386. for (counter = 0; counter < nr_counters; counter++) {
  387. if (mmap_array[i][counter].base)
  388. mmap_read(&mmap_array[i][counter]);
  389. }
  390. }
  391. if (hits == samples) {
  392. if (done)
  393. break;
  394. ret = poll(event_array, nr_poll, -1);
  395. waking++;
  396. }
  397. if (done) {
  398. for (i = 0; i < nr_cpu; i++) {
  399. for (counter = 0; counter < nr_counters; counter++)
  400. ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
  401. }
  402. }
  403. }
  404. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  405. /*
  406. * Approximate RIP event size: 24 bytes.
  407. */
  408. fprintf(stderr,
  409. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  410. (double)bytes_written / 1024.0 / 1024.0,
  411. output_name,
  412. bytes_written / 24);
  413. return 0;
  414. }
  415. static const char * const record_usage[] = {
  416. "perf record [<options>] [<command>]",
  417. "perf record [<options>] -- <command> [<options>]",
  418. NULL
  419. };
  420. static const struct option options[] = {
  421. OPT_CALLBACK('e', "event", NULL, "event",
  422. "event selector. use 'perf list' to list available events",
  423. parse_events),
  424. OPT_CALLBACK(0, "filter", NULL, "filter",
  425. "event filter", parse_filter),
  426. OPT_INTEGER('p', "pid", &target_pid,
  427. "record events on existing pid"),
  428. OPT_INTEGER('r', "realtime", &realtime_prio,
  429. "collect data with this RT SCHED_FIFO priority"),
  430. OPT_BOOLEAN('R', "raw-samples", &raw_samples,
  431. "collect raw sample records from all opened counters"),
  432. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  433. "system-wide collection from all CPUs"),
  434. OPT_BOOLEAN('A', "append", &append_file,
  435. "append to the output file to do incremental profiling"),
  436. OPT_INTEGER('C', "profile_cpu", &profile_cpu,
  437. "CPU to profile on"),
  438. OPT_BOOLEAN('f', "force", &force,
  439. "overwrite existing data file"),
  440. OPT_LONG('c', "count", &default_interval,
  441. "event period to sample"),
  442. OPT_STRING('o', "output", &output_name, "file",
  443. "output file name"),
  444. OPT_BOOLEAN('i', "inherit", &inherit,
  445. "child tasks inherit counters"),
  446. OPT_INTEGER('F', "freq", &freq,
  447. "profile at this frequency"),
  448. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  449. "number of mmap data pages"),
  450. OPT_BOOLEAN('g', "call-graph", &call_graph,
  451. "do call-graph (stack chain/backtrace) recording"),
  452. OPT_BOOLEAN('v', "verbose", &verbose,
  453. "be more verbose (show counter open errors, etc)"),
  454. OPT_BOOLEAN('s', "stat", &inherit_stat,
  455. "per thread counts"),
  456. OPT_BOOLEAN('d', "data", &sample_address,
  457. "Sample addresses"),
  458. OPT_BOOLEAN('n', "no-samples", &no_samples,
  459. "don't sample"),
  460. OPT_BOOLEAN('M', "multiplex", &multiplex,
  461. "multiplex counter output in a single channel"),
  462. OPT_END()
  463. };
  464. int cmd_record(int argc, const char **argv, const char *prefix __used)
  465. {
  466. int counter;
  467. argc = parse_options(argc, argv, options, record_usage,
  468. PARSE_OPT_STOP_AT_NON_OPTION);
  469. if (!argc && target_pid == -1 && !system_wide)
  470. usage_with_options(record_usage, options);
  471. if (!nr_counters) {
  472. nr_counters = 1;
  473. attrs[0].type = PERF_TYPE_HARDWARE;
  474. attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
  475. }
  476. /*
  477. * User specified count overrides default frequency.
  478. */
  479. if (default_interval)
  480. freq = 0;
  481. else if (freq) {
  482. default_interval = freq;
  483. } else {
  484. fprintf(stderr, "frequency and count are zero, aborting\n");
  485. exit(EXIT_FAILURE);
  486. }
  487. for (counter = 0; counter < nr_counters; counter++) {
  488. if (attrs[counter].sample_period)
  489. continue;
  490. attrs[counter].sample_period = default_interval;
  491. }
  492. return __cmd_record(argc, argv);
  493. }