builtin-record.c 50 KB

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