builtin-record.c 12 KB

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