builtin-record.c 11 KB

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