builtin-record.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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/build-id.h"
  11. #include "util/util.h"
  12. #include <subcmd/parse-options.h>
  13. #include "util/parse-events.h"
  14. #include "util/callchain.h"
  15. #include "util/cgroup.h"
  16. #include "util/header.h"
  17. #include "util/event.h"
  18. #include "util/evlist.h"
  19. #include "util/evsel.h"
  20. #include "util/debug.h"
  21. #include "util/session.h"
  22. #include "util/tool.h"
  23. #include "util/symbol.h"
  24. #include "util/cpumap.h"
  25. #include "util/thread_map.h"
  26. #include "util/data.h"
  27. #include "util/perf_regs.h"
  28. #include "util/auxtrace.h"
  29. #include "util/parse-branch-options.h"
  30. #include "util/parse-regs-options.h"
  31. #include "util/llvm-utils.h"
  32. #include <unistd.h>
  33. #include <sched.h>
  34. #include <sys/mman.h>
  35. struct record {
  36. struct perf_tool tool;
  37. struct record_opts opts;
  38. u64 bytes_written;
  39. struct perf_data_file file;
  40. struct auxtrace_record *itr;
  41. struct perf_evlist *evlist;
  42. struct perf_session *session;
  43. const char *progname;
  44. int realtime_prio;
  45. bool no_buildid;
  46. bool no_buildid_cache;
  47. bool buildid_all;
  48. unsigned long long samples;
  49. };
  50. static int record__write(struct record *rec, void *bf, size_t size)
  51. {
  52. if (perf_data_file__write(rec->session->file, bf, size) < 0) {
  53. pr_err("failed to write perf data, error: %m\n");
  54. return -1;
  55. }
  56. rec->bytes_written += size;
  57. return 0;
  58. }
  59. static int process_synthesized_event(struct perf_tool *tool,
  60. union perf_event *event,
  61. struct perf_sample *sample __maybe_unused,
  62. struct machine *machine __maybe_unused)
  63. {
  64. struct record *rec = container_of(tool, struct record, tool);
  65. return record__write(rec, event, event->header.size);
  66. }
  67. static int record__mmap_read(struct record *rec, int idx)
  68. {
  69. struct perf_mmap *md = &rec->evlist->mmap[idx];
  70. u64 head = perf_mmap__read_head(md);
  71. u64 old = md->prev;
  72. unsigned char *data = md->base + page_size;
  73. unsigned long size;
  74. void *buf;
  75. int rc = 0;
  76. if (old == head)
  77. return 0;
  78. rec->samples++;
  79. size = head - old;
  80. if ((old & md->mask) + size != (head & md->mask)) {
  81. buf = &data[old & md->mask];
  82. size = md->mask + 1 - (old & md->mask);
  83. old += size;
  84. if (record__write(rec, buf, size) < 0) {
  85. rc = -1;
  86. goto out;
  87. }
  88. }
  89. buf = &data[old & md->mask];
  90. size = head - old;
  91. old += size;
  92. if (record__write(rec, buf, size) < 0) {
  93. rc = -1;
  94. goto out;
  95. }
  96. md->prev = old;
  97. perf_evlist__mmap_consume(rec->evlist, idx);
  98. out:
  99. return rc;
  100. }
  101. static volatile int done;
  102. static volatile int signr = -1;
  103. static volatile int child_finished;
  104. static volatile int auxtrace_snapshot_enabled;
  105. static volatile int auxtrace_snapshot_err;
  106. static volatile int auxtrace_record__snapshot_started;
  107. static void sig_handler(int sig)
  108. {
  109. if (sig == SIGCHLD)
  110. child_finished = 1;
  111. else
  112. signr = sig;
  113. done = 1;
  114. }
  115. static void record__sig_exit(void)
  116. {
  117. if (signr == -1)
  118. return;
  119. signal(signr, SIG_DFL);
  120. raise(signr);
  121. }
  122. #ifdef HAVE_AUXTRACE_SUPPORT
  123. static int record__process_auxtrace(struct perf_tool *tool,
  124. union perf_event *event, void *data1,
  125. size_t len1, void *data2, size_t len2)
  126. {
  127. struct record *rec = container_of(tool, struct record, tool);
  128. struct perf_data_file *file = &rec->file;
  129. size_t padding;
  130. u8 pad[8] = {0};
  131. if (!perf_data_file__is_pipe(file)) {
  132. off_t file_offset;
  133. int fd = perf_data_file__fd(file);
  134. int err;
  135. file_offset = lseek(fd, 0, SEEK_CUR);
  136. if (file_offset == -1)
  137. return -1;
  138. err = auxtrace_index__auxtrace_event(&rec->session->auxtrace_index,
  139. event, file_offset);
  140. if (err)
  141. return err;
  142. }
  143. /* event.auxtrace.size includes padding, see __auxtrace_mmap__read() */
  144. padding = (len1 + len2) & 7;
  145. if (padding)
  146. padding = 8 - padding;
  147. record__write(rec, event, event->header.size);
  148. record__write(rec, data1, len1);
  149. if (len2)
  150. record__write(rec, data2, len2);
  151. record__write(rec, &pad, padding);
  152. return 0;
  153. }
  154. static int record__auxtrace_mmap_read(struct record *rec,
  155. struct auxtrace_mmap *mm)
  156. {
  157. int ret;
  158. ret = auxtrace_mmap__read(mm, rec->itr, &rec->tool,
  159. record__process_auxtrace);
  160. if (ret < 0)
  161. return ret;
  162. if (ret)
  163. rec->samples++;
  164. return 0;
  165. }
  166. static int record__auxtrace_mmap_read_snapshot(struct record *rec,
  167. struct auxtrace_mmap *mm)
  168. {
  169. int ret;
  170. ret = auxtrace_mmap__read_snapshot(mm, rec->itr, &rec->tool,
  171. record__process_auxtrace,
  172. rec->opts.auxtrace_snapshot_size);
  173. if (ret < 0)
  174. return ret;
  175. if (ret)
  176. rec->samples++;
  177. return 0;
  178. }
  179. static int record__auxtrace_read_snapshot_all(struct record *rec)
  180. {
  181. int i;
  182. int rc = 0;
  183. for (i = 0; i < rec->evlist->nr_mmaps; i++) {
  184. struct auxtrace_mmap *mm =
  185. &rec->evlist->mmap[i].auxtrace_mmap;
  186. if (!mm->base)
  187. continue;
  188. if (record__auxtrace_mmap_read_snapshot(rec, mm) != 0) {
  189. rc = -1;
  190. goto out;
  191. }
  192. }
  193. out:
  194. return rc;
  195. }
  196. static void record__read_auxtrace_snapshot(struct record *rec)
  197. {
  198. pr_debug("Recording AUX area tracing snapshot\n");
  199. if (record__auxtrace_read_snapshot_all(rec) < 0) {
  200. auxtrace_snapshot_err = -1;
  201. } else {
  202. auxtrace_snapshot_err = auxtrace_record__snapshot_finish(rec->itr);
  203. if (!auxtrace_snapshot_err)
  204. auxtrace_snapshot_enabled = 1;
  205. }
  206. }
  207. #else
  208. static inline
  209. int record__auxtrace_mmap_read(struct record *rec __maybe_unused,
  210. struct auxtrace_mmap *mm __maybe_unused)
  211. {
  212. return 0;
  213. }
  214. static inline
  215. void record__read_auxtrace_snapshot(struct record *rec __maybe_unused)
  216. {
  217. }
  218. static inline
  219. int auxtrace_record__snapshot_start(struct auxtrace_record *itr __maybe_unused)
  220. {
  221. return 0;
  222. }
  223. #endif
  224. static int record__open(struct record *rec)
  225. {
  226. char msg[512];
  227. struct perf_evsel *pos;
  228. struct perf_evlist *evlist = rec->evlist;
  229. struct perf_session *session = rec->session;
  230. struct record_opts *opts = &rec->opts;
  231. int rc = 0;
  232. perf_evlist__config(evlist, opts);
  233. evlist__for_each(evlist, pos) {
  234. try_again:
  235. if (perf_evsel__open(pos, pos->cpus, pos->threads) < 0) {
  236. if (perf_evsel__fallback(pos, errno, msg, sizeof(msg))) {
  237. if (verbose)
  238. ui__warning("%s\n", msg);
  239. goto try_again;
  240. }
  241. rc = -errno;
  242. perf_evsel__open_strerror(pos, &opts->target,
  243. errno, msg, sizeof(msg));
  244. ui__error("%s\n", msg);
  245. goto out;
  246. }
  247. }
  248. if (perf_evlist__apply_filters(evlist, &pos)) {
  249. error("failed to set filter \"%s\" on event %s with %d (%s)\n",
  250. pos->filter, perf_evsel__name(pos), errno,
  251. strerror_r(errno, msg, sizeof(msg)));
  252. rc = -1;
  253. goto out;
  254. }
  255. if (perf_evlist__mmap_ex(evlist, opts->mmap_pages, false,
  256. opts->auxtrace_mmap_pages,
  257. opts->auxtrace_snapshot_mode) < 0) {
  258. if (errno == EPERM) {
  259. pr_err("Permission error mapping pages.\n"
  260. "Consider increasing "
  261. "/proc/sys/kernel/perf_event_mlock_kb,\n"
  262. "or try again with a smaller value of -m/--mmap_pages.\n"
  263. "(current value: %u,%u)\n",
  264. opts->mmap_pages, opts->auxtrace_mmap_pages);
  265. rc = -errno;
  266. } else {
  267. pr_err("failed to mmap with %d (%s)\n", errno,
  268. strerror_r(errno, msg, sizeof(msg)));
  269. rc = -errno;
  270. }
  271. goto out;
  272. }
  273. session->evlist = evlist;
  274. perf_session__set_id_hdr_size(session);
  275. out:
  276. return rc;
  277. }
  278. static int process_sample_event(struct perf_tool *tool,
  279. union perf_event *event,
  280. struct perf_sample *sample,
  281. struct perf_evsel *evsel,
  282. struct machine *machine)
  283. {
  284. struct record *rec = container_of(tool, struct record, tool);
  285. rec->samples++;
  286. return build_id__mark_dso_hit(tool, event, sample, evsel, machine);
  287. }
  288. static int process_buildids(struct record *rec)
  289. {
  290. struct perf_data_file *file = &rec->file;
  291. struct perf_session *session = rec->session;
  292. if (file->size == 0)
  293. return 0;
  294. /*
  295. * During this process, it'll load kernel map and replace the
  296. * dso->long_name to a real pathname it found. In this case
  297. * we prefer the vmlinux path like
  298. * /lib/modules/3.16.4/build/vmlinux
  299. *
  300. * rather than build-id path (in debug directory).
  301. * $HOME/.debug/.build-id/f0/6e17aa50adf4d00b88925e03775de107611551
  302. */
  303. symbol_conf.ignore_vmlinux_buildid = true;
  304. /*
  305. * If --buildid-all is given, it marks all DSO regardless of hits,
  306. * so no need to process samples.
  307. */
  308. if (rec->buildid_all)
  309. rec->tool.sample = NULL;
  310. return perf_session__process_events(session);
  311. }
  312. static void perf_event__synthesize_guest_os(struct machine *machine, void *data)
  313. {
  314. int err;
  315. struct perf_tool *tool = data;
  316. /*
  317. *As for guest kernel when processing subcommand record&report,
  318. *we arrange module mmap prior to guest kernel mmap and trigger
  319. *a preload dso because default guest module symbols are loaded
  320. *from guest kallsyms instead of /lib/modules/XXX/XXX. This
  321. *method is used to avoid symbol missing when the first addr is
  322. *in module instead of in guest kernel.
  323. */
  324. err = perf_event__synthesize_modules(tool, process_synthesized_event,
  325. machine);
  326. if (err < 0)
  327. pr_err("Couldn't record guest kernel [%d]'s reference"
  328. " relocation symbol.\n", machine->pid);
  329. /*
  330. * We use _stext for guest kernel because guest kernel's /proc/kallsyms
  331. * have no _text sometimes.
  332. */
  333. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  334. machine);
  335. if (err < 0)
  336. pr_err("Couldn't record guest kernel [%d]'s reference"
  337. " relocation symbol.\n", machine->pid);
  338. }
  339. static struct perf_event_header finished_round_event = {
  340. .size = sizeof(struct perf_event_header),
  341. .type = PERF_RECORD_FINISHED_ROUND,
  342. };
  343. static int record__mmap_read_all(struct record *rec)
  344. {
  345. u64 bytes_written = rec->bytes_written;
  346. int i;
  347. int rc = 0;
  348. for (i = 0; i < rec->evlist->nr_mmaps; i++) {
  349. struct auxtrace_mmap *mm = &rec->evlist->mmap[i].auxtrace_mmap;
  350. if (rec->evlist->mmap[i].base) {
  351. if (record__mmap_read(rec, i) != 0) {
  352. rc = -1;
  353. goto out;
  354. }
  355. }
  356. if (mm->base && !rec->opts.auxtrace_snapshot_mode &&
  357. record__auxtrace_mmap_read(rec, mm) != 0) {
  358. rc = -1;
  359. goto out;
  360. }
  361. }
  362. /*
  363. * Mark the round finished in case we wrote
  364. * at least one event.
  365. */
  366. if (bytes_written != rec->bytes_written)
  367. rc = record__write(rec, &finished_round_event, sizeof(finished_round_event));
  368. out:
  369. return rc;
  370. }
  371. static void record__init_features(struct record *rec)
  372. {
  373. struct perf_session *session = rec->session;
  374. int feat;
  375. for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
  376. perf_header__set_feat(&session->header, feat);
  377. if (rec->no_buildid)
  378. perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
  379. if (!have_tracepoints(&rec->evlist->entries))
  380. perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
  381. if (!rec->opts.branch_stack)
  382. perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
  383. if (!rec->opts.full_auxtrace)
  384. perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
  385. perf_header__clear_feat(&session->header, HEADER_STAT);
  386. }
  387. static volatile int workload_exec_errno;
  388. /*
  389. * perf_evlist__prepare_workload will send a SIGUSR1
  390. * if the fork fails, since we asked by setting its
  391. * want_signal to true.
  392. */
  393. static void workload_exec_failed_signal(int signo __maybe_unused,
  394. siginfo_t *info,
  395. void *ucontext __maybe_unused)
  396. {
  397. workload_exec_errno = info->si_value.sival_int;
  398. done = 1;
  399. child_finished = 1;
  400. }
  401. static void snapshot_sig_handler(int sig);
  402. static int __cmd_record(struct record *rec, int argc, const char **argv)
  403. {
  404. int err;
  405. int status = 0;
  406. unsigned long waking = 0;
  407. const bool forks = argc > 0;
  408. struct machine *machine;
  409. struct perf_tool *tool = &rec->tool;
  410. struct record_opts *opts = &rec->opts;
  411. struct perf_data_file *file = &rec->file;
  412. struct perf_session *session;
  413. bool disabled = false, draining = false;
  414. int fd;
  415. rec->progname = argv[0];
  416. atexit(record__sig_exit);
  417. signal(SIGCHLD, sig_handler);
  418. signal(SIGINT, sig_handler);
  419. signal(SIGTERM, sig_handler);
  420. if (rec->opts.auxtrace_snapshot_mode)
  421. signal(SIGUSR2, snapshot_sig_handler);
  422. else
  423. signal(SIGUSR2, SIG_IGN);
  424. session = perf_session__new(file, false, tool);
  425. if (session == NULL) {
  426. pr_err("Perf session creation failed.\n");
  427. return -1;
  428. }
  429. fd = perf_data_file__fd(file);
  430. rec->session = session;
  431. record__init_features(rec);
  432. if (forks) {
  433. err = perf_evlist__prepare_workload(rec->evlist, &opts->target,
  434. argv, file->is_pipe,
  435. workload_exec_failed_signal);
  436. if (err < 0) {
  437. pr_err("Couldn't run the workload!\n");
  438. status = err;
  439. goto out_delete_session;
  440. }
  441. }
  442. if (record__open(rec) != 0) {
  443. err = -1;
  444. goto out_child;
  445. }
  446. /*
  447. * Normally perf_session__new would do this, but it doesn't have the
  448. * evlist.
  449. */
  450. if (rec->tool.ordered_events && !perf_evlist__sample_id_all(rec->evlist)) {
  451. pr_warning("WARNING: No sample_id_all support, falling back to unordered processing\n");
  452. rec->tool.ordered_events = false;
  453. }
  454. if (!rec->evlist->nr_groups)
  455. perf_header__clear_feat(&session->header, HEADER_GROUP_DESC);
  456. if (file->is_pipe) {
  457. err = perf_header__write_pipe(fd);
  458. if (err < 0)
  459. goto out_child;
  460. } else {
  461. err = perf_session__write_header(session, rec->evlist, fd, false);
  462. if (err < 0)
  463. goto out_child;
  464. }
  465. if (!rec->no_buildid
  466. && !perf_header__has_feat(&session->header, HEADER_BUILD_ID)) {
  467. pr_err("Couldn't generate buildids. "
  468. "Use --no-buildid to profile anyway.\n");
  469. err = -1;
  470. goto out_child;
  471. }
  472. machine = &session->machines.host;
  473. if (file->is_pipe) {
  474. err = perf_event__synthesize_attrs(tool, session,
  475. process_synthesized_event);
  476. if (err < 0) {
  477. pr_err("Couldn't synthesize attrs.\n");
  478. goto out_child;
  479. }
  480. if (have_tracepoints(&rec->evlist->entries)) {
  481. /*
  482. * FIXME err <= 0 here actually means that
  483. * there were no tracepoints so its not really
  484. * an error, just that we don't need to
  485. * synthesize anything. We really have to
  486. * return this more properly and also
  487. * propagate errors that now are calling die()
  488. */
  489. err = perf_event__synthesize_tracing_data(tool, fd, rec->evlist,
  490. process_synthesized_event);
  491. if (err <= 0) {
  492. pr_err("Couldn't record tracing data.\n");
  493. goto out_child;
  494. }
  495. rec->bytes_written += err;
  496. }
  497. }
  498. if (rec->opts.full_auxtrace) {
  499. err = perf_event__synthesize_auxtrace_info(rec->itr, tool,
  500. session, process_synthesized_event);
  501. if (err)
  502. goto out_delete_session;
  503. }
  504. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  505. machine);
  506. if (err < 0)
  507. pr_err("Couldn't record kernel reference relocation symbol\n"
  508. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  509. "Check /proc/kallsyms permission or run as root.\n");
  510. err = perf_event__synthesize_modules(tool, process_synthesized_event,
  511. machine);
  512. if (err < 0)
  513. pr_err("Couldn't record kernel module information.\n"
  514. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  515. "Check /proc/modules permission or run as root.\n");
  516. if (perf_guest) {
  517. machines__process_guests(&session->machines,
  518. perf_event__synthesize_guest_os, tool);
  519. }
  520. err = __machine__synthesize_threads(machine, tool, &opts->target, rec->evlist->threads,
  521. process_synthesized_event, opts->sample_address,
  522. opts->proc_map_timeout);
  523. if (err != 0)
  524. goto out_child;
  525. if (rec->realtime_prio) {
  526. struct sched_param param;
  527. param.sched_priority = rec->realtime_prio;
  528. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  529. pr_err("Could not set realtime priority.\n");
  530. err = -1;
  531. goto out_child;
  532. }
  533. }
  534. /*
  535. * When perf is starting the traced process, all the events
  536. * (apart from group members) have enable_on_exec=1 set,
  537. * so don't spoil it by prematurely enabling them.
  538. */
  539. if (!target__none(&opts->target) && !opts->initial_delay)
  540. perf_evlist__enable(rec->evlist);
  541. /*
  542. * Let the child rip
  543. */
  544. if (forks) {
  545. union perf_event *event;
  546. event = malloc(sizeof(event->comm) + machine->id_hdr_size);
  547. if (event == NULL) {
  548. err = -ENOMEM;
  549. goto out_child;
  550. }
  551. /*
  552. * Some H/W events are generated before COMM event
  553. * which is emitted during exec(), so perf script
  554. * cannot see a correct process name for those events.
  555. * Synthesize COMM event to prevent it.
  556. */
  557. perf_event__synthesize_comm(tool, event,
  558. rec->evlist->workload.pid,
  559. process_synthesized_event,
  560. machine);
  561. free(event);
  562. perf_evlist__start_workload(rec->evlist);
  563. }
  564. if (opts->initial_delay) {
  565. usleep(opts->initial_delay * 1000);
  566. perf_evlist__enable(rec->evlist);
  567. }
  568. auxtrace_snapshot_enabled = 1;
  569. for (;;) {
  570. unsigned long long hits = rec->samples;
  571. if (record__mmap_read_all(rec) < 0) {
  572. auxtrace_snapshot_enabled = 0;
  573. err = -1;
  574. goto out_child;
  575. }
  576. if (auxtrace_record__snapshot_started) {
  577. auxtrace_record__snapshot_started = 0;
  578. if (!auxtrace_snapshot_err)
  579. record__read_auxtrace_snapshot(rec);
  580. if (auxtrace_snapshot_err) {
  581. pr_err("AUX area tracing snapshot failed\n");
  582. err = -1;
  583. goto out_child;
  584. }
  585. }
  586. if (hits == rec->samples) {
  587. if (done || draining)
  588. break;
  589. err = perf_evlist__poll(rec->evlist, -1);
  590. /*
  591. * Propagate error, only if there's any. Ignore positive
  592. * number of returned events and interrupt error.
  593. */
  594. if (err > 0 || (err < 0 && errno == EINTR))
  595. err = 0;
  596. waking++;
  597. if (perf_evlist__filter_pollfd(rec->evlist, POLLERR | POLLHUP) == 0)
  598. draining = true;
  599. }
  600. /*
  601. * When perf is starting the traced process, at the end events
  602. * die with the process and we wait for that. Thus no need to
  603. * disable events in this case.
  604. */
  605. if (done && !disabled && !target__none(&opts->target)) {
  606. auxtrace_snapshot_enabled = 0;
  607. perf_evlist__disable(rec->evlist);
  608. disabled = true;
  609. }
  610. }
  611. auxtrace_snapshot_enabled = 0;
  612. if (forks && workload_exec_errno) {
  613. char msg[STRERR_BUFSIZE];
  614. const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
  615. pr_err("Workload failed: %s\n", emsg);
  616. err = -1;
  617. goto out_child;
  618. }
  619. if (!quiet)
  620. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  621. out_child:
  622. if (forks) {
  623. int exit_status;
  624. if (!child_finished)
  625. kill(rec->evlist->workload.pid, SIGTERM);
  626. wait(&exit_status);
  627. if (err < 0)
  628. status = err;
  629. else if (WIFEXITED(exit_status))
  630. status = WEXITSTATUS(exit_status);
  631. else if (WIFSIGNALED(exit_status))
  632. signr = WTERMSIG(exit_status);
  633. } else
  634. status = err;
  635. /* this will be recalculated during process_buildids() */
  636. rec->samples = 0;
  637. if (!err && !file->is_pipe) {
  638. rec->session->header.data_size += rec->bytes_written;
  639. file->size = lseek(perf_data_file__fd(file), 0, SEEK_CUR);
  640. if (!rec->no_buildid) {
  641. process_buildids(rec);
  642. if (rec->buildid_all)
  643. dsos__hit_all(rec->session);
  644. }
  645. perf_session__write_header(rec->session, rec->evlist, fd, true);
  646. }
  647. if (!err && !quiet) {
  648. char samples[128];
  649. if (rec->samples && !rec->opts.full_auxtrace)
  650. scnprintf(samples, sizeof(samples),
  651. " (%" PRIu64 " samples)", rec->samples);
  652. else
  653. samples[0] = '\0';
  654. fprintf(stderr, "[ perf record: Captured and wrote %.3f MB %s%s ]\n",
  655. perf_data_file__size(file) / 1024.0 / 1024.0,
  656. file->path, samples);
  657. }
  658. out_delete_session:
  659. perf_session__delete(session);
  660. return status;
  661. }
  662. static void callchain_debug(void)
  663. {
  664. static const char *str[CALLCHAIN_MAX] = { "NONE", "FP", "DWARF", "LBR" };
  665. pr_debug("callchain: type %s\n", str[callchain_param.record_mode]);
  666. if (callchain_param.record_mode == CALLCHAIN_DWARF)
  667. pr_debug("callchain: stack dump size %d\n",
  668. callchain_param.dump_size);
  669. }
  670. int record_parse_callchain_opt(const struct option *opt,
  671. const char *arg,
  672. int unset)
  673. {
  674. int ret;
  675. struct record_opts *record = (struct record_opts *)opt->value;
  676. record->callgraph_set = true;
  677. callchain_param.enabled = !unset;
  678. /* --no-call-graph */
  679. if (unset) {
  680. callchain_param.record_mode = CALLCHAIN_NONE;
  681. pr_debug("callchain: disabled\n");
  682. return 0;
  683. }
  684. ret = parse_callchain_record_opt(arg, &callchain_param);
  685. if (!ret) {
  686. /* Enable data address sampling for DWARF unwind. */
  687. if (callchain_param.record_mode == CALLCHAIN_DWARF)
  688. record->sample_address = true;
  689. callchain_debug();
  690. }
  691. return ret;
  692. }
  693. int record_callchain_opt(const struct option *opt,
  694. const char *arg __maybe_unused,
  695. int unset __maybe_unused)
  696. {
  697. struct record_opts *record = (struct record_opts *)opt->value;
  698. record->callgraph_set = true;
  699. callchain_param.enabled = true;
  700. if (callchain_param.record_mode == CALLCHAIN_NONE)
  701. callchain_param.record_mode = CALLCHAIN_FP;
  702. callchain_debug();
  703. return 0;
  704. }
  705. static int perf_record_config(const char *var, const char *value, void *cb)
  706. {
  707. struct record *rec = cb;
  708. if (!strcmp(var, "record.build-id")) {
  709. if (!strcmp(value, "cache"))
  710. rec->no_buildid_cache = false;
  711. else if (!strcmp(value, "no-cache"))
  712. rec->no_buildid_cache = true;
  713. else if (!strcmp(value, "skip"))
  714. rec->no_buildid = true;
  715. else
  716. return -1;
  717. return 0;
  718. }
  719. if (!strcmp(var, "record.call-graph"))
  720. var = "call-graph.record-mode"; /* fall-through */
  721. return perf_default_config(var, value, cb);
  722. }
  723. struct clockid_map {
  724. const char *name;
  725. int clockid;
  726. };
  727. #define CLOCKID_MAP(n, c) \
  728. { .name = n, .clockid = (c), }
  729. #define CLOCKID_END { .name = NULL, }
  730. /*
  731. * Add the missing ones, we need to build on many distros...
  732. */
  733. #ifndef CLOCK_MONOTONIC_RAW
  734. #define CLOCK_MONOTONIC_RAW 4
  735. #endif
  736. #ifndef CLOCK_BOOTTIME
  737. #define CLOCK_BOOTTIME 7
  738. #endif
  739. #ifndef CLOCK_TAI
  740. #define CLOCK_TAI 11
  741. #endif
  742. static const struct clockid_map clockids[] = {
  743. /* available for all events, NMI safe */
  744. CLOCKID_MAP("monotonic", CLOCK_MONOTONIC),
  745. CLOCKID_MAP("monotonic_raw", CLOCK_MONOTONIC_RAW),
  746. /* available for some events */
  747. CLOCKID_MAP("realtime", CLOCK_REALTIME),
  748. CLOCKID_MAP("boottime", CLOCK_BOOTTIME),
  749. CLOCKID_MAP("tai", CLOCK_TAI),
  750. /* available for the lazy */
  751. CLOCKID_MAP("mono", CLOCK_MONOTONIC),
  752. CLOCKID_MAP("raw", CLOCK_MONOTONIC_RAW),
  753. CLOCKID_MAP("real", CLOCK_REALTIME),
  754. CLOCKID_MAP("boot", CLOCK_BOOTTIME),
  755. CLOCKID_END,
  756. };
  757. static int parse_clockid(const struct option *opt, const char *str, int unset)
  758. {
  759. struct record_opts *opts = (struct record_opts *)opt->value;
  760. const struct clockid_map *cm;
  761. const char *ostr = str;
  762. if (unset) {
  763. opts->use_clockid = 0;
  764. return 0;
  765. }
  766. /* no arg passed */
  767. if (!str)
  768. return 0;
  769. /* no setting it twice */
  770. if (opts->use_clockid)
  771. return -1;
  772. opts->use_clockid = true;
  773. /* if its a number, we're done */
  774. if (sscanf(str, "%d", &opts->clockid) == 1)
  775. return 0;
  776. /* allow a "CLOCK_" prefix to the name */
  777. if (!strncasecmp(str, "CLOCK_", 6))
  778. str += 6;
  779. for (cm = clockids; cm->name; cm++) {
  780. if (!strcasecmp(str, cm->name)) {
  781. opts->clockid = cm->clockid;
  782. return 0;
  783. }
  784. }
  785. opts->use_clockid = false;
  786. ui__warning("unknown clockid %s, check man page\n", ostr);
  787. return -1;
  788. }
  789. static int record__parse_mmap_pages(const struct option *opt,
  790. const char *str,
  791. int unset __maybe_unused)
  792. {
  793. struct record_opts *opts = opt->value;
  794. char *s, *p;
  795. unsigned int mmap_pages;
  796. int ret;
  797. if (!str)
  798. return -EINVAL;
  799. s = strdup(str);
  800. if (!s)
  801. return -ENOMEM;
  802. p = strchr(s, ',');
  803. if (p)
  804. *p = '\0';
  805. if (*s) {
  806. ret = __perf_evlist__parse_mmap_pages(&mmap_pages, s);
  807. if (ret)
  808. goto out_free;
  809. opts->mmap_pages = mmap_pages;
  810. }
  811. if (!p) {
  812. ret = 0;
  813. goto out_free;
  814. }
  815. ret = __perf_evlist__parse_mmap_pages(&mmap_pages, p + 1);
  816. if (ret)
  817. goto out_free;
  818. opts->auxtrace_mmap_pages = mmap_pages;
  819. out_free:
  820. free(s);
  821. return ret;
  822. }
  823. static const char * const __record_usage[] = {
  824. "perf record [<options>] [<command>]",
  825. "perf record [<options>] -- <command> [<options>]",
  826. NULL
  827. };
  828. const char * const *record_usage = __record_usage;
  829. /*
  830. * XXX Ideally would be local to cmd_record() and passed to a record__new
  831. * because we need to have access to it in record__exit, that is called
  832. * after cmd_record() exits, but since record_options need to be accessible to
  833. * builtin-script, leave it here.
  834. *
  835. * At least we don't ouch it in all the other functions here directly.
  836. *
  837. * Just say no to tons of global variables, sigh.
  838. */
  839. static struct record record = {
  840. .opts = {
  841. .sample_time = true,
  842. .mmap_pages = UINT_MAX,
  843. .user_freq = UINT_MAX,
  844. .user_interval = ULLONG_MAX,
  845. .freq = 4000,
  846. .target = {
  847. .uses_mmap = true,
  848. .default_per_cpu = true,
  849. },
  850. .proc_map_timeout = 500,
  851. },
  852. .tool = {
  853. .sample = process_sample_event,
  854. .fork = perf_event__process_fork,
  855. .exit = perf_event__process_exit,
  856. .comm = perf_event__process_comm,
  857. .mmap = perf_event__process_mmap,
  858. .mmap2 = perf_event__process_mmap2,
  859. .ordered_events = true,
  860. },
  861. };
  862. const char record_callchain_help[] = CALLCHAIN_RECORD_HELP
  863. "\n\t\t\t\tDefault: fp";
  864. /*
  865. * XXX Will stay a global variable till we fix builtin-script.c to stop messing
  866. * with it and switch to use the library functions in perf_evlist that came
  867. * from builtin-record.c, i.e. use record_opts,
  868. * perf_evlist__prepare_workload, etc instead of fork+exec'in 'perf record',
  869. * using pipes, etc.
  870. */
  871. struct option __record_options[] = {
  872. OPT_CALLBACK('e', "event", &record.evlist, "event",
  873. "event selector. use 'perf list' to list available events",
  874. parse_events_option),
  875. OPT_CALLBACK(0, "filter", &record.evlist, "filter",
  876. "event filter", parse_filter),
  877. OPT_CALLBACK_NOOPT(0, "exclude-perf", &record.evlist,
  878. NULL, "don't record events from perf itself",
  879. exclude_perf),
  880. OPT_STRING('p', "pid", &record.opts.target.pid, "pid",
  881. "record events on existing process id"),
  882. OPT_STRING('t', "tid", &record.opts.target.tid, "tid",
  883. "record events on existing thread id"),
  884. OPT_INTEGER('r', "realtime", &record.realtime_prio,
  885. "collect data with this RT SCHED_FIFO priority"),
  886. OPT_BOOLEAN(0, "no-buffering", &record.opts.no_buffering,
  887. "collect data without buffering"),
  888. OPT_BOOLEAN('R', "raw-samples", &record.opts.raw_samples,
  889. "collect raw sample records from all opened counters"),
  890. OPT_BOOLEAN('a', "all-cpus", &record.opts.target.system_wide,
  891. "system-wide collection from all CPUs"),
  892. OPT_STRING('C', "cpu", &record.opts.target.cpu_list, "cpu",
  893. "list of cpus to monitor"),
  894. OPT_U64('c', "count", &record.opts.user_interval, "event period to sample"),
  895. OPT_STRING('o', "output", &record.file.path, "file",
  896. "output file name"),
  897. OPT_BOOLEAN_SET('i', "no-inherit", &record.opts.no_inherit,
  898. &record.opts.no_inherit_set,
  899. "child tasks do not inherit counters"),
  900. OPT_UINTEGER('F', "freq", &record.opts.user_freq, "profile at this frequency"),
  901. OPT_CALLBACK('m', "mmap-pages", &record.opts, "pages[,pages]",
  902. "number of mmap data pages and AUX area tracing mmap pages",
  903. record__parse_mmap_pages),
  904. OPT_BOOLEAN(0, "group", &record.opts.group,
  905. "put the counters into a counter group"),
  906. OPT_CALLBACK_NOOPT('g', NULL, &record.opts,
  907. NULL, "enables call-graph recording" ,
  908. &record_callchain_opt),
  909. OPT_CALLBACK(0, "call-graph", &record.opts,
  910. "record_mode[,record_size]", record_callchain_help,
  911. &record_parse_callchain_opt),
  912. OPT_INCR('v', "verbose", &verbose,
  913. "be more verbose (show counter open errors, etc)"),
  914. OPT_BOOLEAN('q', "quiet", &quiet, "don't print any message"),
  915. OPT_BOOLEAN('s', "stat", &record.opts.inherit_stat,
  916. "per thread counts"),
  917. OPT_BOOLEAN('d', "data", &record.opts.sample_address, "Record the sample addresses"),
  918. OPT_BOOLEAN_SET('T', "timestamp", &record.opts.sample_time,
  919. &record.opts.sample_time_set,
  920. "Record the sample timestamps"),
  921. OPT_BOOLEAN('P', "period", &record.opts.period, "Record the sample period"),
  922. OPT_BOOLEAN('n', "no-samples", &record.opts.no_samples,
  923. "don't sample"),
  924. OPT_BOOLEAN('N', "no-buildid-cache", &record.no_buildid_cache,
  925. "do not update the buildid cache"),
  926. OPT_BOOLEAN('B', "no-buildid", &record.no_buildid,
  927. "do not collect buildids in perf.data"),
  928. OPT_CALLBACK('G', "cgroup", &record.evlist, "name",
  929. "monitor event in cgroup name only",
  930. parse_cgroups),
  931. OPT_UINTEGER('D', "delay", &record.opts.initial_delay,
  932. "ms to wait before starting measurement after program start"),
  933. OPT_STRING('u', "uid", &record.opts.target.uid_str, "user",
  934. "user to profile"),
  935. OPT_CALLBACK_NOOPT('b', "branch-any", &record.opts.branch_stack,
  936. "branch any", "sample any taken branches",
  937. parse_branch_stack),
  938. OPT_CALLBACK('j', "branch-filter", &record.opts.branch_stack,
  939. "branch filter mask", "branch stack filter modes",
  940. parse_branch_stack),
  941. OPT_BOOLEAN('W', "weight", &record.opts.sample_weight,
  942. "sample by weight (on special events only)"),
  943. OPT_BOOLEAN(0, "transaction", &record.opts.sample_transaction,
  944. "sample transaction flags (special events only)"),
  945. OPT_BOOLEAN(0, "per-thread", &record.opts.target.per_thread,
  946. "use per-thread mmaps"),
  947. OPT_CALLBACK_OPTARG('I', "intr-regs", &record.opts.sample_intr_regs, NULL, "any register",
  948. "sample selected machine registers on interrupt,"
  949. " use -I ? to list register names", parse_regs),
  950. OPT_BOOLEAN(0, "running-time", &record.opts.running_time,
  951. "Record running/enabled time of read (:S) events"),
  952. OPT_CALLBACK('k', "clockid", &record.opts,
  953. "clockid", "clockid to use for events, see clock_gettime()",
  954. parse_clockid),
  955. OPT_STRING_OPTARG('S', "snapshot", &record.opts.auxtrace_snapshot_opts,
  956. "opts", "AUX area tracing Snapshot Mode", ""),
  957. OPT_UINTEGER(0, "proc-map-timeout", &record.opts.proc_map_timeout,
  958. "per thread proc mmap processing timeout in ms"),
  959. OPT_BOOLEAN(0, "switch-events", &record.opts.record_switch_events,
  960. "Record context switch events"),
  961. OPT_STRING(0, "clang-path", &llvm_param.clang_path, "clang path",
  962. "clang binary to use for compiling BPF scriptlets"),
  963. OPT_STRING(0, "clang-opt", &llvm_param.clang_opt, "clang options",
  964. "options passed to clang when compiling BPF scriptlets"),
  965. OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
  966. "file", "vmlinux pathname"),
  967. OPT_BOOLEAN(0, "buildid-all", &record.buildid_all,
  968. "Record build-id of all DSOs regardless of hits"),
  969. OPT_END()
  970. };
  971. struct option *record_options = __record_options;
  972. int cmd_record(int argc, const char **argv, const char *prefix __maybe_unused)
  973. {
  974. int err;
  975. struct record *rec = &record;
  976. char errbuf[BUFSIZ];
  977. #ifndef HAVE_LIBBPF_SUPPORT
  978. # define set_nobuild(s, l, c) set_option_nobuild(record_options, s, l, "NO_LIBBPF=1", c)
  979. set_nobuild('\0', "clang-path", true);
  980. set_nobuild('\0', "clang-opt", true);
  981. # undef set_nobuild
  982. #endif
  983. #ifndef HAVE_BPF_PROLOGUE
  984. # if !defined (HAVE_DWARF_SUPPORT)
  985. # define REASON "NO_DWARF=1"
  986. # elif !defined (HAVE_LIBBPF_SUPPORT)
  987. # define REASON "NO_LIBBPF=1"
  988. # else
  989. # define REASON "this architecture doesn't support BPF prologue"
  990. # endif
  991. # define set_nobuild(s, l, c) set_option_nobuild(record_options, s, l, REASON, c)
  992. set_nobuild('\0', "vmlinux", true);
  993. # undef set_nobuild
  994. # undef REASON
  995. #endif
  996. rec->evlist = perf_evlist__new();
  997. if (rec->evlist == NULL)
  998. return -ENOMEM;
  999. perf_config(perf_record_config, rec);
  1000. argc = parse_options(argc, argv, record_options, record_usage,
  1001. PARSE_OPT_STOP_AT_NON_OPTION);
  1002. if (!argc && target__none(&rec->opts.target))
  1003. usage_with_options(record_usage, record_options);
  1004. if (nr_cgroups && !rec->opts.target.system_wide) {
  1005. usage_with_options_msg(record_usage, record_options,
  1006. "cgroup monitoring only available in system-wide mode");
  1007. }
  1008. if (rec->opts.record_switch_events &&
  1009. !perf_can_record_switch_events()) {
  1010. ui__error("kernel does not support recording context switch events\n");
  1011. parse_options_usage(record_usage, record_options, "switch-events", 0);
  1012. return -EINVAL;
  1013. }
  1014. if (!rec->itr) {
  1015. rec->itr = auxtrace_record__init(rec->evlist, &err);
  1016. if (err)
  1017. return err;
  1018. }
  1019. err = auxtrace_parse_snapshot_options(rec->itr, &rec->opts,
  1020. rec->opts.auxtrace_snapshot_opts);
  1021. if (err)
  1022. return err;
  1023. err = -ENOMEM;
  1024. symbol__init(NULL);
  1025. if (symbol_conf.kptr_restrict)
  1026. pr_warning(
  1027. "WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,\n"
  1028. "check /proc/sys/kernel/kptr_restrict.\n\n"
  1029. "Samples in kernel functions may not be resolved if a suitable vmlinux\n"
  1030. "file is not found in the buildid cache or in the vmlinux path.\n\n"
  1031. "Samples in kernel modules won't be resolved at all.\n\n"
  1032. "If some relocation was applied (e.g. kexec) symbols may be misresolved\n"
  1033. "even with a suitable vmlinux or kallsyms file.\n\n");
  1034. if (rec->no_buildid_cache || rec->no_buildid)
  1035. disable_buildid_cache();
  1036. if (rec->evlist->nr_entries == 0 &&
  1037. perf_evlist__add_default(rec->evlist) < 0) {
  1038. pr_err("Not enough memory for event selector list\n");
  1039. goto out_symbol_exit;
  1040. }
  1041. if (rec->opts.target.tid && !rec->opts.no_inherit_set)
  1042. rec->opts.no_inherit = true;
  1043. err = target__validate(&rec->opts.target);
  1044. if (err) {
  1045. target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
  1046. ui__warning("%s", errbuf);
  1047. }
  1048. err = target__parse_uid(&rec->opts.target);
  1049. if (err) {
  1050. int saved_errno = errno;
  1051. target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
  1052. ui__error("%s", errbuf);
  1053. err = -saved_errno;
  1054. goto out_symbol_exit;
  1055. }
  1056. err = -ENOMEM;
  1057. if (perf_evlist__create_maps(rec->evlist, &rec->opts.target) < 0)
  1058. usage_with_options(record_usage, record_options);
  1059. err = auxtrace_record__options(rec->itr, rec->evlist, &rec->opts);
  1060. if (err)
  1061. goto out_symbol_exit;
  1062. /*
  1063. * We take all buildids when the file contains
  1064. * AUX area tracing data because we do not decode the
  1065. * trace because it would take too long.
  1066. */
  1067. if (rec->opts.full_auxtrace)
  1068. rec->buildid_all = true;
  1069. if (record_opts__config(&rec->opts)) {
  1070. err = -EINVAL;
  1071. goto out_symbol_exit;
  1072. }
  1073. err = __cmd_record(&record, argc, argv);
  1074. out_symbol_exit:
  1075. perf_evlist__delete(rec->evlist);
  1076. symbol__exit();
  1077. auxtrace_record__free(rec->itr);
  1078. return err;
  1079. }
  1080. static void snapshot_sig_handler(int sig __maybe_unused)
  1081. {
  1082. if (!auxtrace_snapshot_enabled)
  1083. return;
  1084. auxtrace_snapshot_enabled = 0;
  1085. auxtrace_snapshot_err = auxtrace_record__snapshot_start(record.itr);
  1086. auxtrace_record__snapshot_started = 1;
  1087. }