builtin-record.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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_RAW;
  323. attr->mmap = track;
  324. attr->comm = track;
  325. attr->inherit = (cpu < 0) && inherit;
  326. attr->disabled = 1;
  327. try_again:
  328. fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
  329. if (fd[nr_cpu][counter] < 0) {
  330. int err = errno;
  331. if (err == EPERM)
  332. die("Permission error - are you root?\n");
  333. else if (err == ENODEV && profile_cpu != -1)
  334. die("No such device - did you specify an out-of-range profile CPU?\n");
  335. /*
  336. * If it's cycles then fall back to hrtimer
  337. * based cpu-clock-tick sw counter, which
  338. * is always available even if no PMU support:
  339. */
  340. if (attr->type == PERF_TYPE_HARDWARE
  341. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  342. if (verbose)
  343. warning(" ... trying to fall back to cpu-clock-ticks\n");
  344. attr->type = PERF_TYPE_SOFTWARE;
  345. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  346. goto try_again;
  347. }
  348. printf("\n");
  349. error("perfcounter syscall returned with %d (%s)\n",
  350. fd[nr_cpu][counter], strerror(err));
  351. die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
  352. exit(-1);
  353. }
  354. h_attr = get_header_attr(attr, counter);
  355. if (!file_new) {
  356. if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
  357. fprintf(stderr, "incompatible append\n");
  358. exit(-1);
  359. }
  360. }
  361. if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
  362. perror("Unable to read perf file descriptor\n");
  363. exit(-1);
  364. }
  365. perf_header_attr__add_id(h_attr, read_data.id);
  366. assert(fd[nr_cpu][counter] >= 0);
  367. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  368. /*
  369. * First counter acts as the group leader:
  370. */
  371. if (group && group_fd == -1)
  372. group_fd = fd[nr_cpu][counter];
  373. event_array[nr_poll].fd = fd[nr_cpu][counter];
  374. event_array[nr_poll].events = POLLIN;
  375. nr_poll++;
  376. mmap_array[nr_cpu][counter].counter = counter;
  377. mmap_array[nr_cpu][counter].prev = 0;
  378. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  379. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  380. PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
  381. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  382. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  383. exit(-1);
  384. }
  385. ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
  386. }
  387. static void open_counters(int cpu, pid_t pid)
  388. {
  389. int counter;
  390. group_fd = -1;
  391. for (counter = 0; counter < nr_counters; counter++)
  392. create_counter(counter, cpu, pid);
  393. nr_cpu++;
  394. }
  395. static void atexit_header(void)
  396. {
  397. header->data_size += bytes_written;
  398. perf_header__write(header, output);
  399. }
  400. static int __cmd_record(int argc, const char **argv)
  401. {
  402. int i, counter;
  403. struct stat st;
  404. pid_t pid = 0;
  405. int flags;
  406. int ret;
  407. page_size = sysconf(_SC_PAGE_SIZE);
  408. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  409. assert(nr_cpus <= MAX_NR_CPUS);
  410. assert(nr_cpus >= 0);
  411. atexit(sig_atexit);
  412. signal(SIGCHLD, sig_handler);
  413. signal(SIGINT, sig_handler);
  414. if (raw_samples)
  415. read_tracing_data();
  416. if (!stat(output_name, &st) && st.st_size) {
  417. if (!force && !append_file) {
  418. fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
  419. output_name);
  420. exit(-1);
  421. }
  422. } else {
  423. append_file = 0;
  424. }
  425. flags = O_CREAT|O_RDWR;
  426. if (append_file)
  427. file_new = 0;
  428. else
  429. flags |= O_TRUNC;
  430. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  431. if (output < 0) {
  432. perror("failed to create output file");
  433. exit(-1);
  434. }
  435. if (!file_new)
  436. header = perf_header__read(output);
  437. else
  438. header = perf_header__new();
  439. atexit(atexit_header);
  440. if (!system_wide) {
  441. pid = target_pid;
  442. if (pid == -1)
  443. pid = getpid();
  444. open_counters(profile_cpu, pid);
  445. } else {
  446. if (profile_cpu != -1) {
  447. open_counters(profile_cpu, target_pid);
  448. } else {
  449. for (i = 0; i < nr_cpus; i++)
  450. open_counters(i, target_pid);
  451. }
  452. }
  453. if (file_new)
  454. perf_header__write(header, output);
  455. if (!system_wide) {
  456. pid_t tgid = pid_synthesize_comm_event(pid, 0);
  457. pid_synthesize_mmap_samples(pid, tgid);
  458. } else
  459. synthesize_all();
  460. if (target_pid == -1 && argc) {
  461. pid = fork();
  462. if (pid < 0)
  463. perror("failed to fork");
  464. if (!pid) {
  465. if (execvp(argv[0], (char **)argv)) {
  466. perror(argv[0]);
  467. exit(-1);
  468. }
  469. }
  470. }
  471. if (realtime_prio) {
  472. struct sched_param param;
  473. param.sched_priority = realtime_prio;
  474. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  475. printf("Could not set realtime priority.\n");
  476. exit(-1);
  477. }
  478. }
  479. for (;;) {
  480. int hits = samples;
  481. for (i = 0; i < nr_cpu; i++) {
  482. for (counter = 0; counter < nr_counters; counter++)
  483. mmap_read(&mmap_array[i][counter]);
  484. }
  485. if (hits == samples) {
  486. if (done)
  487. break;
  488. ret = poll(event_array, nr_poll, 100);
  489. }
  490. }
  491. /*
  492. * Approximate RIP event size: 24 bytes.
  493. */
  494. fprintf(stderr,
  495. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  496. (double)bytes_written / 1024.0 / 1024.0,
  497. output_name,
  498. bytes_written / 24);
  499. return 0;
  500. }
  501. static const char * const record_usage[] = {
  502. "perf record [<options>] [<command>]",
  503. "perf record [<options>] -- <command> [<options>]",
  504. NULL
  505. };
  506. static const struct option options[] = {
  507. OPT_CALLBACK('e', "event", NULL, "event",
  508. "event selector. use 'perf list' to list available events",
  509. parse_events),
  510. OPT_INTEGER('p', "pid", &target_pid,
  511. "record events on existing pid"),
  512. OPT_INTEGER('r', "realtime", &realtime_prio,
  513. "collect data with this RT SCHED_FIFO priority"),
  514. OPT_BOOLEAN('R', "raw-samples", &raw_samples,
  515. "collect raw sample records from all opened counters"),
  516. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  517. "system-wide collection from all CPUs"),
  518. OPT_BOOLEAN('A', "append", &append_file,
  519. "append to the output file to do incremental profiling"),
  520. OPT_INTEGER('C', "profile_cpu", &profile_cpu,
  521. "CPU to profile on"),
  522. OPT_BOOLEAN('f', "force", &force,
  523. "overwrite existing data file"),
  524. OPT_LONG('c', "count", &default_interval,
  525. "event period to sample"),
  526. OPT_STRING('o', "output", &output_name, "file",
  527. "output file name"),
  528. OPT_BOOLEAN('i', "inherit", &inherit,
  529. "child tasks inherit counters"),
  530. OPT_INTEGER('F', "freq", &freq,
  531. "profile at this frequency"),
  532. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  533. "number of mmap data pages"),
  534. OPT_BOOLEAN('g', "call-graph", &call_graph,
  535. "do call-graph (stack chain/backtrace) recording"),
  536. OPT_BOOLEAN('v', "verbose", &verbose,
  537. "be more verbose (show counter open errors, etc)"),
  538. OPT_BOOLEAN('s', "stat", &inherit_stat,
  539. "per thread counts"),
  540. OPT_BOOLEAN('d', "data", &sample_address,
  541. "Sample addresses"),
  542. OPT_BOOLEAN('n', "no-samples", &no_samples,
  543. "don't sample"),
  544. OPT_END()
  545. };
  546. int cmd_record(int argc, const char **argv, const char *prefix __used)
  547. {
  548. int counter;
  549. argc = parse_options(argc, argv, options, record_usage,
  550. PARSE_OPT_STOP_AT_NON_OPTION);
  551. if (!argc && target_pid == -1 && !system_wide)
  552. usage_with_options(record_usage, options);
  553. if (!nr_counters) {
  554. nr_counters = 1;
  555. attrs[0].type = PERF_TYPE_HARDWARE;
  556. attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
  557. }
  558. for (counter = 0; counter < nr_counters; counter++) {
  559. if (attrs[counter].sample_period)
  560. continue;
  561. attrs[counter].sample_period = default_interval;
  562. }
  563. return __cmd_record(argc, argv);
  564. }