builtin-record.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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/tool.h"
  22. #include "util/symbol.h"
  23. #include "util/cpumap.h"
  24. #include "util/thread_map.h"
  25. #include <unistd.h>
  26. #include <sched.h>
  27. #include <sys/mman.h>
  28. enum write_mode_t {
  29. WRITE_FORCE,
  30. WRITE_APPEND
  31. };
  32. struct perf_record {
  33. struct perf_tool tool;
  34. struct perf_record_opts opts;
  35. u64 bytes_written;
  36. const char *output_name;
  37. struct perf_evlist *evlist;
  38. struct perf_session *session;
  39. const char *progname;
  40. int output;
  41. unsigned int page_size;
  42. int realtime_prio;
  43. enum write_mode_t write_mode;
  44. bool no_buildid;
  45. bool no_buildid_cache;
  46. bool force;
  47. bool file_new;
  48. bool append_file;
  49. long samples;
  50. off_t post_processing_offset;
  51. };
  52. static void advance_output(struct perf_record *rec, size_t size)
  53. {
  54. rec->bytes_written += size;
  55. }
  56. static int write_output(struct perf_record *rec, void *buf, size_t size)
  57. {
  58. while (size) {
  59. int ret = write(rec->output, buf, size);
  60. if (ret < 0) {
  61. pr_err("failed to write\n");
  62. return -1;
  63. }
  64. size -= ret;
  65. buf += ret;
  66. rec->bytes_written += ret;
  67. }
  68. return 0;
  69. }
  70. static int process_synthesized_event(struct perf_tool *tool,
  71. union perf_event *event,
  72. struct perf_sample *sample __maybe_unused,
  73. struct machine *machine __maybe_unused)
  74. {
  75. struct perf_record *rec = container_of(tool, struct perf_record, tool);
  76. if (write_output(rec, event, event->header.size) < 0)
  77. return -1;
  78. return 0;
  79. }
  80. static int perf_record__mmap_read(struct perf_record *rec,
  81. struct perf_mmap *md)
  82. {
  83. unsigned int head = perf_mmap__read_head(md);
  84. unsigned int old = md->prev;
  85. unsigned char *data = md->base + rec->page_size;
  86. unsigned long size;
  87. void *buf;
  88. int rc = 0;
  89. if (old == head)
  90. return 0;
  91. rec->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. if (write_output(rec, buf, size) < 0) {
  98. rc = -1;
  99. goto out;
  100. }
  101. }
  102. buf = &data[old & md->mask];
  103. size = head - old;
  104. old += size;
  105. if (write_output(rec, buf, size) < 0) {
  106. rc = -1;
  107. goto out;
  108. }
  109. md->prev = old;
  110. perf_mmap__write_tail(md, old);
  111. out:
  112. return rc;
  113. }
  114. static volatile int done = 0;
  115. static volatile int signr = -1;
  116. static volatile int child_finished = 0;
  117. static void sig_handler(int sig)
  118. {
  119. if (sig == SIGCHLD)
  120. child_finished = 1;
  121. done = 1;
  122. signr = sig;
  123. }
  124. static void perf_record__sig_exit(int exit_status __maybe_unused, void *arg)
  125. {
  126. struct perf_record *rec = arg;
  127. int status;
  128. if (rec->evlist->workload.pid > 0) {
  129. if (!child_finished)
  130. kill(rec->evlist->workload.pid, SIGTERM);
  131. wait(&status);
  132. if (WIFSIGNALED(status))
  133. psignal(WTERMSIG(status), rec->progname);
  134. }
  135. if (signr == -1 || signr == SIGUSR1)
  136. return;
  137. signal(signr, SIG_DFL);
  138. kill(getpid(), signr);
  139. }
  140. static bool perf_evlist__equal(struct perf_evlist *evlist,
  141. struct perf_evlist *other)
  142. {
  143. struct perf_evsel *pos, *pair;
  144. if (evlist->nr_entries != other->nr_entries)
  145. return false;
  146. pair = perf_evlist__first(other);
  147. list_for_each_entry(pos, &evlist->entries, node) {
  148. if (memcmp(&pos->attr, &pair->attr, sizeof(pos->attr) != 0))
  149. return false;
  150. pair = perf_evsel__next(pair);
  151. }
  152. return true;
  153. }
  154. static int perf_record__open(struct perf_record *rec)
  155. {
  156. struct perf_evsel *pos;
  157. struct perf_evlist *evlist = rec->evlist;
  158. struct perf_session *session = rec->session;
  159. struct perf_record_opts *opts = &rec->opts;
  160. int rc = 0;
  161. perf_evlist__config_attrs(evlist, opts);
  162. if (opts->group)
  163. perf_evlist__set_leader(evlist);
  164. list_for_each_entry(pos, &evlist->entries, node) {
  165. struct perf_event_attr *attr = &pos->attr;
  166. /*
  167. * Check if parse_single_tracepoint_event has already asked for
  168. * PERF_SAMPLE_TIME.
  169. *
  170. * XXX this is kludgy but short term fix for problems introduced by
  171. * eac23d1c that broke 'perf script' by having different sample_types
  172. * when using multiple tracepoint events when we use a perf binary
  173. * that tries to use sample_id_all on an older kernel.
  174. *
  175. * We need to move counter creation to perf_session, support
  176. * different sample_types, etc.
  177. */
  178. bool time_needed = attr->sample_type & PERF_SAMPLE_TIME;
  179. fallback_missing_features:
  180. if (opts->exclude_guest_missing)
  181. attr->exclude_guest = attr->exclude_host = 0;
  182. retry_sample_id:
  183. attr->sample_id_all = opts->sample_id_all_missing ? 0 : 1;
  184. try_again:
  185. if (perf_evsel__open(pos, evlist->cpus, evlist->threads) < 0) {
  186. int err = errno;
  187. if (err == EPERM || err == EACCES) {
  188. ui__error_paranoid();
  189. rc = -err;
  190. goto out;
  191. } else if (err == ENODEV && opts->target.cpu_list) {
  192. pr_err("No such device - did you specify"
  193. " an out-of-range profile CPU?\n");
  194. rc = -err;
  195. goto out;
  196. } else if (err == EINVAL) {
  197. if (!opts->exclude_guest_missing &&
  198. (attr->exclude_guest || attr->exclude_host)) {
  199. pr_debug("Old kernel, cannot exclude "
  200. "guest or host samples.\n");
  201. opts->exclude_guest_missing = true;
  202. goto fallback_missing_features;
  203. } else if (!opts->sample_id_all_missing) {
  204. /*
  205. * Old kernel, no attr->sample_id_type_all field
  206. */
  207. opts->sample_id_all_missing = true;
  208. if (!opts->sample_time && !opts->raw_samples && !time_needed)
  209. attr->sample_type &= ~PERF_SAMPLE_TIME;
  210. goto retry_sample_id;
  211. }
  212. }
  213. /*
  214. * If it's cycles then fall back to hrtimer
  215. * based cpu-clock-tick sw counter, which
  216. * is always available even if no PMU support.
  217. *
  218. * PPC returns ENXIO until 2.6.37 (behavior changed
  219. * with commit b0a873e).
  220. */
  221. if ((err == ENOENT || err == ENXIO)
  222. && attr->type == PERF_TYPE_HARDWARE
  223. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  224. if (verbose)
  225. ui__warning("The cycles event is not supported, "
  226. "trying to fall back to cpu-clock-ticks\n");
  227. attr->type = PERF_TYPE_SOFTWARE;
  228. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  229. if (pos->name) {
  230. free(pos->name);
  231. pos->name = NULL;
  232. }
  233. goto try_again;
  234. }
  235. if (err == ENOENT) {
  236. ui__error("The %s event is not supported.\n",
  237. perf_evsel__name(pos));
  238. rc = -err;
  239. goto out;
  240. }
  241. printf("\n");
  242. error("sys_perf_event_open() syscall returned with %d "
  243. "(%s) for event %s. /bin/dmesg may provide "
  244. "additional information.\n",
  245. err, strerror(err), perf_evsel__name(pos));
  246. #if defined(__i386__) || defined(__x86_64__)
  247. if (attr->type == PERF_TYPE_HARDWARE &&
  248. err == EOPNOTSUPP) {
  249. pr_err("No hardware sampling interrupt available."
  250. " No APIC? If so then you can boot the kernel"
  251. " with the \"lapic\" boot parameter to"
  252. " force-enable it.\n");
  253. rc = -err;
  254. goto out;
  255. }
  256. #endif
  257. pr_err("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  258. rc = -err;
  259. goto out;
  260. }
  261. }
  262. if (perf_evlist__apply_filters(evlist)) {
  263. error("failed to set filter with %d (%s)\n", errno,
  264. strerror(errno));
  265. rc = -1;
  266. goto out;
  267. }
  268. if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
  269. if (errno == EPERM) {
  270. pr_err("Permission error mapping pages.\n"
  271. "Consider increasing "
  272. "/proc/sys/kernel/perf_event_mlock_kb,\n"
  273. "or try again with a smaller value of -m/--mmap_pages.\n"
  274. "(current value: %d)\n", opts->mmap_pages);
  275. rc = -errno;
  276. } else if (!is_power_of_2(opts->mmap_pages)) {
  277. pr_err("--mmap_pages/-m value must be a power of two.");
  278. rc = -EINVAL;
  279. } else {
  280. pr_err("failed to mmap with %d (%s)\n", errno, strerror(errno));
  281. rc = -errno;
  282. }
  283. goto out;
  284. }
  285. if (rec->file_new)
  286. session->evlist = evlist;
  287. else {
  288. if (!perf_evlist__equal(session->evlist, evlist)) {
  289. fprintf(stderr, "incompatible append\n");
  290. rc = -1;
  291. goto out;
  292. }
  293. }
  294. perf_session__set_id_hdr_size(session);
  295. out:
  296. return rc;
  297. }
  298. static int process_buildids(struct perf_record *rec)
  299. {
  300. u64 size = lseek(rec->output, 0, SEEK_CUR);
  301. if (size == 0)
  302. return 0;
  303. rec->session->fd = rec->output;
  304. return __perf_session__process_events(rec->session, rec->post_processing_offset,
  305. size - rec->post_processing_offset,
  306. size, &build_id__mark_dso_hit_ops);
  307. }
  308. static void perf_record__exit(int status, void *arg)
  309. {
  310. struct perf_record *rec = arg;
  311. if (status != 0)
  312. return;
  313. if (!rec->opts.pipe_output) {
  314. rec->session->header.data_size += rec->bytes_written;
  315. if (!rec->no_buildid)
  316. process_buildids(rec);
  317. perf_session__write_header(rec->session, rec->evlist,
  318. rec->output, true);
  319. perf_session__delete(rec->session);
  320. perf_evlist__delete(rec->evlist);
  321. symbol__exit();
  322. }
  323. }
  324. static void perf_event__synthesize_guest_os(struct machine *machine, void *data)
  325. {
  326. int err;
  327. struct perf_tool *tool = data;
  328. if (machine__is_host(machine))
  329. return;
  330. /*
  331. *As for guest kernel when processing subcommand record&report,
  332. *we arrange module mmap prior to guest kernel mmap and trigger
  333. *a preload dso because default guest module symbols are loaded
  334. *from guest kallsyms instead of /lib/modules/XXX/XXX. This
  335. *method is used to avoid symbol missing when the first addr is
  336. *in module instead of in guest kernel.
  337. */
  338. err = perf_event__synthesize_modules(tool, process_synthesized_event,
  339. machine);
  340. if (err < 0)
  341. pr_err("Couldn't record guest kernel [%d]'s reference"
  342. " relocation symbol.\n", machine->pid);
  343. /*
  344. * We use _stext for guest kernel because guest kernel's /proc/kallsyms
  345. * have no _text sometimes.
  346. */
  347. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  348. machine, "_text");
  349. if (err < 0)
  350. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  351. machine, "_stext");
  352. if (err < 0)
  353. pr_err("Couldn't record guest kernel [%d]'s reference"
  354. " relocation symbol.\n", machine->pid);
  355. }
  356. static struct perf_event_header finished_round_event = {
  357. .size = sizeof(struct perf_event_header),
  358. .type = PERF_RECORD_FINISHED_ROUND,
  359. };
  360. static int perf_record__mmap_read_all(struct perf_record *rec)
  361. {
  362. int i;
  363. int rc = 0;
  364. for (i = 0; i < rec->evlist->nr_mmaps; i++) {
  365. if (rec->evlist->mmap[i].base) {
  366. if (perf_record__mmap_read(rec, &rec->evlist->mmap[i]) != 0) {
  367. rc = -1;
  368. goto out;
  369. }
  370. }
  371. }
  372. if (perf_header__has_feat(&rec->session->header, HEADER_TRACING_DATA))
  373. rc = write_output(rec, &finished_round_event,
  374. sizeof(finished_round_event));
  375. out:
  376. return rc;
  377. }
  378. static int __cmd_record(struct perf_record *rec, int argc, const char **argv)
  379. {
  380. struct stat st;
  381. int flags;
  382. int err, output, feat;
  383. unsigned long waking = 0;
  384. const bool forks = argc > 0;
  385. struct machine *machine;
  386. struct perf_tool *tool = &rec->tool;
  387. struct perf_record_opts *opts = &rec->opts;
  388. struct perf_evlist *evsel_list = rec->evlist;
  389. const char *output_name = rec->output_name;
  390. struct perf_session *session;
  391. rec->progname = argv[0];
  392. rec->page_size = sysconf(_SC_PAGE_SIZE);
  393. on_exit(perf_record__sig_exit, rec);
  394. signal(SIGCHLD, sig_handler);
  395. signal(SIGINT, sig_handler);
  396. signal(SIGUSR1, sig_handler);
  397. if (!output_name) {
  398. if (!fstat(STDOUT_FILENO, &st) && S_ISFIFO(st.st_mode))
  399. opts->pipe_output = true;
  400. else
  401. rec->output_name = output_name = "perf.data";
  402. }
  403. if (output_name) {
  404. if (!strcmp(output_name, "-"))
  405. opts->pipe_output = true;
  406. else if (!stat(output_name, &st) && st.st_size) {
  407. if (rec->write_mode == WRITE_FORCE) {
  408. char oldname[PATH_MAX];
  409. snprintf(oldname, sizeof(oldname), "%s.old",
  410. output_name);
  411. unlink(oldname);
  412. rename(output_name, oldname);
  413. }
  414. } else if (rec->write_mode == WRITE_APPEND) {
  415. rec->write_mode = WRITE_FORCE;
  416. }
  417. }
  418. flags = O_CREAT|O_RDWR;
  419. if (rec->write_mode == WRITE_APPEND)
  420. rec->file_new = 0;
  421. else
  422. flags |= O_TRUNC;
  423. if (opts->pipe_output)
  424. output = STDOUT_FILENO;
  425. else
  426. output = open(output_name, flags, S_IRUSR | S_IWUSR);
  427. if (output < 0) {
  428. perror("failed to create output file");
  429. return -1;
  430. }
  431. rec->output = output;
  432. session = perf_session__new(output_name, O_WRONLY,
  433. rec->write_mode == WRITE_FORCE, false, NULL);
  434. if (session == NULL) {
  435. pr_err("Not enough memory for reading perf file header\n");
  436. return -1;
  437. }
  438. rec->session = session;
  439. for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
  440. perf_header__set_feat(&session->header, feat);
  441. if (rec->no_buildid)
  442. perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
  443. if (!have_tracepoints(&evsel_list->entries))
  444. perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
  445. if (!rec->opts.branch_stack)
  446. perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
  447. if (!rec->file_new) {
  448. err = perf_session__read_header(session, output);
  449. if (err < 0)
  450. goto out_delete_session;
  451. }
  452. if (forks) {
  453. err = perf_evlist__prepare_workload(evsel_list, opts, argv);
  454. if (err < 0) {
  455. pr_err("Couldn't run the workload!\n");
  456. goto out_delete_session;
  457. }
  458. }
  459. if (perf_record__open(rec) != 0) {
  460. err = -1;
  461. goto out_delete_session;
  462. }
  463. /*
  464. * perf_session__delete(session) will be called at perf_record__exit()
  465. */
  466. on_exit(perf_record__exit, rec);
  467. if (opts->pipe_output) {
  468. err = perf_header__write_pipe(output);
  469. if (err < 0)
  470. goto out_delete_session;
  471. } else if (rec->file_new) {
  472. err = perf_session__write_header(session, evsel_list,
  473. output, false);
  474. if (err < 0)
  475. goto out_delete_session;
  476. }
  477. if (!rec->no_buildid
  478. && !perf_header__has_feat(&session->header, HEADER_BUILD_ID)) {
  479. pr_err("Couldn't generate buildids. "
  480. "Use --no-buildid to profile anyway.\n");
  481. err = -1;
  482. goto out_delete_session;
  483. }
  484. rec->post_processing_offset = lseek(output, 0, SEEK_CUR);
  485. machine = perf_session__find_host_machine(session);
  486. if (!machine) {
  487. pr_err("Couldn't find native kernel information.\n");
  488. err = -1;
  489. goto out_delete_session;
  490. }
  491. if (opts->pipe_output) {
  492. err = perf_event__synthesize_attrs(tool, session,
  493. process_synthesized_event);
  494. if (err < 0) {
  495. pr_err("Couldn't synthesize attrs.\n");
  496. goto out_delete_session;
  497. }
  498. err = perf_event__synthesize_event_types(tool, process_synthesized_event,
  499. machine);
  500. if (err < 0) {
  501. pr_err("Couldn't synthesize event_types.\n");
  502. goto out_delete_session;
  503. }
  504. if (have_tracepoints(&evsel_list->entries)) {
  505. /*
  506. * FIXME err <= 0 here actually means that
  507. * there were no tracepoints so its not really
  508. * an error, just that we don't need to
  509. * synthesize anything. We really have to
  510. * return this more properly and also
  511. * propagate errors that now are calling die()
  512. */
  513. err = perf_event__synthesize_tracing_data(tool, output, evsel_list,
  514. process_synthesized_event);
  515. if (err <= 0) {
  516. pr_err("Couldn't record tracing data.\n");
  517. goto out_delete_session;
  518. }
  519. advance_output(rec, err);
  520. }
  521. }
  522. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  523. machine, "_text");
  524. if (err < 0)
  525. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  526. machine, "_stext");
  527. if (err < 0)
  528. pr_err("Couldn't record kernel reference relocation symbol\n"
  529. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  530. "Check /proc/kallsyms permission or run as root.\n");
  531. err = perf_event__synthesize_modules(tool, process_synthesized_event,
  532. machine);
  533. if (err < 0)
  534. pr_err("Couldn't record kernel module information.\n"
  535. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  536. "Check /proc/modules permission or run as root.\n");
  537. if (perf_guest)
  538. perf_session__process_machines(session, tool,
  539. perf_event__synthesize_guest_os);
  540. if (!opts->target.system_wide)
  541. err = perf_event__synthesize_thread_map(tool, evsel_list->threads,
  542. process_synthesized_event,
  543. machine);
  544. else
  545. err = perf_event__synthesize_threads(tool, process_synthesized_event,
  546. machine);
  547. if (err != 0)
  548. goto out_delete_session;
  549. if (rec->realtime_prio) {
  550. struct sched_param param;
  551. param.sched_priority = rec->realtime_prio;
  552. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  553. pr_err("Could not set realtime priority.\n");
  554. err = -1;
  555. goto out_delete_session;
  556. }
  557. }
  558. perf_evlist__enable(evsel_list);
  559. /*
  560. * Let the child rip
  561. */
  562. if (forks)
  563. perf_evlist__start_workload(evsel_list);
  564. for (;;) {
  565. int hits = rec->samples;
  566. if (perf_record__mmap_read_all(rec) < 0) {
  567. err = -1;
  568. goto out_delete_session;
  569. }
  570. if (hits == rec->samples) {
  571. if (done)
  572. break;
  573. err = poll(evsel_list->pollfd, evsel_list->nr_fds, -1);
  574. waking++;
  575. }
  576. if (done)
  577. perf_evlist__disable(evsel_list);
  578. }
  579. if (quiet || signr == SIGUSR1)
  580. return 0;
  581. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  582. /*
  583. * Approximate RIP event size: 24 bytes.
  584. */
  585. fprintf(stderr,
  586. "[ perf record: Captured and wrote %.3f MB %s (~%" PRIu64 " samples) ]\n",
  587. (double)rec->bytes_written / 1024.0 / 1024.0,
  588. output_name,
  589. rec->bytes_written / 24);
  590. return 0;
  591. out_delete_session:
  592. perf_session__delete(session);
  593. return err;
  594. }
  595. #define BRANCH_OPT(n, m) \
  596. { .name = n, .mode = (m) }
  597. #define BRANCH_END { .name = NULL }
  598. struct branch_mode {
  599. const char *name;
  600. int mode;
  601. };
  602. static const struct branch_mode branch_modes[] = {
  603. BRANCH_OPT("u", PERF_SAMPLE_BRANCH_USER),
  604. BRANCH_OPT("k", PERF_SAMPLE_BRANCH_KERNEL),
  605. BRANCH_OPT("hv", PERF_SAMPLE_BRANCH_HV),
  606. BRANCH_OPT("any", PERF_SAMPLE_BRANCH_ANY),
  607. BRANCH_OPT("any_call", PERF_SAMPLE_BRANCH_ANY_CALL),
  608. BRANCH_OPT("any_ret", PERF_SAMPLE_BRANCH_ANY_RETURN),
  609. BRANCH_OPT("ind_call", PERF_SAMPLE_BRANCH_IND_CALL),
  610. BRANCH_END
  611. };
  612. static int
  613. parse_branch_stack(const struct option *opt, const char *str, int unset)
  614. {
  615. #define ONLY_PLM \
  616. (PERF_SAMPLE_BRANCH_USER |\
  617. PERF_SAMPLE_BRANCH_KERNEL |\
  618. PERF_SAMPLE_BRANCH_HV)
  619. uint64_t *mode = (uint64_t *)opt->value;
  620. const struct branch_mode *br;
  621. char *s, *os = NULL, *p;
  622. int ret = -1;
  623. if (unset)
  624. return 0;
  625. /*
  626. * cannot set it twice, -b + --branch-filter for instance
  627. */
  628. if (*mode)
  629. return -1;
  630. /* str may be NULL in case no arg is passed to -b */
  631. if (str) {
  632. /* because str is read-only */
  633. s = os = strdup(str);
  634. if (!s)
  635. return -1;
  636. for (;;) {
  637. p = strchr(s, ',');
  638. if (p)
  639. *p = '\0';
  640. for (br = branch_modes; br->name; br++) {
  641. if (!strcasecmp(s, br->name))
  642. break;
  643. }
  644. if (!br->name) {
  645. ui__warning("unknown branch filter %s,"
  646. " check man page\n", s);
  647. goto error;
  648. }
  649. *mode |= br->mode;
  650. if (!p)
  651. break;
  652. s = p + 1;
  653. }
  654. }
  655. ret = 0;
  656. /* default to any branch */
  657. if ((*mode & ~ONLY_PLM) == 0) {
  658. *mode = PERF_SAMPLE_BRANCH_ANY;
  659. }
  660. error:
  661. free(os);
  662. return ret;
  663. }
  664. #ifdef LIBUNWIND_SUPPORT
  665. static int get_stack_size(char *str, unsigned long *_size)
  666. {
  667. char *endptr;
  668. unsigned long size;
  669. unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
  670. size = strtoul(str, &endptr, 0);
  671. do {
  672. if (*endptr)
  673. break;
  674. size = round_up(size, sizeof(u64));
  675. if (!size || size > max_size)
  676. break;
  677. *_size = size;
  678. return 0;
  679. } while (0);
  680. pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
  681. max_size, str);
  682. return -1;
  683. }
  684. #endif /* LIBUNWIND_SUPPORT */
  685. static int
  686. parse_callchain_opt(const struct option *opt __maybe_unused, const char *arg,
  687. int unset)
  688. {
  689. struct perf_record *rec = (struct perf_record *)opt->value;
  690. char *tok, *name, *saveptr = NULL;
  691. char *buf;
  692. int ret = -1;
  693. /* --no-call-graph */
  694. if (unset)
  695. return 0;
  696. /* We specified default option if none is provided. */
  697. BUG_ON(!arg);
  698. /* We need buffer that we know we can write to. */
  699. buf = malloc(strlen(arg) + 1);
  700. if (!buf)
  701. return -ENOMEM;
  702. strcpy(buf, arg);
  703. tok = strtok_r((char *)buf, ",", &saveptr);
  704. name = tok ? : (char *)buf;
  705. do {
  706. /* Framepointer style */
  707. if (!strncmp(name, "fp", sizeof("fp"))) {
  708. if (!strtok_r(NULL, ",", &saveptr)) {
  709. rec->opts.call_graph = CALLCHAIN_FP;
  710. ret = 0;
  711. } else
  712. pr_err("callchain: No more arguments "
  713. "needed for -g fp\n");
  714. break;
  715. #ifdef LIBUNWIND_SUPPORT
  716. /* Dwarf style */
  717. } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
  718. const unsigned long default_stack_dump_size = 8192;
  719. ret = 0;
  720. rec->opts.call_graph = CALLCHAIN_DWARF;
  721. rec->opts.stack_dump_size = default_stack_dump_size;
  722. tok = strtok_r(NULL, ",", &saveptr);
  723. if (tok) {
  724. unsigned long size = 0;
  725. ret = get_stack_size(tok, &size);
  726. rec->opts.stack_dump_size = size;
  727. }
  728. if (!ret)
  729. pr_debug("callchain: stack dump size %d\n",
  730. rec->opts.stack_dump_size);
  731. #endif /* LIBUNWIND_SUPPORT */
  732. } else {
  733. pr_err("callchain: Unknown -g option "
  734. "value: %s\n", arg);
  735. break;
  736. }
  737. } while (0);
  738. free(buf);
  739. if (!ret)
  740. pr_debug("callchain: type %d\n", rec->opts.call_graph);
  741. return ret;
  742. }
  743. static const char * const record_usage[] = {
  744. "perf record [<options>] [<command>]",
  745. "perf record [<options>] -- <command> [<options>]",
  746. NULL
  747. };
  748. /*
  749. * XXX Ideally would be local to cmd_record() and passed to a perf_record__new
  750. * because we need to have access to it in perf_record__exit, that is called
  751. * after cmd_record() exits, but since record_options need to be accessible to
  752. * builtin-script, leave it here.
  753. *
  754. * At least we don't ouch it in all the other functions here directly.
  755. *
  756. * Just say no to tons of global variables, sigh.
  757. */
  758. static struct perf_record record = {
  759. .opts = {
  760. .mmap_pages = UINT_MAX,
  761. .user_freq = UINT_MAX,
  762. .user_interval = ULLONG_MAX,
  763. .freq = 4000,
  764. .target = {
  765. .uses_mmap = true,
  766. },
  767. },
  768. .write_mode = WRITE_FORCE,
  769. .file_new = true,
  770. };
  771. #define CALLCHAIN_HELP "do call-graph (stack chain/backtrace) recording: "
  772. #ifdef LIBUNWIND_SUPPORT
  773. static const char callchain_help[] = CALLCHAIN_HELP "[fp] dwarf";
  774. #else
  775. static const char callchain_help[] = CALLCHAIN_HELP "[fp]";
  776. #endif
  777. /*
  778. * XXX Will stay a global variable till we fix builtin-script.c to stop messing
  779. * with it and switch to use the library functions in perf_evlist that came
  780. * from builtin-record.c, i.e. use perf_record_opts,
  781. * perf_evlist__prepare_workload, etc instead of fork+exec'in 'perf record',
  782. * using pipes, etc.
  783. */
  784. const struct option record_options[] = {
  785. OPT_CALLBACK('e', "event", &record.evlist, "event",
  786. "event selector. use 'perf list' to list available events",
  787. parse_events_option),
  788. OPT_CALLBACK(0, "filter", &record.evlist, "filter",
  789. "event filter", parse_filter),
  790. OPT_STRING('p', "pid", &record.opts.target.pid, "pid",
  791. "record events on existing process id"),
  792. OPT_STRING('t', "tid", &record.opts.target.tid, "tid",
  793. "record events on existing thread id"),
  794. OPT_INTEGER('r', "realtime", &record.realtime_prio,
  795. "collect data with this RT SCHED_FIFO priority"),
  796. OPT_BOOLEAN('D', "no-delay", &record.opts.no_delay,
  797. "collect data without buffering"),
  798. OPT_BOOLEAN('R', "raw-samples", &record.opts.raw_samples,
  799. "collect raw sample records from all opened counters"),
  800. OPT_BOOLEAN('a', "all-cpus", &record.opts.target.system_wide,
  801. "system-wide collection from all CPUs"),
  802. OPT_BOOLEAN('A', "append", &record.append_file,
  803. "append to the output file to do incremental profiling"),
  804. OPT_STRING('C', "cpu", &record.opts.target.cpu_list, "cpu",
  805. "list of cpus to monitor"),
  806. OPT_BOOLEAN('f', "force", &record.force,
  807. "overwrite existing data file (deprecated)"),
  808. OPT_U64('c', "count", &record.opts.user_interval, "event period to sample"),
  809. OPT_STRING('o', "output", &record.output_name, "file",
  810. "output file name"),
  811. OPT_BOOLEAN('i', "no-inherit", &record.opts.no_inherit,
  812. "child tasks do not inherit counters"),
  813. OPT_UINTEGER('F', "freq", &record.opts.user_freq, "profile at this frequency"),
  814. OPT_UINTEGER('m', "mmap-pages", &record.opts.mmap_pages,
  815. "number of mmap data pages"),
  816. OPT_BOOLEAN(0, "group", &record.opts.group,
  817. "put the counters into a counter group"),
  818. OPT_CALLBACK_DEFAULT('g', "call-graph", &record, "mode[,dump_size]",
  819. callchain_help, &parse_callchain_opt,
  820. "fp"),
  821. OPT_INCR('v', "verbose", &verbose,
  822. "be more verbose (show counter open errors, etc)"),
  823. OPT_BOOLEAN('q', "quiet", &quiet, "don't print any message"),
  824. OPT_BOOLEAN('s', "stat", &record.opts.inherit_stat,
  825. "per thread counts"),
  826. OPT_BOOLEAN('d', "data", &record.opts.sample_address,
  827. "Sample addresses"),
  828. OPT_BOOLEAN('T', "timestamp", &record.opts.sample_time, "Sample timestamps"),
  829. OPT_BOOLEAN('P', "period", &record.opts.period, "Sample period"),
  830. OPT_BOOLEAN('n', "no-samples", &record.opts.no_samples,
  831. "don't sample"),
  832. OPT_BOOLEAN('N', "no-buildid-cache", &record.no_buildid_cache,
  833. "do not update the buildid cache"),
  834. OPT_BOOLEAN('B', "no-buildid", &record.no_buildid,
  835. "do not collect buildids in perf.data"),
  836. OPT_CALLBACK('G', "cgroup", &record.evlist, "name",
  837. "monitor event in cgroup name only",
  838. parse_cgroups),
  839. OPT_STRING('u', "uid", &record.opts.target.uid_str, "user",
  840. "user to profile"),
  841. OPT_CALLBACK_NOOPT('b', "branch-any", &record.opts.branch_stack,
  842. "branch any", "sample any taken branches",
  843. parse_branch_stack),
  844. OPT_CALLBACK('j', "branch-filter", &record.opts.branch_stack,
  845. "branch filter mask", "branch stack filter modes",
  846. parse_branch_stack),
  847. OPT_END()
  848. };
  849. int cmd_record(int argc, const char **argv, const char *prefix __maybe_unused)
  850. {
  851. int err = -ENOMEM;
  852. struct perf_evsel *pos;
  853. struct perf_evlist *evsel_list;
  854. struct perf_record *rec = &record;
  855. char errbuf[BUFSIZ];
  856. evsel_list = perf_evlist__new(NULL, NULL);
  857. if (evsel_list == NULL)
  858. return -ENOMEM;
  859. rec->evlist = evsel_list;
  860. argc = parse_options(argc, argv, record_options, record_usage,
  861. PARSE_OPT_STOP_AT_NON_OPTION);
  862. if (!argc && perf_target__none(&rec->opts.target))
  863. usage_with_options(record_usage, record_options);
  864. if (rec->force && rec->append_file) {
  865. ui__error("Can't overwrite and append at the same time."
  866. " You need to choose between -f and -A");
  867. usage_with_options(record_usage, record_options);
  868. } else if (rec->append_file) {
  869. rec->write_mode = WRITE_APPEND;
  870. } else {
  871. rec->write_mode = WRITE_FORCE;
  872. }
  873. if (nr_cgroups && !rec->opts.target.system_wide) {
  874. ui__error("cgroup monitoring only available in"
  875. " system-wide mode\n");
  876. usage_with_options(record_usage, record_options);
  877. }
  878. symbol__init();
  879. if (symbol_conf.kptr_restrict)
  880. pr_warning(
  881. "WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,\n"
  882. "check /proc/sys/kernel/kptr_restrict.\n\n"
  883. "Samples in kernel functions may not be resolved if a suitable vmlinux\n"
  884. "file is not found in the buildid cache or in the vmlinux path.\n\n"
  885. "Samples in kernel modules won't be resolved at all.\n\n"
  886. "If some relocation was applied (e.g. kexec) symbols may be misresolved\n"
  887. "even with a suitable vmlinux or kallsyms file.\n\n");
  888. if (rec->no_buildid_cache || rec->no_buildid)
  889. disable_buildid_cache();
  890. if (evsel_list->nr_entries == 0 &&
  891. perf_evlist__add_default(evsel_list) < 0) {
  892. pr_err("Not enough memory for event selector list\n");
  893. goto out_symbol_exit;
  894. }
  895. err = perf_target__validate(&rec->opts.target);
  896. if (err) {
  897. perf_target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
  898. ui__warning("%s", errbuf);
  899. }
  900. err = perf_target__parse_uid(&rec->opts.target);
  901. if (err) {
  902. int saved_errno = errno;
  903. perf_target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
  904. ui__error("%s", errbuf);
  905. err = -saved_errno;
  906. goto out_free_fd;
  907. }
  908. err = -ENOMEM;
  909. if (perf_evlist__create_maps(evsel_list, &rec->opts.target) < 0)
  910. usage_with_options(record_usage, record_options);
  911. list_for_each_entry(pos, &evsel_list->entries, node) {
  912. if (perf_header__push_event(pos->attr.config, perf_evsel__name(pos)))
  913. goto out_free_fd;
  914. }
  915. if (rec->opts.user_interval != ULLONG_MAX)
  916. rec->opts.default_interval = rec->opts.user_interval;
  917. if (rec->opts.user_freq != UINT_MAX)
  918. rec->opts.freq = rec->opts.user_freq;
  919. /*
  920. * User specified count overrides default frequency.
  921. */
  922. if (rec->opts.default_interval)
  923. rec->opts.freq = 0;
  924. else if (rec->opts.freq) {
  925. rec->opts.default_interval = rec->opts.freq;
  926. } else {
  927. ui__error("frequency and count are zero, aborting\n");
  928. err = -EINVAL;
  929. goto out_free_fd;
  930. }
  931. err = __cmd_record(&record, argc, argv);
  932. out_free_fd:
  933. perf_evlist__delete_maps(evsel_list);
  934. out_symbol_exit:
  935. symbol__exit();
  936. return err;
  937. }