builtin-record.c 49 KB

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