builtin-record.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 <unistd.h>
  15. #include <sched.h>
  16. #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
  17. #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
  18. static long default_interval = 100000;
  19. static long event_count[MAX_COUNTERS];
  20. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  21. static int nr_cpus = 0;
  22. static unsigned int page_size;
  23. static unsigned int mmap_pages = 128;
  24. static int freq = 0;
  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 system_wide = 0;
  30. static pid_t target_pid = -1;
  31. static int inherit = 1;
  32. static int force = 0;
  33. static int append_file = 0;
  34. const unsigned int default_count[] = {
  35. 1000000,
  36. 1000000,
  37. 10000,
  38. 10000,
  39. 1000000,
  40. 10000,
  41. };
  42. struct mmap_data {
  43. int counter;
  44. void *base;
  45. unsigned int mask;
  46. unsigned int prev;
  47. };
  48. static unsigned int mmap_read_head(struct mmap_data *md)
  49. {
  50. struct perf_counter_mmap_page *pc = md->base;
  51. int head;
  52. head = pc->data_head;
  53. rmb();
  54. return head;
  55. }
  56. static long samples;
  57. static struct timeval last_read, this_read;
  58. static __u64 bytes_written;
  59. static void mmap_read(struct mmap_data *md)
  60. {
  61. unsigned int head = mmap_read_head(md);
  62. unsigned int old = md->prev;
  63. unsigned char *data = md->base + page_size;
  64. unsigned long size;
  65. void *buf;
  66. int diff;
  67. gettimeofday(&this_read, NULL);
  68. /*
  69. * If we're further behind than half the buffer, there's a chance
  70. * the writer will bite our tail and mess up the samples under us.
  71. *
  72. * If we somehow ended up ahead of the head, we got messed up.
  73. *
  74. * In either case, truncate and restart at head.
  75. */
  76. diff = head - old;
  77. if (diff > md->mask / 2 || diff < 0) {
  78. struct timeval iv;
  79. unsigned long msecs;
  80. timersub(&this_read, &last_read, &iv);
  81. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  82. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  83. " Last read %lu msecs ago.\n", msecs);
  84. /*
  85. * head points to a known good entry, start there.
  86. */
  87. old = head;
  88. }
  89. last_read = this_read;
  90. if (old != head)
  91. samples++;
  92. size = head - old;
  93. if ((old & md->mask) + size != (head & md->mask)) {
  94. buf = &data[old & md->mask];
  95. size = md->mask + 1 - (old & md->mask);
  96. old += size;
  97. while (size) {
  98. int ret = write(output, buf, size);
  99. if (ret < 0)
  100. die("failed to write");
  101. size -= ret;
  102. buf += ret;
  103. bytes_written += ret;
  104. }
  105. }
  106. buf = &data[old & md->mask];
  107. size = head - old;
  108. old += size;
  109. while (size) {
  110. int ret = write(output, buf, size);
  111. if (ret < 0)
  112. die("failed to write");
  113. size -= ret;
  114. buf += ret;
  115. bytes_written += ret;
  116. }
  117. md->prev = old;
  118. }
  119. static volatile int done = 0;
  120. static void sig_handler(int sig)
  121. {
  122. done = 1;
  123. }
  124. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  125. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  126. static int nr_poll;
  127. static int nr_cpu;
  128. struct mmap_event {
  129. struct perf_event_header header;
  130. __u32 pid;
  131. __u32 tid;
  132. __u64 start;
  133. __u64 len;
  134. __u64 pgoff;
  135. char filename[PATH_MAX];
  136. };
  137. struct comm_event {
  138. struct perf_event_header header;
  139. __u32 pid;
  140. __u32 tid;
  141. char comm[16];
  142. };
  143. static void pid_synthesize_comm_event(pid_t pid, int full)
  144. {
  145. struct comm_event comm_ev;
  146. char filename[PATH_MAX];
  147. char bf[BUFSIZ];
  148. int fd, ret;
  149. size_t size;
  150. char *field, *sep;
  151. DIR *tasks;
  152. struct dirent dirent, *next;
  153. snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
  154. fd = open(filename, O_RDONLY);
  155. if (fd < 0) {
  156. fprintf(stderr, "couldn't open %s\n", filename);
  157. exit(EXIT_FAILURE);
  158. }
  159. if (read(fd, bf, sizeof(bf)) < 0) {
  160. fprintf(stderr, "couldn't read %s\n", filename);
  161. exit(EXIT_FAILURE);
  162. }
  163. close(fd);
  164. /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
  165. memset(&comm_ev, 0, sizeof(comm_ev));
  166. field = strchr(bf, '(');
  167. if (field == NULL)
  168. goto out_failure;
  169. sep = strchr(++field, ')');
  170. if (sep == NULL)
  171. goto out_failure;
  172. size = sep - field;
  173. memcpy(comm_ev.comm, field, size++);
  174. comm_ev.pid = pid;
  175. comm_ev.header.type = PERF_EVENT_COMM;
  176. size = ALIGN(size, sizeof(uint64_t));
  177. comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
  178. if (!full) {
  179. comm_ev.tid = pid;
  180. ret = write(output, &comm_ev, comm_ev.header.size);
  181. if (ret < 0) {
  182. perror("failed to write");
  183. exit(-1);
  184. }
  185. return;
  186. }
  187. snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
  188. tasks = opendir(filename);
  189. while (!readdir_r(tasks, &dirent, &next) && next) {
  190. char *end;
  191. pid = strtol(dirent.d_name, &end, 10);
  192. if (*end)
  193. continue;
  194. comm_ev.tid = pid;
  195. ret = write(output, &comm_ev, comm_ev.header.size);
  196. if (ret < 0) {
  197. perror("failed to write");
  198. exit(-1);
  199. }
  200. }
  201. closedir(tasks);
  202. return;
  203. out_failure:
  204. fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
  205. filename);
  206. exit(EXIT_FAILURE);
  207. }
  208. static void pid_synthesize_mmap_samples(pid_t pid)
  209. {
  210. char filename[PATH_MAX];
  211. FILE *fp;
  212. snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
  213. fp = fopen(filename, "r");
  214. if (fp == NULL) {
  215. fprintf(stderr, "couldn't open %s\n", filename);
  216. exit(EXIT_FAILURE);
  217. }
  218. while (1) {
  219. char bf[BUFSIZ], *pbf = bf;
  220. struct mmap_event mmap_ev = {
  221. .header.type = PERF_EVENT_MMAP,
  222. };
  223. int n;
  224. size_t size;
  225. if (fgets(bf, sizeof(bf), fp) == NULL)
  226. break;
  227. /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
  228. n = hex2u64(pbf, &mmap_ev.start);
  229. if (n < 0)
  230. continue;
  231. pbf += n + 1;
  232. n = hex2u64(pbf, &mmap_ev.len);
  233. if (n < 0)
  234. continue;
  235. pbf += n + 3;
  236. if (*pbf == 'x') { /* vm_exec */
  237. char *execname = strrchr(bf, ' ');
  238. if (execname == NULL || execname[1] != '/')
  239. continue;
  240. execname += 1;
  241. size = strlen(execname);
  242. execname[size - 1] = '\0'; /* Remove \n */
  243. memcpy(mmap_ev.filename, execname, size);
  244. size = ALIGN(size, sizeof(uint64_t));
  245. mmap_ev.len -= mmap_ev.start;
  246. mmap_ev.header.size = (sizeof(mmap_ev) -
  247. (sizeof(mmap_ev.filename) - size));
  248. mmap_ev.pid = pid;
  249. mmap_ev.tid = pid;
  250. if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
  251. perror("failed to write");
  252. exit(-1);
  253. }
  254. }
  255. }
  256. fclose(fp);
  257. }
  258. static void synthesize_samples(void)
  259. {
  260. DIR *proc;
  261. struct dirent dirent, *next;
  262. proc = opendir("/proc");
  263. while (!readdir_r(proc, &dirent, &next) && next) {
  264. char *end;
  265. pid_t pid;
  266. pid = strtol(dirent.d_name, &end, 10);
  267. if (*end) /* only interested in proper numerical dirents */
  268. continue;
  269. pid_synthesize_comm_event(pid, 1);
  270. pid_synthesize_mmap_samples(pid);
  271. }
  272. closedir(proc);
  273. }
  274. static int group_fd;
  275. static void create_counter(int counter, int cpu, pid_t pid)
  276. {
  277. struct perf_counter_attr attr;
  278. int track = 1;
  279. memset(&attr, 0, sizeof(attr));
  280. attr.config = event_id[counter];
  281. attr.sample_period = event_count[counter];
  282. attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD;
  283. if (freq) {
  284. attr.freq = 1;
  285. attr.sample_freq = freq;
  286. }
  287. attr.mmap = track;
  288. attr.comm = track;
  289. attr.inherit = (cpu < 0) && inherit;
  290. track = 0; /* only the first counter needs these */
  291. fd[nr_cpu][counter] = sys_perf_counter_open(&attr, pid, cpu, group_fd, 0);
  292. if (fd[nr_cpu][counter] < 0) {
  293. int err = errno;
  294. error("syscall returned with %d (%s)\n",
  295. fd[nr_cpu][counter], strerror(err));
  296. if (err == EPERM)
  297. printf("Are you root?\n");
  298. exit(-1);
  299. }
  300. assert(fd[nr_cpu][counter] >= 0);
  301. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  302. /*
  303. * First counter acts as the group leader:
  304. */
  305. if (group && group_fd == -1)
  306. group_fd = fd[nr_cpu][counter];
  307. event_array[nr_poll].fd = fd[nr_cpu][counter];
  308. event_array[nr_poll].events = POLLIN;
  309. nr_poll++;
  310. mmap_array[nr_cpu][counter].counter = counter;
  311. mmap_array[nr_cpu][counter].prev = 0;
  312. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  313. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  314. PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
  315. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  316. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  317. exit(-1);
  318. }
  319. }
  320. static void open_counters(int cpu, pid_t pid)
  321. {
  322. int counter;
  323. if (pid > 0) {
  324. pid_synthesize_comm_event(pid, 0);
  325. pid_synthesize_mmap_samples(pid);
  326. }
  327. group_fd = -1;
  328. for (counter = 0; counter < nr_counters; counter++)
  329. create_counter(counter, cpu, pid);
  330. nr_cpu++;
  331. }
  332. static int __cmd_record(int argc, const char **argv)
  333. {
  334. int i, counter;
  335. struct stat st;
  336. pid_t pid;
  337. int flags;
  338. int ret;
  339. page_size = sysconf(_SC_PAGE_SIZE);
  340. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  341. assert(nr_cpus <= MAX_NR_CPUS);
  342. assert(nr_cpus >= 0);
  343. if (!stat(output_name, &st) && !force && !append_file) {
  344. fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
  345. output_name);
  346. exit(-1);
  347. }
  348. flags = O_CREAT|O_RDWR;
  349. if (append_file)
  350. flags |= O_APPEND;
  351. else
  352. flags |= O_TRUNC;
  353. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  354. if (output < 0) {
  355. perror("failed to create output file");
  356. exit(-1);
  357. }
  358. if (!system_wide) {
  359. open_counters(-1, target_pid != -1 ? target_pid : getpid());
  360. } else for (i = 0; i < nr_cpus; i++)
  361. open_counters(i, target_pid);
  362. signal(SIGCHLD, sig_handler);
  363. signal(SIGINT, sig_handler);
  364. if (target_pid == -1 && argc) {
  365. pid = fork();
  366. if (pid < 0)
  367. perror("failed to fork");
  368. if (!pid) {
  369. if (execvp(argv[0], (char **)argv)) {
  370. perror(argv[0]);
  371. exit(-1);
  372. }
  373. }
  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. printf("Could not set realtime priority.\n");
  380. exit(-1);
  381. }
  382. }
  383. if (system_wide)
  384. synthesize_samples();
  385. while (!done) {
  386. int hits = samples;
  387. for (i = 0; i < nr_cpu; i++) {
  388. for (counter = 0; counter < nr_counters; counter++)
  389. mmap_read(&mmap_array[i][counter]);
  390. }
  391. if (hits == samples)
  392. ret = poll(event_array, nr_poll, 100);
  393. }
  394. /*
  395. * Approximate RIP event size: 24 bytes.
  396. */
  397. fprintf(stderr,
  398. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  399. (double)bytes_written / 1024.0 / 1024.0,
  400. output_name,
  401. bytes_written / 24);
  402. return 0;
  403. }
  404. static const char * const record_usage[] = {
  405. "perf record [<options>] [<command>]",
  406. "perf record [<options>] -- <command> [<options>]",
  407. NULL
  408. };
  409. static char events_help_msg[EVENTS_HELP_MAX];
  410. static const struct option options[] = {
  411. OPT_CALLBACK('e', "event", NULL, "event",
  412. events_help_msg, parse_events),
  413. OPT_INTEGER('p', "pid", &target_pid,
  414. "record events on existing pid"),
  415. OPT_INTEGER('r', "realtime", &realtime_prio,
  416. "collect data with this RT SCHED_FIFO priority"),
  417. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  418. "system-wide collection from all CPUs"),
  419. OPT_BOOLEAN('A', "append", &append_file,
  420. "append to the output file to do incremental profiling"),
  421. OPT_BOOLEAN('f', "force", &force,
  422. "overwrite existing data file"),
  423. OPT_LONG('c', "count", &default_interval,
  424. "event period to sample"),
  425. OPT_STRING('o', "output", &output_name, "file",
  426. "output file name"),
  427. OPT_BOOLEAN('i', "inherit", &inherit,
  428. "child tasks inherit counters"),
  429. OPT_INTEGER('F', "freq", &freq,
  430. "profile at this frequency"),
  431. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  432. "number of mmap data pages"),
  433. OPT_END()
  434. };
  435. int cmd_record(int argc, const char **argv, const char *prefix)
  436. {
  437. int counter;
  438. create_events_help(events_help_msg);
  439. argc = parse_options(argc, argv, options, record_usage, 0);
  440. if (!argc && target_pid == -1 && !system_wide)
  441. usage_with_options(record_usage, options);
  442. if (!nr_counters) {
  443. nr_counters = 1;
  444. event_id[0] = 0;
  445. }
  446. for (counter = 0; counter < nr_counters; counter++) {
  447. if (event_count[counter])
  448. continue;
  449. event_count[counter] = default_interval;
  450. }
  451. return __cmd_record(argc, argv);
  452. }