builtin-record.c 15 KB

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