builtin-record.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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 "util/trace-event.h"
  18. #include <unistd.h>
  19. #include <sched.h>
  20. #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
  21. #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
  22. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  23. static long default_interval = 100000;
  24. static int nr_cpus = 0;
  25. static unsigned int page_size;
  26. static unsigned int mmap_pages = 128;
  27. static int freq = 0;
  28. static int output;
  29. static const char *output_name = "perf.data";
  30. static int group = 0;
  31. static unsigned int realtime_prio = 0;
  32. static int raw_samples = 0;
  33. static int system_wide = 0;
  34. static int profile_cpu = -1;
  35. static pid_t target_pid = -1;
  36. static int inherit = 1;
  37. static int force = 0;
  38. static int append_file = 0;
  39. static int call_graph = 0;
  40. static int inherit_stat = 0;
  41. static int no_samples = 0;
  42. static int sample_address = 0;
  43. static long samples;
  44. static struct timeval last_read;
  45. static struct timeval this_read;
  46. static u64 bytes_written;
  47. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  48. static int nr_poll;
  49. static int nr_cpu;
  50. static int file_new = 1;
  51. struct perf_header *header;
  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_counter_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_counter_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 void mmap_read(struct mmap_data *md)
  88. {
  89. unsigned int head = mmap_read_head(md);
  90. unsigned int old = md->prev;
  91. unsigned char *data = md->base + page_size;
  92. unsigned long size;
  93. void *buf;
  94. int diff;
  95. gettimeofday(&this_read, NULL);
  96. /*
  97. * If we're further behind than half the buffer, there's a chance
  98. * the writer will bite our tail and mess up the samples under us.
  99. *
  100. * If we somehow ended up ahead of the head, we got messed up.
  101. *
  102. * In either case, truncate and restart at head.
  103. */
  104. diff = head - old;
  105. if (diff < 0) {
  106. struct timeval iv;
  107. unsigned long msecs;
  108. timersub(&this_read, &last_read, &iv);
  109. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  110. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  111. " Last read %lu msecs ago.\n", msecs);
  112. /*
  113. * head points to a known good entry, start there.
  114. */
  115. old = head;
  116. }
  117. last_read = this_read;
  118. if (old != head)
  119. samples++;
  120. size = head - old;
  121. if ((old & md->mask) + size != (head & md->mask)) {
  122. buf = &data[old & md->mask];
  123. size = md->mask + 1 - (old & md->mask);
  124. old += size;
  125. write_output(buf, size);
  126. }
  127. buf = &data[old & md->mask];
  128. size = head - old;
  129. old += size;
  130. write_output(buf, size);
  131. md->prev = old;
  132. mmap_write_tail(md, old);
  133. }
  134. static volatile int done = 0;
  135. static volatile int signr = -1;
  136. static void sig_handler(int sig)
  137. {
  138. done = 1;
  139. signr = sig;
  140. }
  141. static void sig_atexit(void)
  142. {
  143. if (signr == -1)
  144. return;
  145. signal(signr, SIG_DFL);
  146. kill(getpid(), signr);
  147. }
  148. static pid_t pid_synthesize_comm_event(pid_t pid, int full)
  149. {
  150. struct comm_event comm_ev;
  151. char filename[PATH_MAX];
  152. char bf[BUFSIZ];
  153. FILE *fp;
  154. size_t size = 0;
  155. DIR *tasks;
  156. struct dirent dirent, *next;
  157. pid_t tgid = 0;
  158. snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
  159. fp = fopen(filename, "r");
  160. if (fp == NULL) {
  161. /*
  162. * We raced with a task exiting - just return:
  163. */
  164. if (verbose)
  165. fprintf(stderr, "couldn't open %s\n", filename);
  166. return 0;
  167. }
  168. memset(&comm_ev, 0, sizeof(comm_ev));
  169. while (!comm_ev.comm[0] || !comm_ev.pid) {
  170. if (fgets(bf, sizeof(bf), fp) == NULL)
  171. goto out_failure;
  172. if (memcmp(bf, "Name:", 5) == 0) {
  173. char *name = bf + 5;
  174. while (*name && isspace(*name))
  175. ++name;
  176. size = strlen(name) - 1;
  177. memcpy(comm_ev.comm, name, size++);
  178. } else if (memcmp(bf, "Tgid:", 5) == 0) {
  179. char *tgids = bf + 5;
  180. while (*tgids && isspace(*tgids))
  181. ++tgids;
  182. tgid = comm_ev.pid = atoi(tgids);
  183. }
  184. }
  185. comm_ev.header.type = PERF_EVENT_COMM;
  186. size = ALIGN(size, sizeof(u64));
  187. comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
  188. if (!full) {
  189. comm_ev.tid = pid;
  190. write_output(&comm_ev, comm_ev.header.size);
  191. goto out_fclose;
  192. }
  193. snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
  194. tasks = opendir(filename);
  195. while (!readdir_r(tasks, &dirent, &next) && next) {
  196. char *end;
  197. pid = strtol(dirent.d_name, &end, 10);
  198. if (*end)
  199. continue;
  200. comm_ev.tid = pid;
  201. write_output(&comm_ev, comm_ev.header.size);
  202. }
  203. closedir(tasks);
  204. out_fclose:
  205. fclose(fp);
  206. return tgid;
  207. out_failure:
  208. fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
  209. filename);
  210. exit(EXIT_FAILURE);
  211. }
  212. static void pid_synthesize_mmap_samples(pid_t pid, pid_t tgid)
  213. {
  214. char filename[PATH_MAX];
  215. FILE *fp;
  216. snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
  217. fp = fopen(filename, "r");
  218. if (fp == NULL) {
  219. /*
  220. * We raced with a task exiting - just return:
  221. */
  222. if (verbose)
  223. fprintf(stderr, "couldn't open %s\n", filename);
  224. return;
  225. }
  226. while (1) {
  227. char bf[BUFSIZ], *pbf = bf;
  228. struct mmap_event mmap_ev = {
  229. .header = { .type = PERF_EVENT_MMAP },
  230. };
  231. int n;
  232. size_t size;
  233. if (fgets(bf, sizeof(bf), fp) == NULL)
  234. break;
  235. /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
  236. n = hex2u64(pbf, &mmap_ev.start);
  237. if (n < 0)
  238. continue;
  239. pbf += n + 1;
  240. n = hex2u64(pbf, &mmap_ev.len);
  241. if (n < 0)
  242. continue;
  243. pbf += n + 3;
  244. if (*pbf == 'x') { /* vm_exec */
  245. char *execname = strchr(bf, '/');
  246. /* Catch VDSO */
  247. if (execname == NULL)
  248. execname = strstr(bf, "[vdso]");
  249. if (execname == NULL)
  250. continue;
  251. size = strlen(execname);
  252. execname[size - 1] = '\0'; /* Remove \n */
  253. memcpy(mmap_ev.filename, execname, size);
  254. size = ALIGN(size, sizeof(u64));
  255. mmap_ev.len -= mmap_ev.start;
  256. mmap_ev.header.size = (sizeof(mmap_ev) -
  257. (sizeof(mmap_ev.filename) - size));
  258. mmap_ev.pid = tgid;
  259. mmap_ev.tid = pid;
  260. write_output(&mmap_ev, mmap_ev.header.size);
  261. }
  262. }
  263. fclose(fp);
  264. }
  265. static void synthesize_all(void)
  266. {
  267. DIR *proc;
  268. struct dirent dirent, *next;
  269. proc = opendir("/proc");
  270. while (!readdir_r(proc, &dirent, &next) && next) {
  271. char *end;
  272. pid_t pid, tgid;
  273. pid = strtol(dirent.d_name, &end, 10);
  274. if (*end) /* only interested in proper numerical dirents */
  275. continue;
  276. tgid = pid_synthesize_comm_event(pid, 1);
  277. pid_synthesize_mmap_samples(pid, tgid);
  278. }
  279. closedir(proc);
  280. }
  281. static int group_fd;
  282. static struct perf_header_attr *get_header_attr(struct perf_counter_attr *a, int nr)
  283. {
  284. struct perf_header_attr *h_attr;
  285. if (nr < header->attrs) {
  286. h_attr = header->attr[nr];
  287. } else {
  288. h_attr = perf_header_attr__new(a);
  289. perf_header__add_attr(header, h_attr);
  290. }
  291. return h_attr;
  292. }
  293. static void create_counter(int counter, int cpu, pid_t pid)
  294. {
  295. struct perf_counter_attr *attr = attrs + counter;
  296. struct perf_header_attr *h_attr;
  297. int track = !counter; /* only the first counter needs these */
  298. struct {
  299. u64 count;
  300. u64 time_enabled;
  301. u64 time_running;
  302. u64 id;
  303. } read_data;
  304. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  305. PERF_FORMAT_TOTAL_TIME_RUNNING |
  306. PERF_FORMAT_ID;
  307. attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  308. if (freq) {
  309. attr->sample_type |= PERF_SAMPLE_PERIOD;
  310. attr->freq = 1;
  311. attr->sample_freq = freq;
  312. }
  313. if (no_samples)
  314. attr->sample_freq = 0;
  315. if (inherit_stat)
  316. attr->inherit_stat = 1;
  317. if (sample_address)
  318. attr->sample_type |= PERF_SAMPLE_ADDR;
  319. if (call_graph)
  320. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  321. if (raw_samples) {
  322. attr->sample_type |= PERF_SAMPLE_TIME;
  323. attr->sample_type |= PERF_SAMPLE_RAW;
  324. attr->sample_type |= PERF_SAMPLE_CPU;
  325. }
  326. attr->mmap = track;
  327. attr->comm = track;
  328. attr->inherit = (cpu < 0) && inherit;
  329. attr->disabled = 1;
  330. try_again:
  331. fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
  332. if (fd[nr_cpu][counter] < 0) {
  333. int err = errno;
  334. if (err == EPERM)
  335. die("Permission error - are you root?\n");
  336. else if (err == ENODEV && profile_cpu != -1)
  337. die("No such device - did you specify an out-of-range profile CPU?\n");
  338. /*
  339. * If it's cycles then fall back to hrtimer
  340. * based cpu-clock-tick sw counter, which
  341. * is always available even if no PMU support:
  342. */
  343. if (attr->type == PERF_TYPE_HARDWARE
  344. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  345. if (verbose)
  346. warning(" ... trying to fall back to cpu-clock-ticks\n");
  347. attr->type = PERF_TYPE_SOFTWARE;
  348. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  349. goto try_again;
  350. }
  351. printf("\n");
  352. error("perfcounter syscall returned with %d (%s)\n",
  353. fd[nr_cpu][counter], strerror(err));
  354. die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
  355. exit(-1);
  356. }
  357. h_attr = get_header_attr(attr, counter);
  358. if (!file_new) {
  359. if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
  360. fprintf(stderr, "incompatible append\n");
  361. exit(-1);
  362. }
  363. }
  364. if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
  365. perror("Unable to read perf file descriptor\n");
  366. exit(-1);
  367. }
  368. perf_header_attr__add_id(h_attr, read_data.id);
  369. assert(fd[nr_cpu][counter] >= 0);
  370. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  371. /*
  372. * First counter acts as the group leader:
  373. */
  374. if (group && group_fd == -1)
  375. group_fd = fd[nr_cpu][counter];
  376. event_array[nr_poll].fd = fd[nr_cpu][counter];
  377. event_array[nr_poll].events = POLLIN;
  378. nr_poll++;
  379. mmap_array[nr_cpu][counter].counter = counter;
  380. mmap_array[nr_cpu][counter].prev = 0;
  381. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  382. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  383. PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
  384. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  385. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  386. exit(-1);
  387. }
  388. ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
  389. }
  390. static void open_counters(int cpu, pid_t pid)
  391. {
  392. int counter;
  393. group_fd = -1;
  394. for (counter = 0; counter < nr_counters; counter++)
  395. create_counter(counter, cpu, pid);
  396. nr_cpu++;
  397. }
  398. static void atexit_header(void)
  399. {
  400. header->data_size += bytes_written;
  401. perf_header__write(header, output);
  402. }
  403. static int __cmd_record(int argc, const char **argv)
  404. {
  405. int i, counter;
  406. struct stat st;
  407. pid_t pid = 0;
  408. int flags;
  409. int ret;
  410. page_size = sysconf(_SC_PAGE_SIZE);
  411. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  412. assert(nr_cpus <= MAX_NR_CPUS);
  413. assert(nr_cpus >= 0);
  414. atexit(sig_atexit);
  415. signal(SIGCHLD, sig_handler);
  416. signal(SIGINT, sig_handler);
  417. if (!stat(output_name, &st) && st.st_size) {
  418. if (!force && !append_file) {
  419. fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
  420. output_name);
  421. exit(-1);
  422. }
  423. } else {
  424. append_file = 0;
  425. }
  426. flags = O_CREAT|O_RDWR;
  427. if (append_file)
  428. file_new = 0;
  429. else
  430. flags |= O_TRUNC;
  431. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  432. if (output < 0) {
  433. perror("failed to create output file");
  434. exit(-1);
  435. }
  436. if (!file_new)
  437. header = perf_header__read(output);
  438. else
  439. header = perf_header__new();
  440. if (raw_samples) {
  441. read_tracing_data(attrs, nr_counters);
  442. } else {
  443. for (i = 0; i < nr_counters; i++) {
  444. if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
  445. read_tracing_data(attrs, nr_counters);
  446. break;
  447. }
  448. }
  449. }
  450. atexit(atexit_header);
  451. if (!system_wide) {
  452. pid = target_pid;
  453. if (pid == -1)
  454. pid = getpid();
  455. open_counters(profile_cpu, pid);
  456. } else {
  457. if (profile_cpu != -1) {
  458. open_counters(profile_cpu, target_pid);
  459. } else {
  460. for (i = 0; i < nr_cpus; i++)
  461. open_counters(i, target_pid);
  462. }
  463. }
  464. if (file_new)
  465. perf_header__write(header, output);
  466. if (!system_wide) {
  467. pid_t tgid = pid_synthesize_comm_event(pid, 0);
  468. pid_synthesize_mmap_samples(pid, tgid);
  469. } else
  470. synthesize_all();
  471. if (target_pid == -1 && argc) {
  472. pid = fork();
  473. if (pid < 0)
  474. perror("failed to fork");
  475. if (!pid) {
  476. if (execvp(argv[0], (char **)argv)) {
  477. perror(argv[0]);
  478. exit(-1);
  479. }
  480. }
  481. }
  482. if (realtime_prio) {
  483. struct sched_param param;
  484. param.sched_priority = realtime_prio;
  485. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  486. printf("Could not set realtime priority.\n");
  487. exit(-1);
  488. }
  489. }
  490. for (;;) {
  491. int hits = samples;
  492. for (i = 0; i < nr_cpu; i++) {
  493. for (counter = 0; counter < nr_counters; counter++)
  494. mmap_read(&mmap_array[i][counter]);
  495. }
  496. if (hits == samples) {
  497. if (done)
  498. break;
  499. ret = poll(event_array, nr_poll, 100);
  500. }
  501. }
  502. /*
  503. * Approximate RIP event size: 24 bytes.
  504. */
  505. fprintf(stderr,
  506. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  507. (double)bytes_written / 1024.0 / 1024.0,
  508. output_name,
  509. bytes_written / 24);
  510. return 0;
  511. }
  512. static const char * const record_usage[] = {
  513. "perf record [<options>] [<command>]",
  514. "perf record [<options>] -- <command> [<options>]",
  515. NULL
  516. };
  517. static const struct option options[] = {
  518. OPT_CALLBACK('e', "event", NULL, "event",
  519. "event selector. use 'perf list' to list available events",
  520. parse_events),
  521. OPT_INTEGER('p', "pid", &target_pid,
  522. "record events on existing pid"),
  523. OPT_INTEGER('r', "realtime", &realtime_prio,
  524. "collect data with this RT SCHED_FIFO priority"),
  525. OPT_BOOLEAN('R', "raw-samples", &raw_samples,
  526. "collect raw sample records from all opened counters"),
  527. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  528. "system-wide collection from all CPUs"),
  529. OPT_BOOLEAN('A', "append", &append_file,
  530. "append to the output file to do incremental profiling"),
  531. OPT_INTEGER('C', "profile_cpu", &profile_cpu,
  532. "CPU to profile on"),
  533. OPT_BOOLEAN('f', "force", &force,
  534. "overwrite existing data file"),
  535. OPT_LONG('c', "count", &default_interval,
  536. "event period to sample"),
  537. OPT_STRING('o', "output", &output_name, "file",
  538. "output file name"),
  539. OPT_BOOLEAN('i', "inherit", &inherit,
  540. "child tasks inherit counters"),
  541. OPT_INTEGER('F', "freq", &freq,
  542. "profile at this frequency"),
  543. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  544. "number of mmap data pages"),
  545. OPT_BOOLEAN('g', "call-graph", &call_graph,
  546. "do call-graph (stack chain/backtrace) recording"),
  547. OPT_BOOLEAN('v', "verbose", &verbose,
  548. "be more verbose (show counter open errors, etc)"),
  549. OPT_BOOLEAN('s', "stat", &inherit_stat,
  550. "per thread counts"),
  551. OPT_BOOLEAN('d', "data", &sample_address,
  552. "Sample addresses"),
  553. OPT_BOOLEAN('n', "no-samples", &no_samples,
  554. "don't sample"),
  555. OPT_END()
  556. };
  557. int cmd_record(int argc, const char **argv, const char *prefix __used)
  558. {
  559. int counter;
  560. argc = parse_options(argc, argv, options, record_usage,
  561. PARSE_OPT_STOP_AT_NON_OPTION);
  562. if (!argc && target_pid == -1 && !system_wide)
  563. usage_with_options(record_usage, options);
  564. if (!nr_counters) {
  565. nr_counters = 1;
  566. attrs[0].type = PERF_TYPE_HARDWARE;
  567. attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
  568. }
  569. for (counter = 0; counter < nr_counters; counter++) {
  570. if (attrs[counter].sample_period)
  571. continue;
  572. attrs[counter].sample_period = default_interval;
  573. }
  574. return __cmd_record(argc, argv);
  575. }