builtin-record.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * builtin-record.c
  4. *
  5. * Builtin record command: Record the profile of a workload
  6. * (or a CPU, or a PID) into the perf.data output file - for
  7. * later analysis via perf report.
  8. */
  9. #include "builtin.h"
  10. #include "perf.h"
  11. #include "util/build-id.h"
  12. #include "util/util.h"
  13. #include <subcmd/parse-options.h>
  14. #include "util/parse-events.h"
  15. #include "util/config.h"
  16. #include "util/callchain.h"
  17. #include "util/cgroup.h"
  18. #include "util/header.h"
  19. #include "util/event.h"
  20. #include "util/evlist.h"
  21. #include "util/evsel.h"
  22. #include "util/debug.h"
  23. #include "util/drv_configs.h"
  24. #include "util/session.h"
  25. #include "util/tool.h"
  26. #include "util/symbol.h"
  27. #include "util/cpumap.h"
  28. #include "util/thread_map.h"
  29. #include "util/data.h"
  30. #include "util/perf_regs.h"
  31. #include "util/auxtrace.h"
  32. #include "util/tsc.h"
  33. #include "util/parse-branch-options.h"
  34. #include "util/parse-regs-options.h"
  35. #include "util/llvm-utils.h"
  36. #include "util/bpf-loader.h"
  37. #include "util/trigger.h"
  38. #include "util/perf-hooks.h"
  39. #include "util/time-utils.h"
  40. #include "util/units.h"
  41. #include "asm/bug.h"
  42. #include <errno.h>
  43. #include <inttypes.h>
  44. #include <locale.h>
  45. #include <poll.h>
  46. #include <unistd.h>
  47. #include <sched.h>
  48. #include <signal.h>
  49. #include <sys/mman.h>
  50. #include <sys/wait.h>
  51. #include <linux/time64.h>
  52. struct switch_output {
  53. bool enabled;
  54. bool signal;
  55. unsigned long size;
  56. unsigned long time;
  57. const char *str;
  58. bool set;
  59. };
  60. struct record {
  61. struct perf_tool tool;
  62. struct record_opts opts;
  63. u64 bytes_written;
  64. struct perf_data data;
  65. struct auxtrace_record *itr;
  66. struct perf_evlist *evlist;
  67. struct perf_session *session;
  68. int realtime_prio;
  69. bool no_buildid;
  70. bool no_buildid_set;
  71. bool no_buildid_cache;
  72. bool no_buildid_cache_set;
  73. bool buildid_all;
  74. bool timestamp_filename;
  75. bool timestamp_boundary;
  76. struct switch_output switch_output;
  77. unsigned long long samples;
  78. };
  79. static volatile int auxtrace_record__snapshot_started;
  80. static DEFINE_TRIGGER(auxtrace_snapshot_trigger);
  81. static DEFINE_TRIGGER(switch_output_trigger);
  82. static bool switch_output_signal(struct record *rec)
  83. {
  84. return rec->switch_output.signal &&
  85. trigger_is_ready(&switch_output_trigger);
  86. }
  87. static bool switch_output_size(struct record *rec)
  88. {
  89. return rec->switch_output.size &&
  90. trigger_is_ready(&switch_output_trigger) &&
  91. (rec->bytes_written >= rec->switch_output.size);
  92. }
  93. static bool switch_output_time(struct record *rec)
  94. {
  95. return rec->switch_output.time &&
  96. trigger_is_ready(&switch_output_trigger);
  97. }
  98. static int record__write(struct record *rec, void *bf, size_t size)
  99. {
  100. if (perf_data__write(rec->session->data, bf, size) < 0) {
  101. pr_err("failed to write perf data, error: %m\n");
  102. return -1;
  103. }
  104. rec->bytes_written += size;
  105. if (switch_output_size(rec))
  106. trigger_hit(&switch_output_trigger);
  107. return 0;
  108. }
  109. static int process_synthesized_event(struct perf_tool *tool,
  110. union perf_event *event,
  111. struct perf_sample *sample __maybe_unused,
  112. struct machine *machine __maybe_unused)
  113. {
  114. struct record *rec = container_of(tool, struct record, tool);
  115. return record__write(rec, event, event->header.size);
  116. }
  117. static int record__pushfn(void *to, void *bf, size_t size)
  118. {
  119. struct record *rec = to;
  120. rec->samples++;
  121. return record__write(rec, bf, size);
  122. }
  123. static volatile int done;
  124. static volatile int signr = -1;
  125. static volatile int child_finished;
  126. static void sig_handler(int sig)
  127. {
  128. if (sig == SIGCHLD)
  129. child_finished = 1;
  130. else
  131. signr = sig;
  132. done = 1;
  133. }
  134. static void sigsegv_handler(int sig)
  135. {
  136. perf_hooks__recover();
  137. sighandler_dump_stack(sig);
  138. }
  139. static void record__sig_exit(void)
  140. {
  141. if (signr == -1)
  142. return;
  143. signal(signr, SIG_DFL);
  144. raise(signr);
  145. }
  146. #ifdef HAVE_AUXTRACE_SUPPORT
  147. static int record__process_auxtrace(struct perf_tool *tool,
  148. union perf_event *event, void *data1,
  149. size_t len1, void *data2, size_t len2)
  150. {
  151. struct record *rec = container_of(tool, struct record, tool);
  152. struct perf_data *data = &rec->data;
  153. size_t padding;
  154. u8 pad[8] = {0};
  155. if (!perf_data__is_pipe(data)) {
  156. off_t file_offset;
  157. int fd = perf_data__fd(data);
  158. int err;
  159. file_offset = lseek(fd, 0, SEEK_CUR);
  160. if (file_offset == -1)
  161. return -1;
  162. err = auxtrace_index__auxtrace_event(&rec->session->auxtrace_index,
  163. event, file_offset);
  164. if (err)
  165. return err;
  166. }
  167. /* event.auxtrace.size includes padding, see __auxtrace_mmap__read() */
  168. padding = (len1 + len2) & 7;
  169. if (padding)
  170. padding = 8 - padding;
  171. record__write(rec, event, event->header.size);
  172. record__write(rec, data1, len1);
  173. if (len2)
  174. record__write(rec, data2, len2);
  175. record__write(rec, &pad, padding);
  176. return 0;
  177. }
  178. static int record__auxtrace_mmap_read(struct record *rec,
  179. struct auxtrace_mmap *mm)
  180. {
  181. int ret;
  182. ret = auxtrace_mmap__read(mm, rec->itr, &rec->tool,
  183. record__process_auxtrace);
  184. if (ret < 0)
  185. return ret;
  186. if (ret)
  187. rec->samples++;
  188. return 0;
  189. }
  190. static int record__auxtrace_mmap_read_snapshot(struct record *rec,
  191. struct auxtrace_mmap *mm)
  192. {
  193. int ret;
  194. ret = auxtrace_mmap__read_snapshot(mm, rec->itr, &rec->tool,
  195. record__process_auxtrace,
  196. rec->opts.auxtrace_snapshot_size);
  197. if (ret < 0)
  198. return ret;
  199. if (ret)
  200. rec->samples++;
  201. return 0;
  202. }
  203. static int record__auxtrace_read_snapshot_all(struct record *rec)
  204. {
  205. int i;
  206. int rc = 0;
  207. for (i = 0; i < rec->evlist->nr_mmaps; i++) {
  208. struct auxtrace_mmap *mm =
  209. &rec->evlist->mmap[i].auxtrace_mmap;
  210. if (!mm->base)
  211. continue;
  212. if (record__auxtrace_mmap_read_snapshot(rec, mm) != 0) {
  213. rc = -1;
  214. goto out;
  215. }
  216. }
  217. out:
  218. return rc;
  219. }
  220. static void record__read_auxtrace_snapshot(struct record *rec)
  221. {
  222. pr_debug("Recording AUX area tracing snapshot\n");
  223. if (record__auxtrace_read_snapshot_all(rec) < 0) {
  224. trigger_error(&auxtrace_snapshot_trigger);
  225. } else {
  226. if (auxtrace_record__snapshot_finish(rec->itr))
  227. trigger_error(&auxtrace_snapshot_trigger);
  228. else
  229. trigger_ready(&auxtrace_snapshot_trigger);
  230. }
  231. }
  232. static int record__auxtrace_init(struct record *rec)
  233. {
  234. int err;
  235. if (!rec->itr) {
  236. rec->itr = auxtrace_record__init(rec->evlist, &err);
  237. if (err)
  238. return err;
  239. }
  240. err = auxtrace_parse_snapshot_options(rec->itr, &rec->opts,
  241. rec->opts.auxtrace_snapshot_opts);
  242. if (err)
  243. return err;
  244. return auxtrace_parse_filters(rec->evlist);
  245. }
  246. #else
  247. static inline
  248. int record__auxtrace_mmap_read(struct record *rec __maybe_unused,
  249. struct auxtrace_mmap *mm __maybe_unused)
  250. {
  251. return 0;
  252. }
  253. static inline
  254. void record__read_auxtrace_snapshot(struct record *rec __maybe_unused)
  255. {
  256. }
  257. static inline
  258. int auxtrace_record__snapshot_start(struct auxtrace_record *itr __maybe_unused)
  259. {
  260. return 0;
  261. }
  262. static int record__auxtrace_init(struct record *rec __maybe_unused)
  263. {
  264. return 0;
  265. }
  266. #endif
  267. static int record__mmap_evlist(struct record *rec,
  268. struct perf_evlist *evlist)
  269. {
  270. struct record_opts *opts = &rec->opts;
  271. char msg[512];
  272. if (perf_evlist__mmap_ex(evlist, opts->mmap_pages,
  273. opts->auxtrace_mmap_pages,
  274. opts->auxtrace_snapshot_mode) < 0) {
  275. if (errno == EPERM) {
  276. pr_err("Permission error mapping pages.\n"
  277. "Consider increasing "
  278. "/proc/sys/kernel/perf_event_mlock_kb,\n"
  279. "or try again with a smaller value of -m/--mmap_pages.\n"
  280. "(current value: %u,%u)\n",
  281. opts->mmap_pages, opts->auxtrace_mmap_pages);
  282. return -errno;
  283. } else {
  284. pr_err("failed to mmap with %d (%s)\n", errno,
  285. str_error_r(errno, msg, sizeof(msg)));
  286. if (errno)
  287. return -errno;
  288. else
  289. return -EINVAL;
  290. }
  291. }
  292. return 0;
  293. }
  294. static int record__mmap(struct record *rec)
  295. {
  296. return record__mmap_evlist(rec, rec->evlist);
  297. }
  298. static int record__open(struct record *rec)
  299. {
  300. char msg[BUFSIZ];
  301. struct perf_evsel *pos;
  302. struct perf_evlist *evlist = rec->evlist;
  303. struct perf_session *session = rec->session;
  304. struct record_opts *opts = &rec->opts;
  305. struct perf_evsel_config_term *err_term;
  306. int rc = 0;
  307. /*
  308. * For initial_delay we need to add a dummy event so that we can track
  309. * PERF_RECORD_MMAP while we wait for the initial delay to enable the
  310. * real events, the ones asked by the user.
  311. */
  312. if (opts->initial_delay) {
  313. if (perf_evlist__add_dummy(evlist))
  314. return -ENOMEM;
  315. pos = perf_evlist__first(evlist);
  316. pos->tracking = 0;
  317. pos = perf_evlist__last(evlist);
  318. pos->tracking = 1;
  319. pos->attr.enable_on_exec = 1;
  320. }
  321. perf_evlist__config(evlist, opts, &callchain_param);
  322. evlist__for_each_entry(evlist, pos) {
  323. try_again:
  324. if (perf_evsel__open(pos, pos->cpus, pos->threads) < 0) {
  325. if (perf_evsel__fallback(pos, errno, msg, sizeof(msg))) {
  326. if (verbose > 0)
  327. ui__warning("%s\n", msg);
  328. goto try_again;
  329. }
  330. rc = -errno;
  331. perf_evsel__open_strerror(pos, &opts->target,
  332. errno, msg, sizeof(msg));
  333. ui__error("%s\n", msg);
  334. goto out;
  335. }
  336. pos->supported = true;
  337. }
  338. if (perf_evlist__apply_filters(evlist, &pos)) {
  339. pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
  340. pos->filter, perf_evsel__name(pos), errno,
  341. str_error_r(errno, msg, sizeof(msg)));
  342. rc = -1;
  343. goto out;
  344. }
  345. if (perf_evlist__apply_drv_configs(evlist, &pos, &err_term)) {
  346. pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
  347. err_term->val.drv_cfg, perf_evsel__name(pos), errno,
  348. str_error_r(errno, msg, sizeof(msg)));
  349. rc = -1;
  350. goto out;
  351. }
  352. rc = record__mmap(rec);
  353. if (rc)
  354. goto out;
  355. session->evlist = evlist;
  356. perf_session__set_id_hdr_size(session);
  357. out:
  358. return rc;
  359. }
  360. static int process_sample_event(struct perf_tool *tool,
  361. union perf_event *event,
  362. struct perf_sample *sample,
  363. struct perf_evsel *evsel,
  364. struct machine *machine)
  365. {
  366. struct record *rec = container_of(tool, struct record, tool);
  367. if (rec->evlist->first_sample_time == 0)
  368. rec->evlist->first_sample_time = sample->time;
  369. rec->evlist->last_sample_time = sample->time;
  370. if (rec->buildid_all)
  371. return 0;
  372. rec->samples++;
  373. return build_id__mark_dso_hit(tool, event, sample, evsel, machine);
  374. }
  375. static int process_buildids(struct record *rec)
  376. {
  377. struct perf_data *data = &rec->data;
  378. struct perf_session *session = rec->session;
  379. if (data->size == 0)
  380. return 0;
  381. /*
  382. * During this process, it'll load kernel map and replace the
  383. * dso->long_name to a real pathname it found. In this case
  384. * we prefer the vmlinux path like
  385. * /lib/modules/3.16.4/build/vmlinux
  386. *
  387. * rather than build-id path (in debug directory).
  388. * $HOME/.debug/.build-id/f0/6e17aa50adf4d00b88925e03775de107611551
  389. */
  390. symbol_conf.ignore_vmlinux_buildid = true;
  391. /*
  392. * If --buildid-all is given, it marks all DSO regardless of hits,
  393. * so no need to process samples. But if timestamp_boundary is enabled,
  394. * it still needs to walk on all samples to get the timestamps of
  395. * first/last samples.
  396. */
  397. if (rec->buildid_all && !rec->timestamp_boundary)
  398. rec->tool.sample = NULL;
  399. return perf_session__process_events(session);
  400. }
  401. static void perf_event__synthesize_guest_os(struct machine *machine, void *data)
  402. {
  403. int err;
  404. struct perf_tool *tool = data;
  405. /*
  406. *As for guest kernel when processing subcommand record&report,
  407. *we arrange module mmap prior to guest kernel mmap and trigger
  408. *a preload dso because default guest module symbols are loaded
  409. *from guest kallsyms instead of /lib/modules/XXX/XXX. This
  410. *method is used to avoid symbol missing when the first addr is
  411. *in module instead of in guest kernel.
  412. */
  413. err = perf_event__synthesize_modules(tool, process_synthesized_event,
  414. machine);
  415. if (err < 0)
  416. pr_err("Couldn't record guest kernel [%d]'s reference"
  417. " relocation symbol.\n", machine->pid);
  418. /*
  419. * We use _stext for guest kernel because guest kernel's /proc/kallsyms
  420. * have no _text sometimes.
  421. */
  422. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  423. machine);
  424. if (err < 0)
  425. pr_err("Couldn't record guest kernel [%d]'s reference"
  426. " relocation symbol.\n", machine->pid);
  427. }
  428. static struct perf_event_header finished_round_event = {
  429. .size = sizeof(struct perf_event_header),
  430. .type = PERF_RECORD_FINISHED_ROUND,
  431. };
  432. static int record__mmap_read_evlist(struct record *rec, struct perf_evlist *evlist,
  433. bool overwrite)
  434. {
  435. u64 bytes_written = rec->bytes_written;
  436. int i;
  437. int rc = 0;
  438. struct perf_mmap *maps;
  439. if (!evlist)
  440. return 0;
  441. maps = overwrite ? evlist->overwrite_mmap : evlist->mmap;
  442. if (!maps)
  443. return 0;
  444. if (overwrite && evlist->bkw_mmap_state != BKW_MMAP_DATA_PENDING)
  445. return 0;
  446. for (i = 0; i < evlist->nr_mmaps; i++) {
  447. struct auxtrace_mmap *mm = &maps[i].auxtrace_mmap;
  448. if (maps[i].base) {
  449. if (perf_mmap__push(&maps[i], rec, record__pushfn) != 0) {
  450. rc = -1;
  451. goto out;
  452. }
  453. }
  454. if (mm->base && !rec->opts.auxtrace_snapshot_mode &&
  455. record__auxtrace_mmap_read(rec, mm) != 0) {
  456. rc = -1;
  457. goto out;
  458. }
  459. }
  460. /*
  461. * Mark the round finished in case we wrote
  462. * at least one event.
  463. */
  464. if (bytes_written != rec->bytes_written)
  465. rc = record__write(rec, &finished_round_event, sizeof(finished_round_event));
  466. if (overwrite)
  467. perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_EMPTY);
  468. out:
  469. return rc;
  470. }
  471. static int record__mmap_read_all(struct record *rec)
  472. {
  473. int err;
  474. err = record__mmap_read_evlist(rec, rec->evlist, false);
  475. if (err)
  476. return err;
  477. return record__mmap_read_evlist(rec, rec->evlist, true);
  478. }
  479. static void record__init_features(struct record *rec)
  480. {
  481. struct perf_session *session = rec->session;
  482. int feat;
  483. for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
  484. perf_header__set_feat(&session->header, feat);
  485. if (rec->no_buildid)
  486. perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
  487. if (!have_tracepoints(&rec->evlist->entries))
  488. perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
  489. if (!rec->opts.branch_stack)
  490. perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
  491. if (!rec->opts.full_auxtrace)
  492. perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
  493. perf_header__clear_feat(&session->header, HEADER_STAT);
  494. }
  495. static void
  496. record__finish_output(struct record *rec)
  497. {
  498. struct perf_data *data = &rec->data;
  499. int fd = perf_data__fd(data);
  500. if (data->is_pipe)
  501. return;
  502. rec->session->header.data_size += rec->bytes_written;
  503. data->size = lseek(perf_data__fd(data), 0, SEEK_CUR);
  504. if (!rec->no_buildid) {
  505. process_buildids(rec);
  506. if (rec->buildid_all)
  507. dsos__hit_all(rec->session);
  508. }
  509. perf_session__write_header(rec->session, rec->evlist, fd, true);
  510. return;
  511. }
  512. static int record__synthesize_workload(struct record *rec, bool tail)
  513. {
  514. int err;
  515. struct thread_map *thread_map;
  516. if (rec->opts.tail_synthesize != tail)
  517. return 0;
  518. thread_map = thread_map__new_by_tid(rec->evlist->workload.pid);
  519. if (thread_map == NULL)
  520. return -1;
  521. err = perf_event__synthesize_thread_map(&rec->tool, thread_map,
  522. process_synthesized_event,
  523. &rec->session->machines.host,
  524. rec->opts.sample_address,
  525. rec->opts.proc_map_timeout);
  526. thread_map__put(thread_map);
  527. return err;
  528. }
  529. static int record__synthesize(struct record *rec, bool tail);
  530. static int
  531. record__switch_output(struct record *rec, bool at_exit)
  532. {
  533. struct perf_data *data = &rec->data;
  534. int fd, err;
  535. /* Same Size: "2015122520103046"*/
  536. char timestamp[] = "InvalidTimestamp";
  537. record__synthesize(rec, true);
  538. if (target__none(&rec->opts.target))
  539. record__synthesize_workload(rec, true);
  540. rec->samples = 0;
  541. record__finish_output(rec);
  542. err = fetch_current_timestamp(timestamp, sizeof(timestamp));
  543. if (err) {
  544. pr_err("Failed to get current timestamp\n");
  545. return -EINVAL;
  546. }
  547. fd = perf_data__switch(data, timestamp,
  548. rec->session->header.data_offset,
  549. at_exit);
  550. if (fd >= 0 && !at_exit) {
  551. rec->bytes_written = 0;
  552. rec->session->header.data_size = 0;
  553. }
  554. if (!quiet)
  555. fprintf(stderr, "[ perf record: Dump %s.%s ]\n",
  556. data->file.path, timestamp);
  557. /* Output tracking events */
  558. if (!at_exit) {
  559. record__synthesize(rec, false);
  560. /*
  561. * In 'perf record --switch-output' without -a,
  562. * record__synthesize() in record__switch_output() won't
  563. * generate tracking events because there's no thread_map
  564. * in evlist. Which causes newly created perf.data doesn't
  565. * contain map and comm information.
  566. * Create a fake thread_map and directly call
  567. * perf_event__synthesize_thread_map() for those events.
  568. */
  569. if (target__none(&rec->opts.target))
  570. record__synthesize_workload(rec, false);
  571. }
  572. return fd;
  573. }
  574. static volatile int workload_exec_errno;
  575. /*
  576. * perf_evlist__prepare_workload will send a SIGUSR1
  577. * if the fork fails, since we asked by setting its
  578. * want_signal to true.
  579. */
  580. static void workload_exec_failed_signal(int signo __maybe_unused,
  581. siginfo_t *info,
  582. void *ucontext __maybe_unused)
  583. {
  584. workload_exec_errno = info->si_value.sival_int;
  585. done = 1;
  586. child_finished = 1;
  587. }
  588. static void snapshot_sig_handler(int sig);
  589. static void alarm_sig_handler(int sig);
  590. int __weak
  591. perf_event__synth_time_conv(const struct perf_event_mmap_page *pc __maybe_unused,
  592. struct perf_tool *tool __maybe_unused,
  593. perf_event__handler_t process __maybe_unused,
  594. struct machine *machine __maybe_unused)
  595. {
  596. return 0;
  597. }
  598. static const struct perf_event_mmap_page *
  599. perf_evlist__pick_pc(struct perf_evlist *evlist)
  600. {
  601. if (evlist) {
  602. if (evlist->mmap && evlist->mmap[0].base)
  603. return evlist->mmap[0].base;
  604. if (evlist->overwrite_mmap && evlist->overwrite_mmap[0].base)
  605. return evlist->overwrite_mmap[0].base;
  606. }
  607. return NULL;
  608. }
  609. static const struct perf_event_mmap_page *record__pick_pc(struct record *rec)
  610. {
  611. const struct perf_event_mmap_page *pc;
  612. pc = perf_evlist__pick_pc(rec->evlist);
  613. if (pc)
  614. return pc;
  615. return NULL;
  616. }
  617. static int record__synthesize(struct record *rec, bool tail)
  618. {
  619. struct perf_session *session = rec->session;
  620. struct machine *machine = &session->machines.host;
  621. struct perf_data *data = &rec->data;
  622. struct record_opts *opts = &rec->opts;
  623. struct perf_tool *tool = &rec->tool;
  624. int fd = perf_data__fd(data);
  625. int err = 0;
  626. if (rec->opts.tail_synthesize != tail)
  627. return 0;
  628. if (data->is_pipe) {
  629. /*
  630. * We need to synthesize events first, because some
  631. * features works on top of them (on report side).
  632. */
  633. err = perf_event__synthesize_attrs(tool, session,
  634. process_synthesized_event);
  635. if (err < 0) {
  636. pr_err("Couldn't synthesize attrs.\n");
  637. goto out;
  638. }
  639. err = perf_event__synthesize_features(tool, session, rec->evlist,
  640. process_synthesized_event);
  641. if (err < 0) {
  642. pr_err("Couldn't synthesize features.\n");
  643. return err;
  644. }
  645. if (have_tracepoints(&rec->evlist->entries)) {
  646. /*
  647. * FIXME err <= 0 here actually means that
  648. * there were no tracepoints so its not really
  649. * an error, just that we don't need to
  650. * synthesize anything. We really have to
  651. * return this more properly and also
  652. * propagate errors that now are calling die()
  653. */
  654. err = perf_event__synthesize_tracing_data(tool, fd, rec->evlist,
  655. process_synthesized_event);
  656. if (err <= 0) {
  657. pr_err("Couldn't record tracing data.\n");
  658. goto out;
  659. }
  660. rec->bytes_written += err;
  661. }
  662. }
  663. err = perf_event__synth_time_conv(record__pick_pc(rec), tool,
  664. process_synthesized_event, machine);
  665. if (err)
  666. goto out;
  667. if (rec->opts.full_auxtrace) {
  668. err = perf_event__synthesize_auxtrace_info(rec->itr, tool,
  669. session, process_synthesized_event);
  670. if (err)
  671. goto out;
  672. }
  673. if (!perf_evlist__exclude_kernel(rec->evlist)) {
  674. err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
  675. machine);
  676. WARN_ONCE(err < 0, "Couldn't record kernel reference relocation symbol\n"
  677. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  678. "Check /proc/kallsyms permission or run as root.\n");
  679. err = perf_event__synthesize_modules(tool, process_synthesized_event,
  680. machine);
  681. WARN_ONCE(err < 0, "Couldn't record kernel module information.\n"
  682. "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
  683. "Check /proc/modules permission or run as root.\n");
  684. }
  685. if (perf_guest) {
  686. machines__process_guests(&session->machines,
  687. perf_event__synthesize_guest_os, tool);
  688. }
  689. err = perf_event__synthesize_extra_attr(&rec->tool,
  690. rec->evlist,
  691. process_synthesized_event,
  692. data->is_pipe);
  693. if (err)
  694. goto out;
  695. err = perf_event__synthesize_thread_map2(&rec->tool, rec->evlist->threads,
  696. process_synthesized_event,
  697. NULL);
  698. if (err < 0) {
  699. pr_err("Couldn't synthesize thread map.\n");
  700. return err;
  701. }
  702. err = perf_event__synthesize_cpu_map(&rec->tool, rec->evlist->cpus,
  703. process_synthesized_event, NULL);
  704. if (err < 0) {
  705. pr_err("Couldn't synthesize cpu map.\n");
  706. return err;
  707. }
  708. err = __machine__synthesize_threads(machine, tool, &opts->target, rec->evlist->threads,
  709. process_synthesized_event, opts->sample_address,
  710. opts->proc_map_timeout, 1);
  711. out:
  712. return err;
  713. }
  714. static int __cmd_record(struct record *rec, int argc, const char **argv)
  715. {
  716. int err;
  717. int status = 0;
  718. unsigned long waking = 0;
  719. const bool forks = argc > 0;
  720. struct perf_tool *tool = &rec->tool;
  721. struct record_opts *opts = &rec->opts;
  722. struct perf_data *data = &rec->data;
  723. struct perf_session *session;
  724. bool disabled = false, draining = false;
  725. int fd;
  726. atexit(record__sig_exit);
  727. signal(SIGCHLD, sig_handler);
  728. signal(SIGINT, sig_handler);
  729. signal(SIGTERM, sig_handler);
  730. signal(SIGSEGV, sigsegv_handler);
  731. if (rec->opts.record_namespaces)
  732. tool->namespace_events = true;
  733. if (rec->opts.auxtrace_snapshot_mode || rec->switch_output.enabled) {
  734. signal(SIGUSR2, snapshot_sig_handler);
  735. if (rec->opts.auxtrace_snapshot_mode)
  736. trigger_on(&auxtrace_snapshot_trigger);
  737. if (rec->switch_output.enabled)
  738. trigger_on(&switch_output_trigger);
  739. } else {
  740. signal(SIGUSR2, SIG_IGN);
  741. }
  742. session = perf_session__new(data, false, tool);
  743. if (session == NULL) {
  744. pr_err("Perf session creation failed.\n");
  745. return -1;
  746. }
  747. fd = perf_data__fd(data);
  748. rec->session = session;
  749. record__init_features(rec);
  750. if (forks) {
  751. err = perf_evlist__prepare_workload(rec->evlist, &opts->target,
  752. argv, data->is_pipe,
  753. workload_exec_failed_signal);
  754. if (err < 0) {
  755. pr_err("Couldn't run the workload!\n");
  756. status = err;
  757. goto out_delete_session;
  758. }
  759. }
  760. /*
  761. * If we have just single event and are sending data
  762. * through pipe, we need to force the ids allocation,
  763. * because we synthesize event name through the pipe
  764. * and need the id for that.
  765. */
  766. if (data->is_pipe && rec->evlist->nr_entries == 1)
  767. rec->opts.sample_id = true;
  768. if (record__open(rec) != 0) {
  769. err = -1;
  770. goto out_child;
  771. }
  772. err = bpf__apply_obj_config();
  773. if (err) {
  774. char errbuf[BUFSIZ];
  775. bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
  776. pr_err("ERROR: Apply config to BPF failed: %s\n",
  777. errbuf);
  778. goto out_child;
  779. }
  780. /*
  781. * Normally perf_session__new would do this, but it doesn't have the
  782. * evlist.
  783. */
  784. if (rec->tool.ordered_events && !perf_evlist__sample_id_all(rec->evlist)) {
  785. pr_warning("WARNING: No sample_id_all support, falling back to unordered processing\n");
  786. rec->tool.ordered_events = false;
  787. }
  788. if (!rec->evlist->nr_groups)
  789. perf_header__clear_feat(&session->header, HEADER_GROUP_DESC);
  790. if (data->is_pipe) {
  791. err = perf_header__write_pipe(fd);
  792. if (err < 0)
  793. goto out_child;
  794. } else {
  795. err = perf_session__write_header(session, rec->evlist, fd, false);
  796. if (err < 0)
  797. goto out_child;
  798. }
  799. if (!rec->no_buildid
  800. && !perf_header__has_feat(&session->header, HEADER_BUILD_ID)) {
  801. pr_err("Couldn't generate buildids. "
  802. "Use --no-buildid to profile anyway.\n");
  803. err = -1;
  804. goto out_child;
  805. }
  806. err = record__synthesize(rec, false);
  807. if (err < 0)
  808. goto out_child;
  809. if (rec->realtime_prio) {
  810. struct sched_param param;
  811. param.sched_priority = rec->realtime_prio;
  812. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  813. pr_err("Could not set realtime priority.\n");
  814. err = -1;
  815. goto out_child;
  816. }
  817. }
  818. /*
  819. * When perf is starting the traced process, all the events
  820. * (apart from group members) have enable_on_exec=1 set,
  821. * so don't spoil it by prematurely enabling them.
  822. */
  823. if (!target__none(&opts->target) && !opts->initial_delay)
  824. perf_evlist__enable(rec->evlist);
  825. /*
  826. * Let the child rip
  827. */
  828. if (forks) {
  829. struct machine *machine = &session->machines.host;
  830. union perf_event *event;
  831. pid_t tgid;
  832. event = malloc(sizeof(event->comm) + machine->id_hdr_size);
  833. if (event == NULL) {
  834. err = -ENOMEM;
  835. goto out_child;
  836. }
  837. /*
  838. * Some H/W events are generated before COMM event
  839. * which is emitted during exec(), so perf script
  840. * cannot see a correct process name for those events.
  841. * Synthesize COMM event to prevent it.
  842. */
  843. tgid = perf_event__synthesize_comm(tool, event,
  844. rec->evlist->workload.pid,
  845. process_synthesized_event,
  846. machine);
  847. free(event);
  848. if (tgid == -1)
  849. goto out_child;
  850. event = malloc(sizeof(event->namespaces) +
  851. (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
  852. machine->id_hdr_size);
  853. if (event == NULL) {
  854. err = -ENOMEM;
  855. goto out_child;
  856. }
  857. /*
  858. * Synthesize NAMESPACES event for the command specified.
  859. */
  860. perf_event__synthesize_namespaces(tool, event,
  861. rec->evlist->workload.pid,
  862. tgid, process_synthesized_event,
  863. machine);
  864. free(event);
  865. perf_evlist__start_workload(rec->evlist);
  866. }
  867. if (opts->initial_delay) {
  868. usleep(opts->initial_delay * USEC_PER_MSEC);
  869. perf_evlist__enable(rec->evlist);
  870. }
  871. trigger_ready(&auxtrace_snapshot_trigger);
  872. trigger_ready(&switch_output_trigger);
  873. perf_hooks__invoke_record_start();
  874. for (;;) {
  875. unsigned long long hits = rec->samples;
  876. /*
  877. * rec->evlist->bkw_mmap_state is possible to be
  878. * BKW_MMAP_EMPTY here: when done == true and
  879. * hits != rec->samples in previous round.
  880. *
  881. * perf_evlist__toggle_bkw_mmap ensure we never
  882. * convert BKW_MMAP_EMPTY to BKW_MMAP_DATA_PENDING.
  883. */
  884. if (trigger_is_hit(&switch_output_trigger) || done || draining)
  885. perf_evlist__toggle_bkw_mmap(rec->evlist, BKW_MMAP_DATA_PENDING);
  886. if (record__mmap_read_all(rec) < 0) {
  887. trigger_error(&auxtrace_snapshot_trigger);
  888. trigger_error(&switch_output_trigger);
  889. err = -1;
  890. goto out_child;
  891. }
  892. if (auxtrace_record__snapshot_started) {
  893. auxtrace_record__snapshot_started = 0;
  894. if (!trigger_is_error(&auxtrace_snapshot_trigger))
  895. record__read_auxtrace_snapshot(rec);
  896. if (trigger_is_error(&auxtrace_snapshot_trigger)) {
  897. pr_err("AUX area tracing snapshot failed\n");
  898. err = -1;
  899. goto out_child;
  900. }
  901. }
  902. if (trigger_is_hit(&switch_output_trigger)) {
  903. /*
  904. * If switch_output_trigger is hit, the data in
  905. * overwritable ring buffer should have been collected,
  906. * so bkw_mmap_state should be set to BKW_MMAP_EMPTY.
  907. *
  908. * If SIGUSR2 raise after or during record__mmap_read_all(),
  909. * record__mmap_read_all() didn't collect data from
  910. * overwritable ring buffer. Read again.
  911. */
  912. if (rec->evlist->bkw_mmap_state == BKW_MMAP_RUNNING)
  913. continue;
  914. trigger_ready(&switch_output_trigger);
  915. /*
  916. * Reenable events in overwrite ring buffer after
  917. * record__mmap_read_all(): we should have collected
  918. * data from it.
  919. */
  920. perf_evlist__toggle_bkw_mmap(rec->evlist, BKW_MMAP_RUNNING);
  921. if (!quiet)
  922. fprintf(stderr, "[ perf record: dump data: Woken up %ld times ]\n",
  923. waking);
  924. waking = 0;
  925. fd = record__switch_output(rec, false);
  926. if (fd < 0) {
  927. pr_err("Failed to switch to new file\n");
  928. trigger_error(&switch_output_trigger);
  929. err = fd;
  930. goto out_child;
  931. }
  932. /* re-arm the alarm */
  933. if (rec->switch_output.time)
  934. alarm(rec->switch_output.time);
  935. }
  936. if (hits == rec->samples) {
  937. if (done || draining)
  938. break;
  939. err = perf_evlist__poll(rec->evlist, -1);
  940. /*
  941. * Propagate error, only if there's any. Ignore positive
  942. * number of returned events and interrupt error.
  943. */
  944. if (err > 0 || (err < 0 && errno == EINTR))
  945. err = 0;
  946. waking++;
  947. if (perf_evlist__filter_pollfd(rec->evlist, POLLERR | POLLHUP) == 0)
  948. draining = true;
  949. }
  950. /*
  951. * When perf is starting the traced process, at the end events
  952. * die with the process and we wait for that. Thus no need to
  953. * disable events in this case.
  954. */
  955. if (done && !disabled && !target__none(&opts->target)) {
  956. trigger_off(&auxtrace_snapshot_trigger);
  957. perf_evlist__disable(rec->evlist);
  958. disabled = true;
  959. }
  960. }
  961. trigger_off(&auxtrace_snapshot_trigger);
  962. trigger_off(&switch_output_trigger);
  963. if (forks && workload_exec_errno) {
  964. char msg[STRERR_BUFSIZE];
  965. const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
  966. pr_err("Workload failed: %s\n", emsg);
  967. err = -1;
  968. goto out_child;
  969. }
  970. if (!quiet)
  971. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  972. if (target__none(&rec->opts.target))
  973. record__synthesize_workload(rec, true);
  974. out_child:
  975. if (forks) {
  976. int exit_status;
  977. if (!child_finished)
  978. kill(rec->evlist->workload.pid, SIGTERM);
  979. wait(&exit_status);
  980. if (err < 0)
  981. status = err;
  982. else if (WIFEXITED(exit_status))
  983. status = WEXITSTATUS(exit_status);
  984. else if (WIFSIGNALED(exit_status))
  985. signr = WTERMSIG(exit_status);
  986. } else
  987. status = err;
  988. record__synthesize(rec, true);
  989. /* this will be recalculated during process_buildids() */
  990. rec->samples = 0;
  991. if (!err) {
  992. if (!rec->timestamp_filename) {
  993. record__finish_output(rec);
  994. } else {
  995. fd = record__switch_output(rec, true);
  996. if (fd < 0) {
  997. status = fd;
  998. goto out_delete_session;
  999. }
  1000. }
  1001. }
  1002. perf_hooks__invoke_record_end();
  1003. if (!err && !quiet) {
  1004. char samples[128];
  1005. const char *postfix = rec->timestamp_filename ?
  1006. ".<timestamp>" : "";
  1007. if (rec->samples && !rec->opts.full_auxtrace)
  1008. scnprintf(samples, sizeof(samples),
  1009. " (%" PRIu64 " samples)", rec->samples);
  1010. else
  1011. samples[0] = '\0';
  1012. fprintf(stderr, "[ perf record: Captured and wrote %.3f MB %s%s%s ]\n",
  1013. perf_data__size(data) / 1024.0 / 1024.0,
  1014. data->file.path, postfix, samples);
  1015. }
  1016. out_delete_session:
  1017. perf_session__delete(session);
  1018. return status;
  1019. }
  1020. static void callchain_debug(struct callchain_param *callchain)
  1021. {
  1022. static const char *str[CALLCHAIN_MAX] = { "NONE", "FP", "DWARF", "LBR" };
  1023. pr_debug("callchain: type %s\n", str[callchain->record_mode]);
  1024. if (callchain->record_mode == CALLCHAIN_DWARF)
  1025. pr_debug("callchain: stack dump size %d\n",
  1026. callchain->dump_size);
  1027. }
  1028. int record_opts__parse_callchain(struct record_opts *record,
  1029. struct callchain_param *callchain,
  1030. const char *arg, bool unset)
  1031. {
  1032. int ret;
  1033. callchain->enabled = !unset;
  1034. /* --no-call-graph */
  1035. if (unset) {
  1036. callchain->record_mode = CALLCHAIN_NONE;
  1037. pr_debug("callchain: disabled\n");
  1038. return 0;
  1039. }
  1040. ret = parse_callchain_record_opt(arg, callchain);
  1041. if (!ret) {
  1042. /* Enable data address sampling for DWARF unwind. */
  1043. if (callchain->record_mode == CALLCHAIN_DWARF)
  1044. record->sample_address = true;
  1045. callchain_debug(callchain);
  1046. }
  1047. return ret;
  1048. }
  1049. int record_parse_callchain_opt(const struct option *opt,
  1050. const char *arg,
  1051. int unset)
  1052. {
  1053. return record_opts__parse_callchain(opt->value, &callchain_param, arg, unset);
  1054. }
  1055. int record_callchain_opt(const struct option *opt,
  1056. const char *arg __maybe_unused,
  1057. int unset __maybe_unused)
  1058. {
  1059. struct callchain_param *callchain = opt->value;
  1060. callchain->enabled = true;
  1061. if (callchain->record_mode == CALLCHAIN_NONE)
  1062. callchain->record_mode = CALLCHAIN_FP;
  1063. callchain_debug(callchain);
  1064. return 0;
  1065. }
  1066. static int perf_record_config(const char *var, const char *value, void *cb)
  1067. {
  1068. struct record *rec = cb;
  1069. if (!strcmp(var, "record.build-id")) {
  1070. if (!strcmp(value, "cache"))
  1071. rec->no_buildid_cache = false;
  1072. else if (!strcmp(value, "no-cache"))
  1073. rec->no_buildid_cache = true;
  1074. else if (!strcmp(value, "skip"))
  1075. rec->no_buildid = true;
  1076. else
  1077. return -1;
  1078. return 0;
  1079. }
  1080. if (!strcmp(var, "record.call-graph")) {
  1081. var = "call-graph.record-mode";
  1082. return perf_default_config(var, value, cb);
  1083. }
  1084. return 0;
  1085. }
  1086. struct clockid_map {
  1087. const char *name;
  1088. int clockid;
  1089. };
  1090. #define CLOCKID_MAP(n, c) \
  1091. { .name = n, .clockid = (c), }
  1092. #define CLOCKID_END { .name = NULL, }
  1093. /*
  1094. * Add the missing ones, we need to build on many distros...
  1095. */
  1096. #ifndef CLOCK_MONOTONIC_RAW
  1097. #define CLOCK_MONOTONIC_RAW 4
  1098. #endif
  1099. #ifndef CLOCK_BOOTTIME
  1100. #define CLOCK_BOOTTIME 7
  1101. #endif
  1102. #ifndef CLOCK_TAI
  1103. #define CLOCK_TAI 11
  1104. #endif
  1105. static const struct clockid_map clockids[] = {
  1106. /* available for all events, NMI safe */
  1107. CLOCKID_MAP("monotonic", CLOCK_MONOTONIC),
  1108. CLOCKID_MAP("monotonic_raw", CLOCK_MONOTONIC_RAW),
  1109. /* available for some events */
  1110. CLOCKID_MAP("realtime", CLOCK_REALTIME),
  1111. CLOCKID_MAP("boottime", CLOCK_BOOTTIME),
  1112. CLOCKID_MAP("tai", CLOCK_TAI),
  1113. /* available for the lazy */
  1114. CLOCKID_MAP("mono", CLOCK_MONOTONIC),
  1115. CLOCKID_MAP("raw", CLOCK_MONOTONIC_RAW),
  1116. CLOCKID_MAP("real", CLOCK_REALTIME),
  1117. CLOCKID_MAP("boot", CLOCK_BOOTTIME),
  1118. CLOCKID_END,
  1119. };
  1120. static int parse_clockid(const struct option *opt, const char *str, int unset)
  1121. {
  1122. struct record_opts *opts = (struct record_opts *)opt->value;
  1123. const struct clockid_map *cm;
  1124. const char *ostr = str;
  1125. if (unset) {
  1126. opts->use_clockid = 0;
  1127. return 0;
  1128. }
  1129. /* no arg passed */
  1130. if (!str)
  1131. return 0;
  1132. /* no setting it twice */
  1133. if (opts->use_clockid)
  1134. return -1;
  1135. opts->use_clockid = true;
  1136. /* if its a number, we're done */
  1137. if (sscanf(str, "%d", &opts->clockid) == 1)
  1138. return 0;
  1139. /* allow a "CLOCK_" prefix to the name */
  1140. if (!strncasecmp(str, "CLOCK_", 6))
  1141. str += 6;
  1142. for (cm = clockids; cm->name; cm++) {
  1143. if (!strcasecmp(str, cm->name)) {
  1144. opts->clockid = cm->clockid;
  1145. return 0;
  1146. }
  1147. }
  1148. opts->use_clockid = false;
  1149. ui__warning("unknown clockid %s, check man page\n", ostr);
  1150. return -1;
  1151. }
  1152. static int record__parse_mmap_pages(const struct option *opt,
  1153. const char *str,
  1154. int unset __maybe_unused)
  1155. {
  1156. struct record_opts *opts = opt->value;
  1157. char *s, *p;
  1158. unsigned int mmap_pages;
  1159. int ret;
  1160. if (!str)
  1161. return -EINVAL;
  1162. s = strdup(str);
  1163. if (!s)
  1164. return -ENOMEM;
  1165. p = strchr(s, ',');
  1166. if (p)
  1167. *p = '\0';
  1168. if (*s) {
  1169. ret = __perf_evlist__parse_mmap_pages(&mmap_pages, s);
  1170. if (ret)
  1171. goto out_free;
  1172. opts->mmap_pages = mmap_pages;
  1173. }
  1174. if (!p) {
  1175. ret = 0;
  1176. goto out_free;
  1177. }
  1178. ret = __perf_evlist__parse_mmap_pages(&mmap_pages, p + 1);
  1179. if (ret)
  1180. goto out_free;
  1181. opts->auxtrace_mmap_pages = mmap_pages;
  1182. out_free:
  1183. free(s);
  1184. return ret;
  1185. }
  1186. static void switch_output_size_warn(struct record *rec)
  1187. {
  1188. u64 wakeup_size = perf_evlist__mmap_size(rec->opts.mmap_pages);
  1189. struct switch_output *s = &rec->switch_output;
  1190. wakeup_size /= 2;
  1191. if (s->size < wakeup_size) {
  1192. char buf[100];
  1193. unit_number__scnprintf(buf, sizeof(buf), wakeup_size);
  1194. pr_warning("WARNING: switch-output data size lower than "
  1195. "wakeup kernel buffer size (%s) "
  1196. "expect bigger perf.data sizes\n", buf);
  1197. }
  1198. }
  1199. static int switch_output_setup(struct record *rec)
  1200. {
  1201. struct switch_output *s = &rec->switch_output;
  1202. static struct parse_tag tags_size[] = {
  1203. { .tag = 'B', .mult = 1 },
  1204. { .tag = 'K', .mult = 1 << 10 },
  1205. { .tag = 'M', .mult = 1 << 20 },
  1206. { .tag = 'G', .mult = 1 << 30 },
  1207. { .tag = 0 },
  1208. };
  1209. static struct parse_tag tags_time[] = {
  1210. { .tag = 's', .mult = 1 },
  1211. { .tag = 'm', .mult = 60 },
  1212. { .tag = 'h', .mult = 60*60 },
  1213. { .tag = 'd', .mult = 60*60*24 },
  1214. { .tag = 0 },
  1215. };
  1216. unsigned long val;
  1217. if (!s->set)
  1218. return 0;
  1219. if (!strcmp(s->str, "signal")) {
  1220. s->signal = true;
  1221. pr_debug("switch-output with SIGUSR2 signal\n");
  1222. goto enabled;
  1223. }
  1224. val = parse_tag_value(s->str, tags_size);
  1225. if (val != (unsigned long) -1) {
  1226. s->size = val;
  1227. pr_debug("switch-output with %s size threshold\n", s->str);
  1228. goto enabled;
  1229. }
  1230. val = parse_tag_value(s->str, tags_time);
  1231. if (val != (unsigned long) -1) {
  1232. s->time = val;
  1233. pr_debug("switch-output with %s time threshold (%lu seconds)\n",
  1234. s->str, s->time);
  1235. goto enabled;
  1236. }
  1237. return -1;
  1238. enabled:
  1239. rec->timestamp_filename = true;
  1240. s->enabled = true;
  1241. if (s->size && !rec->opts.no_buffering)
  1242. switch_output_size_warn(rec);
  1243. return 0;
  1244. }
  1245. static const char * const __record_usage[] = {
  1246. "perf record [<options>] [<command>]",
  1247. "perf record [<options>] -- <command> [<options>]",
  1248. NULL
  1249. };
  1250. const char * const *record_usage = __record_usage;
  1251. /*
  1252. * XXX Ideally would be local to cmd_record() and passed to a record__new
  1253. * because we need to have access to it in record__exit, that is called
  1254. * after cmd_record() exits, but since record_options need to be accessible to
  1255. * builtin-script, leave it here.
  1256. *
  1257. * At least we don't ouch it in all the other functions here directly.
  1258. *
  1259. * Just say no to tons of global variables, sigh.
  1260. */
  1261. static struct record record = {
  1262. .opts = {
  1263. .sample_time = true,
  1264. .mmap_pages = UINT_MAX,
  1265. .user_freq = UINT_MAX,
  1266. .user_interval = ULLONG_MAX,
  1267. .freq = 4000,
  1268. .target = {
  1269. .uses_mmap = true,
  1270. .default_per_cpu = true,
  1271. },
  1272. .proc_map_timeout = 500,
  1273. },
  1274. .tool = {
  1275. .sample = process_sample_event,
  1276. .fork = perf_event__process_fork,
  1277. .exit = perf_event__process_exit,
  1278. .comm = perf_event__process_comm,
  1279. .namespaces = perf_event__process_namespaces,
  1280. .mmap = perf_event__process_mmap,
  1281. .mmap2 = perf_event__process_mmap2,
  1282. .ordered_events = true,
  1283. },
  1284. };
  1285. const char record_callchain_help[] = CALLCHAIN_RECORD_HELP
  1286. "\n\t\t\t\tDefault: fp";
  1287. static bool dry_run;
  1288. /*
  1289. * XXX Will stay a global variable till we fix builtin-script.c to stop messing
  1290. * with it and switch to use the library functions in perf_evlist that came
  1291. * from builtin-record.c, i.e. use record_opts,
  1292. * perf_evlist__prepare_workload, etc instead of fork+exec'in 'perf record',
  1293. * using pipes, etc.
  1294. */
  1295. static struct option __record_options[] = {
  1296. OPT_CALLBACK('e', "event", &record.evlist, "event",
  1297. "event selector. use 'perf list' to list available events",
  1298. parse_events_option),
  1299. OPT_CALLBACK(0, "filter", &record.evlist, "filter",
  1300. "event filter", parse_filter),
  1301. OPT_CALLBACK_NOOPT(0, "exclude-perf", &record.evlist,
  1302. NULL, "don't record events from perf itself",
  1303. exclude_perf),
  1304. OPT_STRING('p', "pid", &record.opts.target.pid, "pid",
  1305. "record events on existing process id"),
  1306. OPT_STRING('t', "tid", &record.opts.target.tid, "tid",
  1307. "record events on existing thread id"),
  1308. OPT_INTEGER('r', "realtime", &record.realtime_prio,
  1309. "collect data with this RT SCHED_FIFO priority"),
  1310. OPT_BOOLEAN(0, "no-buffering", &record.opts.no_buffering,
  1311. "collect data without buffering"),
  1312. OPT_BOOLEAN('R', "raw-samples", &record.opts.raw_samples,
  1313. "collect raw sample records from all opened counters"),
  1314. OPT_BOOLEAN('a', "all-cpus", &record.opts.target.system_wide,
  1315. "system-wide collection from all CPUs"),
  1316. OPT_STRING('C', "cpu", &record.opts.target.cpu_list, "cpu",
  1317. "list of cpus to monitor"),
  1318. OPT_U64('c', "count", &record.opts.user_interval, "event period to sample"),
  1319. OPT_STRING('o', "output", &record.data.file.path, "file",
  1320. "output file name"),
  1321. OPT_BOOLEAN_SET('i', "no-inherit", &record.opts.no_inherit,
  1322. &record.opts.no_inherit_set,
  1323. "child tasks do not inherit counters"),
  1324. OPT_BOOLEAN(0, "tail-synthesize", &record.opts.tail_synthesize,
  1325. "synthesize non-sample events at the end of output"),
  1326. OPT_BOOLEAN(0, "overwrite", &record.opts.overwrite, "use overwrite mode"),
  1327. OPT_BOOLEAN(0, "strict-freq", &record.opts.strict_freq,
  1328. "Fail if the specified frequency can't be used"),
  1329. OPT_CALLBACK('F', "freq", &record.opts, "freq or 'max'",
  1330. "profile at this frequency",
  1331. record__parse_freq),
  1332. OPT_CALLBACK('m', "mmap-pages", &record.opts, "pages[,pages]",
  1333. "number of mmap data pages and AUX area tracing mmap pages",
  1334. record__parse_mmap_pages),
  1335. OPT_BOOLEAN(0, "group", &record.opts.group,
  1336. "put the counters into a counter group"),
  1337. OPT_CALLBACK_NOOPT('g', NULL, &callchain_param,
  1338. NULL, "enables call-graph recording" ,
  1339. &record_callchain_opt),
  1340. OPT_CALLBACK(0, "call-graph", &record.opts,
  1341. "record_mode[,record_size]", record_callchain_help,
  1342. &record_parse_callchain_opt),
  1343. OPT_INCR('v', "verbose", &verbose,
  1344. "be more verbose (show counter open errors, etc)"),
  1345. OPT_BOOLEAN('q', "quiet", &quiet, "don't print any message"),
  1346. OPT_BOOLEAN('s', "stat", &record.opts.inherit_stat,
  1347. "per thread counts"),
  1348. OPT_BOOLEAN('d', "data", &record.opts.sample_address, "Record the sample addresses"),
  1349. OPT_BOOLEAN(0, "phys-data", &record.opts.sample_phys_addr,
  1350. "Record the sample physical addresses"),
  1351. OPT_BOOLEAN(0, "sample-cpu", &record.opts.sample_cpu, "Record the sample cpu"),
  1352. OPT_BOOLEAN_SET('T', "timestamp", &record.opts.sample_time,
  1353. &record.opts.sample_time_set,
  1354. "Record the sample timestamps"),
  1355. OPT_BOOLEAN_SET('P', "period", &record.opts.period, &record.opts.period_set,
  1356. "Record the sample period"),
  1357. OPT_BOOLEAN('n', "no-samples", &record.opts.no_samples,
  1358. "don't sample"),
  1359. OPT_BOOLEAN_SET('N', "no-buildid-cache", &record.no_buildid_cache,
  1360. &record.no_buildid_cache_set,
  1361. "do not update the buildid cache"),
  1362. OPT_BOOLEAN_SET('B', "no-buildid", &record.no_buildid,
  1363. &record.no_buildid_set,
  1364. "do not collect buildids in perf.data"),
  1365. OPT_CALLBACK('G', "cgroup", &record.evlist, "name",
  1366. "monitor event in cgroup name only",
  1367. parse_cgroups),
  1368. OPT_UINTEGER('D', "delay", &record.opts.initial_delay,
  1369. "ms to wait before starting measurement after program start"),
  1370. OPT_STRING('u', "uid", &record.opts.target.uid_str, "user",
  1371. "user to profile"),
  1372. OPT_CALLBACK_NOOPT('b', "branch-any", &record.opts.branch_stack,
  1373. "branch any", "sample any taken branches",
  1374. parse_branch_stack),
  1375. OPT_CALLBACK('j', "branch-filter", &record.opts.branch_stack,
  1376. "branch filter mask", "branch stack filter modes",
  1377. parse_branch_stack),
  1378. OPT_BOOLEAN('W', "weight", &record.opts.sample_weight,
  1379. "sample by weight (on special events only)"),
  1380. OPT_BOOLEAN(0, "transaction", &record.opts.sample_transaction,
  1381. "sample transaction flags (special events only)"),
  1382. OPT_BOOLEAN(0, "per-thread", &record.opts.target.per_thread,
  1383. "use per-thread mmaps"),
  1384. OPT_CALLBACK_OPTARG('I', "intr-regs", &record.opts.sample_intr_regs, NULL, "any register",
  1385. "sample selected machine registers on interrupt,"
  1386. " use -I ? to list register names", parse_regs),
  1387. OPT_CALLBACK_OPTARG(0, "user-regs", &record.opts.sample_user_regs, NULL, "any register",
  1388. "sample selected machine registers on interrupt,"
  1389. " use -I ? to list register names", parse_regs),
  1390. OPT_BOOLEAN(0, "running-time", &record.opts.running_time,
  1391. "Record running/enabled time of read (:S) events"),
  1392. OPT_CALLBACK('k', "clockid", &record.opts,
  1393. "clockid", "clockid to use for events, see clock_gettime()",
  1394. parse_clockid),
  1395. OPT_STRING_OPTARG('S', "snapshot", &record.opts.auxtrace_snapshot_opts,
  1396. "opts", "AUX area tracing Snapshot Mode", ""),
  1397. OPT_UINTEGER(0, "proc-map-timeout", &record.opts.proc_map_timeout,
  1398. "per thread proc mmap processing timeout in ms"),
  1399. OPT_BOOLEAN(0, "namespaces", &record.opts.record_namespaces,
  1400. "Record namespaces events"),
  1401. OPT_BOOLEAN(0, "switch-events", &record.opts.record_switch_events,
  1402. "Record context switch events"),
  1403. OPT_BOOLEAN_FLAG(0, "all-kernel", &record.opts.all_kernel,
  1404. "Configure all used events to run in kernel space.",
  1405. PARSE_OPT_EXCLUSIVE),
  1406. OPT_BOOLEAN_FLAG(0, "all-user", &record.opts.all_user,
  1407. "Configure all used events to run in user space.",
  1408. PARSE_OPT_EXCLUSIVE),
  1409. OPT_STRING(0, "clang-path", &llvm_param.clang_path, "clang path",
  1410. "clang binary to use for compiling BPF scriptlets"),
  1411. OPT_STRING(0, "clang-opt", &llvm_param.clang_opt, "clang options",
  1412. "options passed to clang when compiling BPF scriptlets"),
  1413. OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name,
  1414. "file", "vmlinux pathname"),
  1415. OPT_BOOLEAN(0, "buildid-all", &record.buildid_all,
  1416. "Record build-id of all DSOs regardless of hits"),
  1417. OPT_BOOLEAN(0, "timestamp-filename", &record.timestamp_filename,
  1418. "append timestamp to output filename"),
  1419. OPT_BOOLEAN(0, "timestamp-boundary", &record.timestamp_boundary,
  1420. "Record timestamp boundary (time of first/last samples)"),
  1421. OPT_STRING_OPTARG_SET(0, "switch-output", &record.switch_output.str,
  1422. &record.switch_output.set, "signal,size,time",
  1423. "Switch output when receive SIGUSR2 or cross size,time threshold",
  1424. "signal"),
  1425. OPT_BOOLEAN(0, "dry-run", &dry_run,
  1426. "Parse options then exit"),
  1427. OPT_END()
  1428. };
  1429. struct option *record_options = __record_options;
  1430. int cmd_record(int argc, const char **argv)
  1431. {
  1432. int err;
  1433. struct record *rec = &record;
  1434. char errbuf[BUFSIZ];
  1435. setlocale(LC_ALL, "");
  1436. #ifndef HAVE_LIBBPF_SUPPORT
  1437. # define set_nobuild(s, l, c) set_option_nobuild(record_options, s, l, "NO_LIBBPF=1", c)
  1438. set_nobuild('\0', "clang-path", true);
  1439. set_nobuild('\0', "clang-opt", true);
  1440. # undef set_nobuild
  1441. #endif
  1442. #ifndef HAVE_BPF_PROLOGUE
  1443. # if !defined (HAVE_DWARF_SUPPORT)
  1444. # define REASON "NO_DWARF=1"
  1445. # elif !defined (HAVE_LIBBPF_SUPPORT)
  1446. # define REASON "NO_LIBBPF=1"
  1447. # else
  1448. # define REASON "this architecture doesn't support BPF prologue"
  1449. # endif
  1450. # define set_nobuild(s, l, c) set_option_nobuild(record_options, s, l, REASON, c)
  1451. set_nobuild('\0', "vmlinux", true);
  1452. # undef set_nobuild
  1453. # undef REASON
  1454. #endif
  1455. rec->evlist = perf_evlist__new();
  1456. if (rec->evlist == NULL)
  1457. return -ENOMEM;
  1458. err = perf_config(perf_record_config, rec);
  1459. if (err)
  1460. return err;
  1461. argc = parse_options(argc, argv, record_options, record_usage,
  1462. PARSE_OPT_STOP_AT_NON_OPTION);
  1463. if (quiet)
  1464. perf_quiet_option();
  1465. /* Make system wide (-a) the default target. */
  1466. if (!argc && target__none(&rec->opts.target))
  1467. rec->opts.target.system_wide = true;
  1468. if (nr_cgroups && !rec->opts.target.system_wide) {
  1469. usage_with_options_msg(record_usage, record_options,
  1470. "cgroup monitoring only available in system-wide mode");
  1471. }
  1472. if (rec->opts.record_switch_events &&
  1473. !perf_can_record_switch_events()) {
  1474. ui__error("kernel does not support recording context switch events\n");
  1475. parse_options_usage(record_usage, record_options, "switch-events", 0);
  1476. return -EINVAL;
  1477. }
  1478. if (switch_output_setup(rec)) {
  1479. parse_options_usage(record_usage, record_options, "switch-output", 0);
  1480. return -EINVAL;
  1481. }
  1482. if (rec->switch_output.time) {
  1483. signal(SIGALRM, alarm_sig_handler);
  1484. alarm(rec->switch_output.time);
  1485. }
  1486. /*
  1487. * Allow aliases to facilitate the lookup of symbols for address
  1488. * filters. Refer to auxtrace_parse_filters().
  1489. */
  1490. symbol_conf.allow_aliases = true;
  1491. symbol__init(NULL);
  1492. err = record__auxtrace_init(rec);
  1493. if (err)
  1494. goto out;
  1495. if (dry_run)
  1496. goto out;
  1497. err = bpf__setup_stdout(rec->evlist);
  1498. if (err) {
  1499. bpf__strerror_setup_stdout(rec->evlist, err, errbuf, sizeof(errbuf));
  1500. pr_err("ERROR: Setup BPF stdout failed: %s\n",
  1501. errbuf);
  1502. goto out;
  1503. }
  1504. err = -ENOMEM;
  1505. if (symbol_conf.kptr_restrict && !perf_evlist__exclude_kernel(rec->evlist))
  1506. pr_warning(
  1507. "WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,\n"
  1508. "check /proc/sys/kernel/kptr_restrict.\n\n"
  1509. "Samples in kernel functions may not be resolved if a suitable vmlinux\n"
  1510. "file is not found in the buildid cache or in the vmlinux path.\n\n"
  1511. "Samples in kernel modules won't be resolved at all.\n\n"
  1512. "If some relocation was applied (e.g. kexec) symbols may be misresolved\n"
  1513. "even with a suitable vmlinux or kallsyms file.\n\n");
  1514. if (rec->no_buildid_cache || rec->no_buildid) {
  1515. disable_buildid_cache();
  1516. } else if (rec->switch_output.enabled) {
  1517. /*
  1518. * In 'perf record --switch-output', disable buildid
  1519. * generation by default to reduce data file switching
  1520. * overhead. Still generate buildid if they are required
  1521. * explicitly using
  1522. *
  1523. * perf record --switch-output --no-no-buildid \
  1524. * --no-no-buildid-cache
  1525. *
  1526. * Following code equals to:
  1527. *
  1528. * if ((rec->no_buildid || !rec->no_buildid_set) &&
  1529. * (rec->no_buildid_cache || !rec->no_buildid_cache_set))
  1530. * disable_buildid_cache();
  1531. */
  1532. bool disable = true;
  1533. if (rec->no_buildid_set && !rec->no_buildid)
  1534. disable = false;
  1535. if (rec->no_buildid_cache_set && !rec->no_buildid_cache)
  1536. disable = false;
  1537. if (disable) {
  1538. rec->no_buildid = true;
  1539. rec->no_buildid_cache = true;
  1540. disable_buildid_cache();
  1541. }
  1542. }
  1543. if (record.opts.overwrite)
  1544. record.opts.tail_synthesize = true;
  1545. if (rec->evlist->nr_entries == 0 &&
  1546. __perf_evlist__add_default(rec->evlist, !record.opts.no_samples) < 0) {
  1547. pr_err("Not enough memory for event selector list\n");
  1548. goto out;
  1549. }
  1550. if (rec->opts.target.tid && !rec->opts.no_inherit_set)
  1551. rec->opts.no_inherit = true;
  1552. err = target__validate(&rec->opts.target);
  1553. if (err) {
  1554. target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
  1555. ui__warning("%s\n", errbuf);
  1556. }
  1557. err = target__parse_uid(&rec->opts.target);
  1558. if (err) {
  1559. int saved_errno = errno;
  1560. target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
  1561. ui__error("%s", errbuf);
  1562. err = -saved_errno;
  1563. goto out;
  1564. }
  1565. /* Enable ignoring missing threads when -u/-p option is defined. */
  1566. rec->opts.ignore_missing_thread = rec->opts.target.uid != UINT_MAX || rec->opts.target.pid;
  1567. err = -ENOMEM;
  1568. if (perf_evlist__create_maps(rec->evlist, &rec->opts.target) < 0)
  1569. usage_with_options(record_usage, record_options);
  1570. err = auxtrace_record__options(rec->itr, rec->evlist, &rec->opts);
  1571. if (err)
  1572. goto out;
  1573. /*
  1574. * We take all buildids when the file contains
  1575. * AUX area tracing data because we do not decode the
  1576. * trace because it would take too long.
  1577. */
  1578. if (rec->opts.full_auxtrace)
  1579. rec->buildid_all = true;
  1580. if (record_opts__config(&rec->opts)) {
  1581. err = -EINVAL;
  1582. goto out;
  1583. }
  1584. err = __cmd_record(&record, argc, argv);
  1585. out:
  1586. perf_evlist__delete(rec->evlist);
  1587. symbol__exit();
  1588. auxtrace_record__free(rec->itr);
  1589. return err;
  1590. }
  1591. static void snapshot_sig_handler(int sig __maybe_unused)
  1592. {
  1593. struct record *rec = &record;
  1594. if (trigger_is_ready(&auxtrace_snapshot_trigger)) {
  1595. trigger_hit(&auxtrace_snapshot_trigger);
  1596. auxtrace_record__snapshot_started = 1;
  1597. if (auxtrace_record__snapshot_start(record.itr))
  1598. trigger_error(&auxtrace_snapshot_trigger);
  1599. }
  1600. if (switch_output_signal(rec))
  1601. trigger_hit(&switch_output_trigger);
  1602. }
  1603. static void alarm_sig_handler(int sig __maybe_unused)
  1604. {
  1605. struct record *rec = &record;
  1606. if (switch_output_time(rec))
  1607. trigger_hit(&switch_output_trigger);
  1608. }