builtin-record.c 49 KB

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