builtin-record.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. #define _FILE_OFFSET_BITS 64
  9. #include "builtin.h"
  10. #include "perf.h"
  11. #include "util/build-id.h"
  12. #include "util/util.h"
  13. #include "util/parse-options.h"
  14. #include "util/parse-events.h"
  15. #include "util/header.h"
  16. #include "util/event.h"
  17. #include "util/evlist.h"
  18. #include "util/evsel.h"
  19. #include "util/debug.h"
  20. #include "util/session.h"
  21. #include "util/symbol.h"
  22. #include "util/cpumap.h"
  23. #include <unistd.h>
  24. #include <sched.h>
  25. #include <sys/mman.h>
  26. #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
  27. enum write_mode_t {
  28. WRITE_FORCE,
  29. WRITE_APPEND
  30. };
  31. static u64 user_interval = ULLONG_MAX;
  32. static u64 default_interval = 0;
  33. static u64 sample_type;
  34. static struct cpu_map *cpus;
  35. static unsigned int page_size;
  36. static unsigned int mmap_pages = 128;
  37. static unsigned int user_freq = UINT_MAX;
  38. static int freq = 1000;
  39. static int output;
  40. static int pipe_output = 0;
  41. static const char *output_name = "perf.data";
  42. static int group = 0;
  43. static int realtime_prio = 0;
  44. static bool nodelay = false;
  45. static bool raw_samples = false;
  46. static bool sample_id_all_avail = true;
  47. static bool system_wide = false;
  48. static pid_t target_pid = -1;
  49. static pid_t target_tid = -1;
  50. static struct thread_map *threads;
  51. static pid_t child_pid = -1;
  52. static bool no_inherit = false;
  53. static enum write_mode_t write_mode = WRITE_FORCE;
  54. static bool call_graph = false;
  55. static bool inherit_stat = false;
  56. static bool no_samples = false;
  57. static bool sample_address = false;
  58. static bool sample_time = false;
  59. static bool no_buildid = false;
  60. static bool no_buildid_cache = false;
  61. static struct perf_evlist *evsel_list;
  62. static long samples = 0;
  63. static u64 bytes_written = 0;
  64. static struct pollfd *event_array;
  65. static int nr_poll = 0;
  66. static int nr_cpu = 0;
  67. static int file_new = 1;
  68. static off_t post_processing_offset;
  69. static struct perf_session *session;
  70. static const char *cpu_list;
  71. struct mmap_data {
  72. void *base;
  73. unsigned int mask;
  74. unsigned int prev;
  75. };
  76. static struct mmap_data mmap_array[MAX_NR_CPUS];
  77. static unsigned long mmap_read_head(struct mmap_data *md)
  78. {
  79. struct perf_event_mmap_page *pc = md->base;
  80. long head;
  81. head = pc->data_head;
  82. rmb();
  83. return head;
  84. }
  85. static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
  86. {
  87. struct perf_event_mmap_page *pc = md->base;
  88. /*
  89. * ensure all reads are done before we write the tail out.
  90. */
  91. /* mb(); */
  92. pc->data_tail = tail;
  93. }
  94. static void advance_output(size_t size)
  95. {
  96. bytes_written += size;
  97. }
  98. static void write_output(void *buf, size_t size)
  99. {
  100. while (size) {
  101. int ret = write(output, buf, size);
  102. if (ret < 0)
  103. die("failed to write");
  104. size -= ret;
  105. buf += ret;
  106. bytes_written += ret;
  107. }
  108. }
  109. static int process_synthesized_event(event_t *event,
  110. struct sample_data *sample __used,
  111. struct perf_session *self __used)
  112. {
  113. write_output(event, event->header.size);
  114. return 0;
  115. }
  116. static void mmap_read(struct mmap_data *md)
  117. {
  118. unsigned int head = mmap_read_head(md);
  119. unsigned int old = md->prev;
  120. unsigned char *data = md->base + page_size;
  121. unsigned long size;
  122. void *buf;
  123. int diff;
  124. /*
  125. * If we're further behind than half the buffer, there's a chance
  126. * the writer will bite our tail and mess up the samples under us.
  127. *
  128. * If we somehow ended up ahead of the head, we got messed up.
  129. *
  130. * In either case, truncate and restart at head.
  131. */
  132. diff = head - old;
  133. if (diff < 0) {
  134. fprintf(stderr, "WARNING: failed to keep up with mmap data\n");
  135. /*
  136. * head points to a known good entry, start there.
  137. */
  138. old = head;
  139. }
  140. if (old != head)
  141. samples++;
  142. size = head - old;
  143. if ((old & md->mask) + size != (head & md->mask)) {
  144. buf = &data[old & md->mask];
  145. size = md->mask + 1 - (old & md->mask);
  146. old += size;
  147. write_output(buf, size);
  148. }
  149. buf = &data[old & md->mask];
  150. size = head - old;
  151. old += size;
  152. write_output(buf, size);
  153. md->prev = old;
  154. mmap_write_tail(md, old);
  155. }
  156. static volatile int done = 0;
  157. static volatile int signr = -1;
  158. static void sig_handler(int sig)
  159. {
  160. done = 1;
  161. signr = sig;
  162. }
  163. static void sig_atexit(void)
  164. {
  165. if (child_pid > 0)
  166. kill(child_pid, SIGTERM);
  167. if (signr == -1 || signr == SIGUSR1)
  168. return;
  169. signal(signr, SIG_DFL);
  170. kill(getpid(), signr);
  171. }
  172. static int group_fd;
  173. static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
  174. {
  175. struct perf_header_attr *h_attr;
  176. if (nr < session->header.attrs) {
  177. h_attr = session->header.attr[nr];
  178. } else {
  179. h_attr = perf_header_attr__new(a);
  180. if (h_attr != NULL)
  181. if (perf_header__add_attr(&session->header, h_attr) < 0) {
  182. perf_header_attr__delete(h_attr);
  183. h_attr = NULL;
  184. }
  185. }
  186. return h_attr;
  187. }
  188. static void create_counter(struct perf_evlist *evlist,
  189. struct perf_evsel *evsel, int cpu)
  190. {
  191. char *filter = evsel->filter;
  192. struct perf_event_attr *attr = &evsel->attr;
  193. struct perf_header_attr *h_attr;
  194. int track = !evsel->idx; /* only the first counter needs these */
  195. int thread_index;
  196. int ret;
  197. struct {
  198. u64 count;
  199. u64 time_enabled;
  200. u64 time_running;
  201. u64 id;
  202. } read_data;
  203. /*
  204. * Check if parse_single_tracepoint_event has already asked for
  205. * PERF_SAMPLE_TIME.
  206. *
  207. * XXX this is kludgy but short term fix for problems introduced by
  208. * eac23d1c that broke 'perf script' by having different sample_types
  209. * when using multiple tracepoint events when we use a perf binary
  210. * that tries to use sample_id_all on an older kernel.
  211. *
  212. * We need to move counter creation to perf_session, support
  213. * different sample_types, etc.
  214. */
  215. bool time_needed = attr->sample_type & PERF_SAMPLE_TIME;
  216. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  217. PERF_FORMAT_TOTAL_TIME_RUNNING |
  218. PERF_FORMAT_ID;
  219. attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  220. if (evlist->nr_entries > 1)
  221. attr->sample_type |= PERF_SAMPLE_ID;
  222. /*
  223. * We default some events to a 1 default interval. But keep
  224. * it a weak assumption overridable by the user.
  225. */
  226. if (!attr->sample_period || (user_freq != UINT_MAX &&
  227. user_interval != ULLONG_MAX)) {
  228. if (freq) {
  229. attr->sample_type |= PERF_SAMPLE_PERIOD;
  230. attr->freq = 1;
  231. attr->sample_freq = freq;
  232. } else {
  233. attr->sample_period = default_interval;
  234. }
  235. }
  236. if (no_samples)
  237. attr->sample_freq = 0;
  238. if (inherit_stat)
  239. attr->inherit_stat = 1;
  240. if (sample_address) {
  241. attr->sample_type |= PERF_SAMPLE_ADDR;
  242. attr->mmap_data = track;
  243. }
  244. if (call_graph)
  245. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  246. if (system_wide)
  247. attr->sample_type |= PERF_SAMPLE_CPU;
  248. if (sample_id_all_avail &&
  249. (sample_time || system_wide || !no_inherit || cpu_list))
  250. attr->sample_type |= PERF_SAMPLE_TIME;
  251. if (raw_samples) {
  252. attr->sample_type |= PERF_SAMPLE_TIME;
  253. attr->sample_type |= PERF_SAMPLE_RAW;
  254. attr->sample_type |= PERF_SAMPLE_CPU;
  255. }
  256. if (nodelay) {
  257. attr->watermark = 0;
  258. attr->wakeup_events = 1;
  259. }
  260. attr->mmap = track;
  261. attr->comm = track;
  262. attr->inherit = !no_inherit;
  263. if (target_pid == -1 && target_tid == -1 && !system_wide) {
  264. attr->disabled = 1;
  265. attr->enable_on_exec = 1;
  266. }
  267. retry_sample_id:
  268. attr->sample_id_all = sample_id_all_avail ? 1 : 0;
  269. for (thread_index = 0; thread_index < threads->nr; thread_index++) {
  270. try_again:
  271. FD(evsel, nr_cpu, thread_index) = sys_perf_event_open(attr, threads->map[thread_index], cpu, group_fd, 0);
  272. if (FD(evsel, nr_cpu, thread_index) < 0) {
  273. int err = errno;
  274. if (err == EPERM || err == EACCES)
  275. die("Permission error - are you root?\n"
  276. "\t Consider tweaking"
  277. " /proc/sys/kernel/perf_event_paranoid.\n");
  278. else if (err == ENODEV && cpu_list) {
  279. die("No such device - did you specify"
  280. " an out-of-range profile CPU?\n");
  281. } else if (err == EINVAL && sample_id_all_avail) {
  282. /*
  283. * Old kernel, no attr->sample_id_type_all field
  284. */
  285. sample_id_all_avail = false;
  286. if (!sample_time && !raw_samples && !time_needed)
  287. attr->sample_type &= ~PERF_SAMPLE_TIME;
  288. goto retry_sample_id;
  289. }
  290. /*
  291. * If it's cycles then fall back to hrtimer
  292. * based cpu-clock-tick sw counter, which
  293. * is always available even if no PMU support:
  294. */
  295. if (attr->type == PERF_TYPE_HARDWARE
  296. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  297. if (verbose)
  298. warning(" ... trying to fall back to cpu-clock-ticks\n");
  299. attr->type = PERF_TYPE_SOFTWARE;
  300. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  301. goto try_again;
  302. }
  303. printf("\n");
  304. error("sys_perf_event_open() syscall returned with %d (%s). /bin/dmesg may provide additional information.\n",
  305. FD(evsel, nr_cpu, thread_index), strerror(err));
  306. #if defined(__i386__) || defined(__x86_64__)
  307. if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
  308. die("No hardware sampling interrupt available."
  309. " No APIC? If so then you can boot the kernel"
  310. " with the \"lapic\" boot parameter to"
  311. " force-enable it.\n");
  312. #endif
  313. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  314. exit(-1);
  315. }
  316. h_attr = get_header_attr(attr, evsel->idx);
  317. if (h_attr == NULL)
  318. die("nomem\n");
  319. if (!file_new) {
  320. if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
  321. fprintf(stderr, "incompatible append\n");
  322. exit(-1);
  323. }
  324. }
  325. if (read(FD(evsel, nr_cpu, thread_index), &read_data, sizeof(read_data)) == -1) {
  326. perror("Unable to read perf file descriptor");
  327. exit(-1);
  328. }
  329. if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
  330. pr_warning("Not enough memory to add id\n");
  331. exit(-1);
  332. }
  333. assert(FD(evsel, nr_cpu, thread_index) >= 0);
  334. fcntl(FD(evsel, nr_cpu, thread_index), F_SETFL, O_NONBLOCK);
  335. /*
  336. * First counter acts as the group leader:
  337. */
  338. if (group && group_fd == -1)
  339. group_fd = FD(evsel, nr_cpu, thread_index);
  340. if (evsel->idx || thread_index) {
  341. struct perf_evsel *first;
  342. first = list_entry(evlist->entries.next, struct perf_evsel, node);
  343. ret = ioctl(FD(evsel, nr_cpu, thread_index),
  344. PERF_EVENT_IOC_SET_OUTPUT,
  345. FD(first, nr_cpu, 0));
  346. if (ret) {
  347. error("failed to set output: %d (%s)\n", errno,
  348. strerror(errno));
  349. exit(-1);
  350. }
  351. } else {
  352. mmap_array[nr_cpu].prev = 0;
  353. mmap_array[nr_cpu].mask = mmap_pages*page_size - 1;
  354. mmap_array[nr_cpu].base = mmap(NULL, (mmap_pages+1)*page_size,
  355. PROT_READ | PROT_WRITE, MAP_SHARED, FD(evsel, nr_cpu, thread_index), 0);
  356. if (mmap_array[nr_cpu].base == MAP_FAILED) {
  357. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  358. exit(-1);
  359. }
  360. event_array[nr_poll].fd = FD(evsel, nr_cpu, thread_index);
  361. event_array[nr_poll].events = POLLIN;
  362. nr_poll++;
  363. }
  364. if (filter != NULL) {
  365. ret = ioctl(FD(evsel, nr_cpu, thread_index),
  366. PERF_EVENT_IOC_SET_FILTER, filter);
  367. if (ret) {
  368. error("failed to set filter with %d (%s)\n", errno,
  369. strerror(errno));
  370. exit(-1);
  371. }
  372. }
  373. }
  374. if (!sample_type)
  375. sample_type = attr->sample_type;
  376. }
  377. static void open_counters(struct perf_evlist *evlist, int cpu)
  378. {
  379. struct perf_evsel *pos;
  380. group_fd = -1;
  381. list_for_each_entry(pos, &evlist->entries, node)
  382. create_counter(evlist, pos, cpu);
  383. nr_cpu++;
  384. }
  385. static int process_buildids(void)
  386. {
  387. u64 size = lseek(output, 0, SEEK_CUR);
  388. if (size == 0)
  389. return 0;
  390. session->fd = output;
  391. return __perf_session__process_events(session, post_processing_offset,
  392. size - post_processing_offset,
  393. size, &build_id__mark_dso_hit_ops);
  394. }
  395. static void atexit_header(void)
  396. {
  397. if (!pipe_output) {
  398. session->header.data_size += bytes_written;
  399. if (!no_buildid)
  400. process_buildids();
  401. perf_header__write(&session->header, evsel_list, output, true);
  402. perf_session__delete(session);
  403. perf_evlist__delete(evsel_list);
  404. symbol__exit();
  405. }
  406. }
  407. static void event__synthesize_guest_os(struct machine *machine, void *data)
  408. {
  409. int err;
  410. struct perf_session *psession = data;
  411. if (machine__is_host(machine))
  412. return;
  413. /*
  414. *As for guest kernel when processing subcommand record&report,
  415. *we arrange module mmap prior to guest kernel mmap and trigger
  416. *a preload dso because default guest module symbols are loaded
  417. *from guest kallsyms instead of /lib/modules/XXX/XXX. This
  418. *method is used to avoid symbol missing when the first addr is
  419. *in module instead of in guest kernel.
  420. */
  421. err = event__synthesize_modules(process_synthesized_event,
  422. psession, machine);
  423. if (err < 0)
  424. pr_err("Couldn't record guest kernel [%d]'s reference"
  425. " relocation symbol.\n", machine->pid);
  426. /*
  427. * We use _stext for guest kernel because guest kernel's /proc/kallsyms
  428. * have no _text sometimes.
  429. */
  430. err = event__synthesize_kernel_mmap(process_synthesized_event,
  431. psession, machine, "_text");
  432. if (err < 0)
  433. err = event__synthesize_kernel_mmap(process_synthesized_event,
  434. psession, machine, "_stext");
  435. if (err < 0)
  436. pr_err("Couldn't record guest kernel [%d]'s reference"
  437. " relocation symbol.\n", machine->pid);
  438. }
  439. static struct perf_event_header finished_round_event = {
  440. .size = sizeof(struct perf_event_header),
  441. .type = PERF_RECORD_FINISHED_ROUND,
  442. };
  443. static void mmap_read_all(void)
  444. {
  445. int i;
  446. for (i = 0; i < nr_cpu; i++) {
  447. if (mmap_array[i].base)
  448. mmap_read(&mmap_array[i]);
  449. }
  450. if (perf_header__has_feat(&session->header, HEADER_TRACE_INFO))
  451. write_output(&finished_round_event, sizeof(finished_round_event));
  452. }
  453. static int __cmd_record(int argc, const char **argv)
  454. {
  455. int i;
  456. struct stat st;
  457. int flags;
  458. int err;
  459. unsigned long waking = 0;
  460. int child_ready_pipe[2], go_pipe[2];
  461. const bool forks = argc > 0;
  462. char buf;
  463. struct machine *machine;
  464. page_size = sysconf(_SC_PAGE_SIZE);
  465. atexit(sig_atexit);
  466. signal(SIGCHLD, sig_handler);
  467. signal(SIGINT, sig_handler);
  468. signal(SIGUSR1, sig_handler);
  469. if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
  470. perror("failed to create pipes");
  471. exit(-1);
  472. }
  473. if (!strcmp(output_name, "-"))
  474. pipe_output = 1;
  475. else if (!stat(output_name, &st) && st.st_size) {
  476. if (write_mode == WRITE_FORCE) {
  477. char oldname[PATH_MAX];
  478. snprintf(oldname, sizeof(oldname), "%s.old",
  479. output_name);
  480. unlink(oldname);
  481. rename(output_name, oldname);
  482. }
  483. } else if (write_mode == WRITE_APPEND) {
  484. write_mode = WRITE_FORCE;
  485. }
  486. flags = O_CREAT|O_RDWR;
  487. if (write_mode == WRITE_APPEND)
  488. file_new = 0;
  489. else
  490. flags |= O_TRUNC;
  491. if (pipe_output)
  492. output = STDOUT_FILENO;
  493. else
  494. output = open(output_name, flags, S_IRUSR | S_IWUSR);
  495. if (output < 0) {
  496. perror("failed to create output file");
  497. exit(-1);
  498. }
  499. session = perf_session__new(output_name, O_WRONLY,
  500. write_mode == WRITE_FORCE, false, NULL);
  501. if (session == NULL) {
  502. pr_err("Not enough memory for reading perf file header\n");
  503. return -1;
  504. }
  505. if (!no_buildid)
  506. perf_header__set_feat(&session->header, HEADER_BUILD_ID);
  507. if (!file_new) {
  508. err = perf_header__read(session, output);
  509. if (err < 0)
  510. goto out_delete_session;
  511. }
  512. if (have_tracepoints(&evsel_list->entries))
  513. perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
  514. /*
  515. * perf_session__delete(session) will be called at atexit_header()
  516. */
  517. atexit(atexit_header);
  518. if (forks) {
  519. child_pid = fork();
  520. if (child_pid < 0) {
  521. perror("failed to fork");
  522. exit(-1);
  523. }
  524. if (!child_pid) {
  525. if (pipe_output)
  526. dup2(2, 1);
  527. close(child_ready_pipe[0]);
  528. close(go_pipe[1]);
  529. fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
  530. /*
  531. * Do a dummy execvp to get the PLT entry resolved,
  532. * so we avoid the resolver overhead on the real
  533. * execvp call.
  534. */
  535. execvp("", (char **)argv);
  536. /*
  537. * Tell the parent we're ready to go
  538. */
  539. close(child_ready_pipe[1]);
  540. /*
  541. * Wait until the parent tells us to go.
  542. */
  543. if (read(go_pipe[0], &buf, 1) == -1)
  544. perror("unable to read pipe");
  545. execvp(argv[0], (char **)argv);
  546. perror(argv[0]);
  547. kill(getppid(), SIGUSR1);
  548. exit(-1);
  549. }
  550. if (!system_wide && target_tid == -1 && target_pid == -1)
  551. threads->map[0] = child_pid;
  552. close(child_ready_pipe[1]);
  553. close(go_pipe[0]);
  554. /*
  555. * wait for child to settle
  556. */
  557. if (read(child_ready_pipe[0], &buf, 1) == -1) {
  558. perror("unable to read pipe");
  559. exit(-1);
  560. }
  561. close(child_ready_pipe[0]);
  562. }
  563. if (!system_wide && no_inherit && !cpu_list) {
  564. open_counters(evsel_list, -1);
  565. } else {
  566. for (i = 0; i < cpus->nr; i++)
  567. open_counters(evsel_list, cpus->map[i]);
  568. }
  569. perf_session__set_sample_type(session, sample_type);
  570. if (pipe_output) {
  571. err = perf_header__write_pipe(output);
  572. if (err < 0)
  573. return err;
  574. } else if (file_new) {
  575. err = perf_header__write(&session->header, evsel_list,
  576. output, false);
  577. if (err < 0)
  578. return err;
  579. }
  580. post_processing_offset = lseek(output, 0, SEEK_CUR);
  581. perf_session__set_sample_id_all(session, sample_id_all_avail);
  582. if (pipe_output) {
  583. err = event__synthesize_attrs(&session->header,
  584. process_synthesized_event,
  585. session);
  586. if (err < 0) {
  587. pr_err("Couldn't synthesize attrs.\n");
  588. return err;
  589. }
  590. err = event__synthesize_event_types(process_synthesized_event,
  591. session);
  592. if (err < 0) {
  593. pr_err("Couldn't synthesize event_types.\n");
  594. return err;
  595. }
  596. if (have_tracepoints(&evsel_list->entries)) {
  597. /*
  598. * FIXME err <= 0 here actually means that
  599. * there were no tracepoints so its not really
  600. * an error, just that we don't need to
  601. * synthesize anything. We really have to
  602. * return this more properly and also
  603. * propagate errors that now are calling die()
  604. */
  605. err = event__synthesize_tracing_data(output, evsel_list,
  606. process_synthesized_event,
  607. session);
  608. if (err <= 0) {
  609. pr_err("Couldn't record tracing data.\n");
  610. return err;
  611. }
  612. advance_output(err);
  613. }
  614. }
  615. machine = perf_session__find_host_machine(session);
  616. if (!machine) {
  617. pr_err("Couldn't find native kernel information.\n");
  618. return -1;
  619. }
  620. err = event__synthesize_kernel_mmap(process_synthesized_event,
  621. session, machine, "_text");
  622. if (err < 0)
  623. err = event__synthesize_kernel_mmap(process_synthesized_event,
  624. session, machine, "_stext");
  625. if (err < 0)
  626. pr_err("Couldn't record kernel reference relocation symbol\n"
  627. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  628. "Check /proc/kallsyms permission or run as root.\n");
  629. err = event__synthesize_modules(process_synthesized_event,
  630. session, machine);
  631. if (err < 0)
  632. pr_err("Couldn't record kernel module information.\n"
  633. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  634. "Check /proc/modules permission or run as root.\n");
  635. if (perf_guest)
  636. perf_session__process_machines(session, event__synthesize_guest_os);
  637. if (!system_wide)
  638. event__synthesize_thread(target_tid, process_synthesized_event,
  639. session);
  640. else
  641. event__synthesize_threads(process_synthesized_event, session);
  642. if (realtime_prio) {
  643. struct sched_param param;
  644. param.sched_priority = realtime_prio;
  645. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  646. pr_err("Could not set realtime priority.\n");
  647. exit(-1);
  648. }
  649. }
  650. /*
  651. * Let the child rip
  652. */
  653. if (forks)
  654. close(go_pipe[1]);
  655. for (;;) {
  656. int hits = samples;
  657. int thread;
  658. mmap_read_all();
  659. if (hits == samples) {
  660. if (done)
  661. break;
  662. err = poll(event_array, nr_poll, -1);
  663. waking++;
  664. }
  665. if (done) {
  666. for (i = 0; i < nr_cpu; i++) {
  667. struct perf_evsel *pos;
  668. list_for_each_entry(pos, &evsel_list->entries, node) {
  669. for (thread = 0;
  670. thread < threads->nr;
  671. thread++)
  672. ioctl(FD(pos, i, thread),
  673. PERF_EVENT_IOC_DISABLE);
  674. }
  675. }
  676. }
  677. }
  678. if (quiet || signr == SIGUSR1)
  679. return 0;
  680. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  681. /*
  682. * Approximate RIP event size: 24 bytes.
  683. */
  684. fprintf(stderr,
  685. "[ perf record: Captured and wrote %.3f MB %s (~%" PRIu64 " samples) ]\n",
  686. (double)bytes_written / 1024.0 / 1024.0,
  687. output_name,
  688. bytes_written / 24);
  689. return 0;
  690. out_delete_session:
  691. perf_session__delete(session);
  692. return err;
  693. }
  694. static const char * const record_usage[] = {
  695. "perf record [<options>] [<command>]",
  696. "perf record [<options>] -- <command> [<options>]",
  697. NULL
  698. };
  699. static bool force, append_file;
  700. const struct option record_options[] = {
  701. OPT_CALLBACK('e', "event", &evsel_list, "event",
  702. "event selector. use 'perf list' to list available events",
  703. parse_events),
  704. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  705. "event filter", parse_filter),
  706. OPT_INTEGER('p', "pid", &target_pid,
  707. "record events on existing process id"),
  708. OPT_INTEGER('t', "tid", &target_tid,
  709. "record events on existing thread id"),
  710. OPT_INTEGER('r', "realtime", &realtime_prio,
  711. "collect data with this RT SCHED_FIFO priority"),
  712. OPT_BOOLEAN('D', "no-delay", &nodelay,
  713. "collect data without buffering"),
  714. OPT_BOOLEAN('R', "raw-samples", &raw_samples,
  715. "collect raw sample records from all opened counters"),
  716. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  717. "system-wide collection from all CPUs"),
  718. OPT_BOOLEAN('A', "append", &append_file,
  719. "append to the output file to do incremental profiling"),
  720. OPT_STRING('C', "cpu", &cpu_list, "cpu",
  721. "list of cpus to monitor"),
  722. OPT_BOOLEAN('f', "force", &force,
  723. "overwrite existing data file (deprecated)"),
  724. OPT_U64('c', "count", &user_interval, "event period to sample"),
  725. OPT_STRING('o', "output", &output_name, "file",
  726. "output file name"),
  727. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  728. "child tasks do not inherit counters"),
  729. OPT_UINTEGER('F', "freq", &user_freq, "profile at this frequency"),
  730. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  731. OPT_BOOLEAN('g', "call-graph", &call_graph,
  732. "do call-graph (stack chain/backtrace) recording"),
  733. OPT_INCR('v', "verbose", &verbose,
  734. "be more verbose (show counter open errors, etc)"),
  735. OPT_BOOLEAN('q', "quiet", &quiet, "don't print any message"),
  736. OPT_BOOLEAN('s', "stat", &inherit_stat,
  737. "per thread counts"),
  738. OPT_BOOLEAN('d', "data", &sample_address,
  739. "Sample addresses"),
  740. OPT_BOOLEAN('T', "timestamp", &sample_time, "Sample timestamps"),
  741. OPT_BOOLEAN('n', "no-samples", &no_samples,
  742. "don't sample"),
  743. OPT_BOOLEAN('N', "no-buildid-cache", &no_buildid_cache,
  744. "do not update the buildid cache"),
  745. OPT_BOOLEAN('B', "no-buildid", &no_buildid,
  746. "do not collect buildids in perf.data"),
  747. OPT_END()
  748. };
  749. int cmd_record(int argc, const char **argv, const char *prefix __used)
  750. {
  751. int err = -ENOMEM;
  752. struct perf_evsel *pos;
  753. evsel_list = perf_evlist__new();
  754. if (evsel_list == NULL)
  755. return -ENOMEM;
  756. argc = parse_options(argc, argv, record_options, record_usage,
  757. PARSE_OPT_STOP_AT_NON_OPTION);
  758. if (!argc && target_pid == -1 && target_tid == -1 &&
  759. !system_wide && !cpu_list)
  760. usage_with_options(record_usage, record_options);
  761. if (force && append_file) {
  762. fprintf(stderr, "Can't overwrite and append at the same time."
  763. " You need to choose between -f and -A");
  764. usage_with_options(record_usage, record_options);
  765. } else if (append_file) {
  766. write_mode = WRITE_APPEND;
  767. } else {
  768. write_mode = WRITE_FORCE;
  769. }
  770. symbol__init();
  771. if (no_buildid_cache || no_buildid)
  772. disable_buildid_cache();
  773. if (evsel_list->nr_entries == 0 &&
  774. perf_evlist__add_default(evsel_list) < 0) {
  775. pr_err("Not enough memory for event selector list\n");
  776. goto out_symbol_exit;
  777. }
  778. if (target_pid != -1)
  779. target_tid = target_pid;
  780. threads = thread_map__new(target_pid, target_tid);
  781. if (threads == NULL) {
  782. pr_err("Problems finding threads of monitor\n");
  783. usage_with_options(record_usage, record_options);
  784. }
  785. cpus = cpu_map__new(cpu_list);
  786. if (cpus == NULL) {
  787. perror("failed to parse CPUs map");
  788. return -1;
  789. }
  790. list_for_each_entry(pos, &evsel_list->entries, node) {
  791. if (perf_evsel__alloc_fd(pos, cpus->nr, threads->nr) < 0)
  792. goto out_free_fd;
  793. if (perf_header__push_event(pos->attr.config, event_name(pos)))
  794. goto out_free_fd;
  795. }
  796. event_array = malloc((sizeof(struct pollfd) * MAX_NR_CPUS *
  797. MAX_COUNTERS * threads->nr));
  798. if (!event_array)
  799. goto out_free_fd;
  800. if (user_interval != ULLONG_MAX)
  801. default_interval = user_interval;
  802. if (user_freq != UINT_MAX)
  803. freq = user_freq;
  804. /*
  805. * User specified count overrides default frequency.
  806. */
  807. if (default_interval)
  808. freq = 0;
  809. else if (freq) {
  810. default_interval = freq;
  811. } else {
  812. fprintf(stderr, "frequency and count are zero, aborting\n");
  813. err = -EINVAL;
  814. goto out_free_event_array;
  815. }
  816. err = __cmd_record(argc, argv);
  817. out_free_event_array:
  818. free(event_array);
  819. out_free_fd:
  820. thread_map__delete(threads);
  821. threads = NULL;
  822. out_symbol_exit:
  823. symbol__exit();
  824. return err;
  825. }