builtin-stat.c 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * builtin-stat.c
  4. *
  5. * Builtin stat command: Give a precise performance counters summary
  6. * overview about any workload, CPU or specific PID.
  7. *
  8. * Sample output:
  9. $ perf stat ./hackbench 10
  10. Time: 0.118
  11. Performance counter stats for './hackbench 10':
  12. 1708.761321 task-clock # 11.037 CPUs utilized
  13. 41,190 context-switches # 0.024 M/sec
  14. 6,735 CPU-migrations # 0.004 M/sec
  15. 17,318 page-faults # 0.010 M/sec
  16. 5,205,202,243 cycles # 3.046 GHz
  17. 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
  18. 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
  19. 2,603,501,247 instructions # 0.50 insns per cycle
  20. # 1.48 stalled cycles per insn
  21. 484,357,498 branches # 283.455 M/sec
  22. 6,388,934 branch-misses # 1.32% of all branches
  23. 0.154822978 seconds time elapsed
  24. *
  25. * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <[email protected]>
  26. *
  27. * Improvements and fixes by:
  28. *
  29. * Arjan van de Ven <[email protected]>
  30. * Yanmin Zhang <[email protected]>
  31. * Wu Fengguang <[email protected]>
  32. * Mike Galbraith <[email protected]>
  33. * Paul Mackerras <[email protected]>
  34. * Jaswinder Singh Rajput <[email protected]>
  35. */
  36. #include "builtin.h"
  37. #include "perf.h"
  38. #include "util/cgroup.h"
  39. #include <subcmd/parse-options.h>
  40. #include "util/parse-events.h"
  41. #include "util/pmu.h"
  42. #include "util/event.h"
  43. #include "util/evlist.h"
  44. #include "util/evlist-hybrid.h"
  45. #include "util/evsel.h"
  46. #include "util/debug.h"
  47. #include "util/color.h"
  48. #include "util/stat.h"
  49. #include "util/header.h"
  50. #include "util/cpumap.h"
  51. #include "util/thread_map.h"
  52. #include "util/counts.h"
  53. #include "util/topdown.h"
  54. #include "util/session.h"
  55. #include "util/tool.h"
  56. #include "util/string2.h"
  57. #include "util/metricgroup.h"
  58. #include "util/synthetic-events.h"
  59. #include "util/target.h"
  60. #include "util/time-utils.h"
  61. #include "util/top.h"
  62. #include "util/affinity.h"
  63. #include "util/pfm.h"
  64. #include "util/bpf_counter.h"
  65. #include "util/iostat.h"
  66. #include "util/pmu-hybrid.h"
  67. #include "asm/bug.h"
  68. #include <linux/time64.h>
  69. #include <linux/zalloc.h>
  70. #include <api/fs/fs.h>
  71. #include <errno.h>
  72. #include <signal.h>
  73. #include <stdlib.h>
  74. #include <sys/prctl.h>
  75. #include <inttypes.h>
  76. #include <locale.h>
  77. #include <math.h>
  78. #include <sys/types.h>
  79. #include <sys/stat.h>
  80. #include <sys/wait.h>
  81. #include <unistd.h>
  82. #include <sys/time.h>
  83. #include <sys/resource.h>
  84. #include <linux/err.h>
  85. #include <linux/ctype.h>
  86. #include <perf/evlist.h>
  87. #define DEFAULT_SEPARATOR " "
  88. #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
  89. static void print_counters(struct timespec *ts, int argc, const char **argv);
  90. /* Default events used for perf stat -T */
  91. static const char *transaction_attrs = {
  92. "task-clock,"
  93. "{"
  94. "instructions,"
  95. "cycles,"
  96. "cpu/cycles-t/,"
  97. "cpu/tx-start/,"
  98. "cpu/el-start/,"
  99. "cpu/cycles-ct/"
  100. "}"
  101. };
  102. /* More limited version when the CPU does not have all events. */
  103. static const char * transaction_limited_attrs = {
  104. "task-clock,"
  105. "{"
  106. "instructions,"
  107. "cycles,"
  108. "cpu/cycles-t/,"
  109. "cpu/tx-start/"
  110. "}"
  111. };
  112. static const char * topdown_attrs[] = {
  113. "topdown-total-slots",
  114. "topdown-slots-retired",
  115. "topdown-recovery-bubbles",
  116. "topdown-fetch-bubbles",
  117. "topdown-slots-issued",
  118. NULL,
  119. };
  120. static const char *topdown_metric_attrs[] = {
  121. "slots",
  122. "topdown-retiring",
  123. "topdown-bad-spec",
  124. "topdown-fe-bound",
  125. "topdown-be-bound",
  126. NULL,
  127. };
  128. static const char *topdown_metric_L2_attrs[] = {
  129. "slots",
  130. "topdown-retiring",
  131. "topdown-bad-spec",
  132. "topdown-fe-bound",
  133. "topdown-be-bound",
  134. "topdown-heavy-ops",
  135. "topdown-br-mispredict",
  136. "topdown-fetch-lat",
  137. "topdown-mem-bound",
  138. NULL,
  139. };
  140. #define TOPDOWN_MAX_LEVEL 2
  141. static const char *smi_cost_attrs = {
  142. "{"
  143. "msr/aperf/,"
  144. "msr/smi/,"
  145. "cycles"
  146. "}"
  147. };
  148. static struct evlist *evsel_list;
  149. static bool all_counters_use_bpf = true;
  150. static struct target target = {
  151. .uid = UINT_MAX,
  152. };
  153. #define METRIC_ONLY_LEN 20
  154. static volatile pid_t child_pid = -1;
  155. static int detailed_run = 0;
  156. static bool transaction_run;
  157. static bool topdown_run = false;
  158. static bool smi_cost = false;
  159. static bool smi_reset = false;
  160. static int big_num_opt = -1;
  161. static bool group = false;
  162. static const char *pre_cmd = NULL;
  163. static const char *post_cmd = NULL;
  164. static bool sync_run = false;
  165. static bool forever = false;
  166. static bool force_metric_only = false;
  167. static struct timespec ref_time;
  168. static bool append_file;
  169. static bool interval_count;
  170. static const char *output_name;
  171. static int output_fd;
  172. static char *metrics;
  173. struct perf_stat {
  174. bool record;
  175. struct perf_data data;
  176. struct perf_session *session;
  177. u64 bytes_written;
  178. struct perf_tool tool;
  179. bool maps_allocated;
  180. struct perf_cpu_map *cpus;
  181. struct perf_thread_map *threads;
  182. enum aggr_mode aggr_mode;
  183. };
  184. static struct perf_stat perf_stat;
  185. #define STAT_RECORD perf_stat.record
  186. static volatile int done = 0;
  187. static struct perf_stat_config stat_config = {
  188. .aggr_mode = AGGR_GLOBAL,
  189. .scale = true,
  190. .unit_width = 4, /* strlen("unit") */
  191. .run_count = 1,
  192. .metric_only_len = METRIC_ONLY_LEN,
  193. .walltime_nsecs_stats = &walltime_nsecs_stats,
  194. .ru_stats = &ru_stats,
  195. .big_num = true,
  196. .ctl_fd = -1,
  197. .ctl_fd_ack = -1,
  198. .iostat_run = false,
  199. };
  200. static bool cpus_map_matched(struct evsel *a, struct evsel *b)
  201. {
  202. if (!a->core.cpus && !b->core.cpus)
  203. return true;
  204. if (!a->core.cpus || !b->core.cpus)
  205. return false;
  206. if (perf_cpu_map__nr(a->core.cpus) != perf_cpu_map__nr(b->core.cpus))
  207. return false;
  208. for (int i = 0; i < perf_cpu_map__nr(a->core.cpus); i++) {
  209. if (perf_cpu_map__cpu(a->core.cpus, i).cpu !=
  210. perf_cpu_map__cpu(b->core.cpus, i).cpu)
  211. return false;
  212. }
  213. return true;
  214. }
  215. static void evlist__check_cpu_maps(struct evlist *evlist)
  216. {
  217. struct evsel *evsel, *pos, *leader;
  218. char buf[1024];
  219. if (evlist__has_hybrid(evlist))
  220. evlist__warn_hybrid_group(evlist);
  221. evlist__for_each_entry(evlist, evsel) {
  222. leader = evsel__leader(evsel);
  223. /* Check that leader matches cpus with each member. */
  224. if (leader == evsel)
  225. continue;
  226. if (cpus_map_matched(leader, evsel))
  227. continue;
  228. /* If there's mismatch disable the group and warn user. */
  229. WARN_ONCE(1, "WARNING: grouped events cpus do not match, disabling group:\n");
  230. evsel__group_desc(leader, buf, sizeof(buf));
  231. pr_warning(" %s\n", buf);
  232. if (verbose) {
  233. cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
  234. pr_warning(" %s: %s\n", leader->name, buf);
  235. cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
  236. pr_warning(" %s: %s\n", evsel->name, buf);
  237. }
  238. for_each_group_evsel(pos, leader)
  239. evsel__remove_from_group(pos, leader);
  240. }
  241. }
  242. static inline void diff_timespec(struct timespec *r, struct timespec *a,
  243. struct timespec *b)
  244. {
  245. r->tv_sec = a->tv_sec - b->tv_sec;
  246. if (a->tv_nsec < b->tv_nsec) {
  247. r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
  248. r->tv_sec--;
  249. } else {
  250. r->tv_nsec = a->tv_nsec - b->tv_nsec ;
  251. }
  252. }
  253. static void perf_stat__reset_stats(void)
  254. {
  255. evlist__reset_stats(evsel_list);
  256. perf_stat__reset_shadow_stats();
  257. }
  258. static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
  259. union perf_event *event,
  260. struct perf_sample *sample __maybe_unused,
  261. struct machine *machine __maybe_unused)
  262. {
  263. if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
  264. pr_err("failed to write perf data, error: %m\n");
  265. return -1;
  266. }
  267. perf_stat.bytes_written += event->header.size;
  268. return 0;
  269. }
  270. static int write_stat_round_event(u64 tm, u64 type)
  271. {
  272. return perf_event__synthesize_stat_round(NULL, tm, type,
  273. process_synthesized_event,
  274. NULL);
  275. }
  276. #define WRITE_STAT_ROUND_EVENT(time, interval) \
  277. write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
  278. #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
  279. static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
  280. struct perf_counts_values *count)
  281. {
  282. struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
  283. struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
  284. return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
  285. process_synthesized_event, NULL);
  286. }
  287. static int read_single_counter(struct evsel *counter, int cpu_map_idx,
  288. int thread, struct timespec *rs)
  289. {
  290. switch(counter->tool_event) {
  291. case PERF_TOOL_DURATION_TIME: {
  292. u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
  293. struct perf_counts_values *count =
  294. perf_counts(counter->counts, cpu_map_idx, thread);
  295. count->ena = count->run = val;
  296. count->val = val;
  297. return 0;
  298. }
  299. case PERF_TOOL_USER_TIME:
  300. case PERF_TOOL_SYSTEM_TIME: {
  301. u64 val;
  302. struct perf_counts_values *count =
  303. perf_counts(counter->counts, cpu_map_idx, thread);
  304. if (counter->tool_event == PERF_TOOL_USER_TIME)
  305. val = ru_stats.ru_utime_usec_stat.mean;
  306. else
  307. val = ru_stats.ru_stime_usec_stat.mean;
  308. count->ena = count->run = val;
  309. count->val = val;
  310. return 0;
  311. }
  312. default:
  313. case PERF_TOOL_NONE:
  314. return evsel__read_counter(counter, cpu_map_idx, thread);
  315. case PERF_TOOL_MAX:
  316. /* This should never be reached */
  317. return 0;
  318. }
  319. }
  320. /*
  321. * Read out the results of a single counter:
  322. * do not aggregate counts across CPUs in system-wide mode
  323. */
  324. static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu_map_idx)
  325. {
  326. int nthreads = perf_thread_map__nr(evsel_list->core.threads);
  327. int thread;
  328. if (!counter->supported)
  329. return -ENOENT;
  330. for (thread = 0; thread < nthreads; thread++) {
  331. struct perf_counts_values *count;
  332. count = perf_counts(counter->counts, cpu_map_idx, thread);
  333. /*
  334. * The leader's group read loads data into its group members
  335. * (via evsel__read_counter()) and sets their count->loaded.
  336. */
  337. if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
  338. read_single_counter(counter, cpu_map_idx, thread, rs)) {
  339. counter->counts->scaled = -1;
  340. perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
  341. perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
  342. return -1;
  343. }
  344. perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
  345. if (STAT_RECORD) {
  346. if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
  347. pr_err("failed to write stat event\n");
  348. return -1;
  349. }
  350. }
  351. if (verbose > 1) {
  352. fprintf(stat_config.output,
  353. "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  354. evsel__name(counter),
  355. perf_cpu_map__cpu(evsel__cpus(counter),
  356. cpu_map_idx).cpu,
  357. count->val, count->ena, count->run);
  358. }
  359. }
  360. return 0;
  361. }
  362. static int read_affinity_counters(struct timespec *rs)
  363. {
  364. struct evlist_cpu_iterator evlist_cpu_itr;
  365. struct affinity saved_affinity, *affinity;
  366. if (all_counters_use_bpf)
  367. return 0;
  368. if (!target__has_cpu(&target) || target__has_per_thread(&target))
  369. affinity = NULL;
  370. else if (affinity__setup(&saved_affinity) < 0)
  371. return -1;
  372. else
  373. affinity = &saved_affinity;
  374. evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
  375. struct evsel *counter = evlist_cpu_itr.evsel;
  376. if (evsel__is_bpf(counter))
  377. continue;
  378. if (!counter->err) {
  379. counter->err = read_counter_cpu(counter, rs,
  380. evlist_cpu_itr.cpu_map_idx);
  381. }
  382. }
  383. if (affinity)
  384. affinity__cleanup(&saved_affinity);
  385. return 0;
  386. }
  387. static int read_bpf_map_counters(void)
  388. {
  389. struct evsel *counter;
  390. int err;
  391. evlist__for_each_entry(evsel_list, counter) {
  392. if (!evsel__is_bpf(counter))
  393. continue;
  394. err = bpf_counter__read(counter);
  395. if (err)
  396. return err;
  397. }
  398. return 0;
  399. }
  400. static void read_counters(struct timespec *rs)
  401. {
  402. struct evsel *counter;
  403. if (!stat_config.stop_read_counter) {
  404. if (read_bpf_map_counters() ||
  405. read_affinity_counters(rs))
  406. return;
  407. }
  408. evlist__for_each_entry(evsel_list, counter) {
  409. if (counter->err)
  410. pr_debug("failed to read counter %s\n", counter->name);
  411. if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
  412. pr_warning("failed to process counter %s\n", counter->name);
  413. counter->err = 0;
  414. }
  415. }
  416. static void process_interval(void)
  417. {
  418. struct timespec ts, rs;
  419. clock_gettime(CLOCK_MONOTONIC, &ts);
  420. diff_timespec(&rs, &ts, &ref_time);
  421. perf_stat__reset_shadow_per_stat(&rt_stat);
  422. read_counters(&rs);
  423. if (STAT_RECORD) {
  424. if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
  425. pr_err("failed to write stat round event\n");
  426. }
  427. init_stats(&walltime_nsecs_stats);
  428. update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
  429. print_counters(&rs, 0, NULL);
  430. }
  431. static bool handle_interval(unsigned int interval, int *times)
  432. {
  433. if (interval) {
  434. process_interval();
  435. if (interval_count && !(--(*times)))
  436. return true;
  437. }
  438. return false;
  439. }
  440. static int enable_counters(void)
  441. {
  442. struct evsel *evsel;
  443. int err;
  444. evlist__for_each_entry(evsel_list, evsel) {
  445. if (!evsel__is_bpf(evsel))
  446. continue;
  447. err = bpf_counter__enable(evsel);
  448. if (err)
  449. return err;
  450. }
  451. if (!target__enable_on_exec(&target)) {
  452. if (!all_counters_use_bpf)
  453. evlist__enable(evsel_list);
  454. }
  455. return 0;
  456. }
  457. static void disable_counters(void)
  458. {
  459. struct evsel *counter;
  460. /*
  461. * If we don't have tracee (attaching to task or cpu), counters may
  462. * still be running. To get accurate group ratios, we must stop groups
  463. * from counting before reading their constituent counters.
  464. */
  465. if (!target__none(&target)) {
  466. evlist__for_each_entry(evsel_list, counter)
  467. bpf_counter__disable(counter);
  468. if (!all_counters_use_bpf)
  469. evlist__disable(evsel_list);
  470. }
  471. }
  472. static volatile int workload_exec_errno;
  473. /*
  474. * evlist__prepare_workload will send a SIGUSR1
  475. * if the fork fails, since we asked by setting its
  476. * want_signal to true.
  477. */
  478. static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
  479. void *ucontext __maybe_unused)
  480. {
  481. workload_exec_errno = info->si_value.sival_int;
  482. }
  483. static bool evsel__should_store_id(struct evsel *counter)
  484. {
  485. return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
  486. }
  487. static bool is_target_alive(struct target *_target,
  488. struct perf_thread_map *threads)
  489. {
  490. struct stat st;
  491. int i;
  492. if (!target__has_task(_target))
  493. return true;
  494. for (i = 0; i < threads->nr; i++) {
  495. char path[PATH_MAX];
  496. scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
  497. threads->map[i].pid);
  498. if (!stat(path, &st))
  499. return true;
  500. }
  501. return false;
  502. }
  503. static void process_evlist(struct evlist *evlist, unsigned int interval)
  504. {
  505. enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
  506. if (evlist__ctlfd_process(evlist, &cmd) > 0) {
  507. switch (cmd) {
  508. case EVLIST_CTL_CMD_ENABLE:
  509. __fallthrough;
  510. case EVLIST_CTL_CMD_DISABLE:
  511. if (interval)
  512. process_interval();
  513. break;
  514. case EVLIST_CTL_CMD_SNAPSHOT:
  515. case EVLIST_CTL_CMD_ACK:
  516. case EVLIST_CTL_CMD_UNSUPPORTED:
  517. case EVLIST_CTL_CMD_EVLIST:
  518. case EVLIST_CTL_CMD_STOP:
  519. case EVLIST_CTL_CMD_PING:
  520. default:
  521. break;
  522. }
  523. }
  524. }
  525. static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
  526. int *time_to_sleep)
  527. {
  528. int tts = *time_to_sleep;
  529. struct timespec time_diff;
  530. diff_timespec(&time_diff, time_stop, time_start);
  531. tts -= time_diff.tv_sec * MSEC_PER_SEC +
  532. time_diff.tv_nsec / NSEC_PER_MSEC;
  533. if (tts < 0)
  534. tts = 0;
  535. *time_to_sleep = tts;
  536. }
  537. static int dispatch_events(bool forks, int timeout, int interval, int *times)
  538. {
  539. int child_exited = 0, status = 0;
  540. int time_to_sleep, sleep_time;
  541. struct timespec time_start, time_stop;
  542. if (interval)
  543. sleep_time = interval;
  544. else if (timeout)
  545. sleep_time = timeout;
  546. else
  547. sleep_time = 1000;
  548. time_to_sleep = sleep_time;
  549. while (!done) {
  550. if (forks)
  551. child_exited = waitpid(child_pid, &status, WNOHANG);
  552. else
  553. child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
  554. if (child_exited)
  555. break;
  556. clock_gettime(CLOCK_MONOTONIC, &time_start);
  557. if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
  558. if (timeout || handle_interval(interval, times))
  559. break;
  560. time_to_sleep = sleep_time;
  561. } else { /* fd revent */
  562. process_evlist(evsel_list, interval);
  563. clock_gettime(CLOCK_MONOTONIC, &time_stop);
  564. compute_tts(&time_start, &time_stop, &time_to_sleep);
  565. }
  566. }
  567. return status;
  568. }
  569. enum counter_recovery {
  570. COUNTER_SKIP,
  571. COUNTER_RETRY,
  572. COUNTER_FATAL,
  573. };
  574. static enum counter_recovery stat_handle_error(struct evsel *counter)
  575. {
  576. char msg[BUFSIZ];
  577. /*
  578. * PPC returns ENXIO for HW counters until 2.6.37
  579. * (behavior changed with commit b0a873e).
  580. */
  581. if (errno == EINVAL || errno == ENOSYS ||
  582. errno == ENOENT || errno == EOPNOTSUPP ||
  583. errno == ENXIO) {
  584. if (verbose > 0)
  585. ui__warning("%s event is not supported by the kernel.\n",
  586. evsel__name(counter));
  587. counter->supported = false;
  588. /*
  589. * errored is a sticky flag that means one of the counter's
  590. * cpu event had a problem and needs to be reexamined.
  591. */
  592. counter->errored = true;
  593. if ((evsel__leader(counter) != counter) ||
  594. !(counter->core.leader->nr_members > 1))
  595. return COUNTER_SKIP;
  596. } else if (evsel__fallback(counter, errno, msg, sizeof(msg))) {
  597. if (verbose > 0)
  598. ui__warning("%s\n", msg);
  599. return COUNTER_RETRY;
  600. } else if (target__has_per_thread(&target) &&
  601. evsel_list->core.threads &&
  602. evsel_list->core.threads->err_thread != -1) {
  603. /*
  604. * For global --per-thread case, skip current
  605. * error thread.
  606. */
  607. if (!thread_map__remove(evsel_list->core.threads,
  608. evsel_list->core.threads->err_thread)) {
  609. evsel_list->core.threads->err_thread = -1;
  610. return COUNTER_RETRY;
  611. }
  612. }
  613. evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
  614. ui__error("%s\n", msg);
  615. if (child_pid != -1)
  616. kill(child_pid, SIGTERM);
  617. return COUNTER_FATAL;
  618. }
  619. static int __run_perf_stat(int argc, const char **argv, int run_idx)
  620. {
  621. int interval = stat_config.interval;
  622. int times = stat_config.times;
  623. int timeout = stat_config.timeout;
  624. char msg[BUFSIZ];
  625. unsigned long long t0, t1;
  626. struct evsel *counter;
  627. size_t l;
  628. int status = 0;
  629. const bool forks = (argc > 0);
  630. bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
  631. struct evlist_cpu_iterator evlist_cpu_itr;
  632. struct affinity saved_affinity, *affinity = NULL;
  633. int err;
  634. bool second_pass = false;
  635. if (forks) {
  636. if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
  637. perror("failed to prepare workload");
  638. return -1;
  639. }
  640. child_pid = evsel_list->workload.pid;
  641. }
  642. if (group)
  643. evlist__set_leader(evsel_list);
  644. if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
  645. if (affinity__setup(&saved_affinity) < 0)
  646. return -1;
  647. affinity = &saved_affinity;
  648. }
  649. evlist__for_each_entry(evsel_list, counter) {
  650. counter->reset_group = false;
  651. if (bpf_counter__load(counter, &target))
  652. return -1;
  653. if (!(evsel__is_bperf(counter)))
  654. all_counters_use_bpf = false;
  655. }
  656. evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
  657. counter = evlist_cpu_itr.evsel;
  658. /*
  659. * bperf calls evsel__open_per_cpu() in bperf__load(), so
  660. * no need to call it again here.
  661. */
  662. if (target.use_bpf)
  663. break;
  664. if (counter->reset_group || counter->errored)
  665. continue;
  666. if (evsel__is_bperf(counter))
  667. continue;
  668. try_again:
  669. if (create_perf_stat_counter(counter, &stat_config, &target,
  670. evlist_cpu_itr.cpu_map_idx) < 0) {
  671. /*
  672. * Weak group failed. We cannot just undo this here
  673. * because earlier CPUs might be in group mode, and the kernel
  674. * doesn't support mixing group and non group reads. Defer
  675. * it to later.
  676. * Don't close here because we're in the wrong affinity.
  677. */
  678. if ((errno == EINVAL || errno == EBADF) &&
  679. evsel__leader(counter) != counter &&
  680. counter->weak_group) {
  681. evlist__reset_weak_group(evsel_list, counter, false);
  682. assert(counter->reset_group);
  683. second_pass = true;
  684. continue;
  685. }
  686. switch (stat_handle_error(counter)) {
  687. case COUNTER_FATAL:
  688. return -1;
  689. case COUNTER_RETRY:
  690. goto try_again;
  691. case COUNTER_SKIP:
  692. continue;
  693. default:
  694. break;
  695. }
  696. }
  697. counter->supported = true;
  698. }
  699. if (second_pass) {
  700. /*
  701. * Now redo all the weak group after closing them,
  702. * and also close errored counters.
  703. */
  704. /* First close errored or weak retry */
  705. evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
  706. counter = evlist_cpu_itr.evsel;
  707. if (!counter->reset_group && !counter->errored)
  708. continue;
  709. perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
  710. }
  711. /* Now reopen weak */
  712. evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
  713. counter = evlist_cpu_itr.evsel;
  714. if (!counter->reset_group)
  715. continue;
  716. try_again_reset:
  717. pr_debug2("reopening weak %s\n", evsel__name(counter));
  718. if (create_perf_stat_counter(counter, &stat_config, &target,
  719. evlist_cpu_itr.cpu_map_idx) < 0) {
  720. switch (stat_handle_error(counter)) {
  721. case COUNTER_FATAL:
  722. return -1;
  723. case COUNTER_RETRY:
  724. goto try_again_reset;
  725. case COUNTER_SKIP:
  726. continue;
  727. default:
  728. break;
  729. }
  730. }
  731. counter->supported = true;
  732. }
  733. }
  734. affinity__cleanup(affinity);
  735. evlist__for_each_entry(evsel_list, counter) {
  736. if (!counter->supported) {
  737. perf_evsel__free_fd(&counter->core);
  738. continue;
  739. }
  740. l = strlen(counter->unit);
  741. if (l > stat_config.unit_width)
  742. stat_config.unit_width = l;
  743. if (evsel__should_store_id(counter) &&
  744. evsel__store_ids(counter, evsel_list))
  745. return -1;
  746. }
  747. if (evlist__apply_filters(evsel_list, &counter)) {
  748. pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
  749. counter->filter, evsel__name(counter), errno,
  750. str_error_r(errno, msg, sizeof(msg)));
  751. return -1;
  752. }
  753. if (STAT_RECORD) {
  754. int fd = perf_data__fd(&perf_stat.data);
  755. if (is_pipe) {
  756. err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
  757. } else {
  758. err = perf_session__write_header(perf_stat.session, evsel_list,
  759. fd, false);
  760. }
  761. if (err < 0)
  762. return err;
  763. err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
  764. process_synthesized_event, is_pipe);
  765. if (err < 0)
  766. return err;
  767. }
  768. if (target.initial_delay) {
  769. pr_info(EVLIST_DISABLED_MSG);
  770. } else {
  771. err = enable_counters();
  772. if (err)
  773. return -1;
  774. }
  775. /* Exec the command, if any */
  776. if (forks)
  777. evlist__start_workload(evsel_list);
  778. if (target.initial_delay > 0) {
  779. usleep(target.initial_delay * USEC_PER_MSEC);
  780. err = enable_counters();
  781. if (err)
  782. return -1;
  783. pr_info(EVLIST_ENABLED_MSG);
  784. }
  785. t0 = rdclock();
  786. clock_gettime(CLOCK_MONOTONIC, &ref_time);
  787. if (forks) {
  788. if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
  789. status = dispatch_events(forks, timeout, interval, &times);
  790. if (child_pid != -1) {
  791. if (timeout)
  792. kill(child_pid, SIGTERM);
  793. wait4(child_pid, &status, 0, &stat_config.ru_data);
  794. }
  795. if (workload_exec_errno) {
  796. const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
  797. pr_err("Workload failed: %s\n", emsg);
  798. return -1;
  799. }
  800. if (WIFSIGNALED(status))
  801. psignal(WTERMSIG(status), argv[0]);
  802. } else {
  803. status = dispatch_events(forks, timeout, interval, &times);
  804. }
  805. disable_counters();
  806. t1 = rdclock();
  807. if (stat_config.walltime_run_table)
  808. stat_config.walltime_run[run_idx] = t1 - t0;
  809. if (interval && stat_config.summary) {
  810. stat_config.interval = 0;
  811. stat_config.stop_read_counter = true;
  812. init_stats(&walltime_nsecs_stats);
  813. update_stats(&walltime_nsecs_stats, t1 - t0);
  814. if (stat_config.aggr_mode == AGGR_GLOBAL)
  815. evlist__save_aggr_prev_raw_counts(evsel_list);
  816. evlist__copy_prev_raw_counts(evsel_list);
  817. evlist__reset_prev_raw_counts(evsel_list);
  818. perf_stat__reset_shadow_per_stat(&rt_stat);
  819. } else {
  820. update_stats(&walltime_nsecs_stats, t1 - t0);
  821. update_rusage_stats(&ru_stats, &stat_config.ru_data);
  822. }
  823. /*
  824. * Closing a group leader splits the group, and as we only disable
  825. * group leaders, results in remaining events becoming enabled. To
  826. * avoid arbitrary skew, we must read all counters before closing any
  827. * group leaders.
  828. */
  829. read_counters(&(struct timespec) { .tv_nsec = t1-t0 });
  830. /*
  831. * We need to keep evsel_list alive, because it's processed
  832. * later the evsel_list will be closed after.
  833. */
  834. if (!STAT_RECORD)
  835. evlist__close(evsel_list);
  836. return WEXITSTATUS(status);
  837. }
  838. static int run_perf_stat(int argc, const char **argv, int run_idx)
  839. {
  840. int ret;
  841. if (pre_cmd) {
  842. ret = system(pre_cmd);
  843. if (ret)
  844. return ret;
  845. }
  846. if (sync_run)
  847. sync();
  848. ret = __run_perf_stat(argc, argv, run_idx);
  849. if (ret)
  850. return ret;
  851. if (post_cmd) {
  852. ret = system(post_cmd);
  853. if (ret)
  854. return ret;
  855. }
  856. return ret;
  857. }
  858. static void print_counters(struct timespec *ts, int argc, const char **argv)
  859. {
  860. /* Do not print anything if we record to the pipe. */
  861. if (STAT_RECORD && perf_stat.data.is_pipe)
  862. return;
  863. if (quiet)
  864. return;
  865. evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
  866. }
  867. static volatile int signr = -1;
  868. static void skip_signal(int signo)
  869. {
  870. if ((child_pid == -1) || stat_config.interval)
  871. done = 1;
  872. signr = signo;
  873. /*
  874. * render child_pid harmless
  875. * won't send SIGTERM to a random
  876. * process in case of race condition
  877. * and fast PID recycling
  878. */
  879. child_pid = -1;
  880. }
  881. static void sig_atexit(void)
  882. {
  883. sigset_t set, oset;
  884. /*
  885. * avoid race condition with SIGCHLD handler
  886. * in skip_signal() which is modifying child_pid
  887. * goal is to avoid send SIGTERM to a random
  888. * process
  889. */
  890. sigemptyset(&set);
  891. sigaddset(&set, SIGCHLD);
  892. sigprocmask(SIG_BLOCK, &set, &oset);
  893. if (child_pid != -1)
  894. kill(child_pid, SIGTERM);
  895. sigprocmask(SIG_SETMASK, &oset, NULL);
  896. if (signr == -1)
  897. return;
  898. signal(signr, SIG_DFL);
  899. kill(getpid(), signr);
  900. }
  901. void perf_stat__set_big_num(int set)
  902. {
  903. stat_config.big_num = (set != 0);
  904. }
  905. void perf_stat__set_no_csv_summary(int set)
  906. {
  907. stat_config.no_csv_summary = (set != 0);
  908. }
  909. static int stat__set_big_num(const struct option *opt __maybe_unused,
  910. const char *s __maybe_unused, int unset)
  911. {
  912. big_num_opt = unset ? 0 : 1;
  913. perf_stat__set_big_num(!unset);
  914. return 0;
  915. }
  916. static int enable_metric_only(const struct option *opt __maybe_unused,
  917. const char *s __maybe_unused, int unset)
  918. {
  919. force_metric_only = true;
  920. stat_config.metric_only = !unset;
  921. return 0;
  922. }
  923. static int append_metric_groups(const struct option *opt __maybe_unused,
  924. const char *str,
  925. int unset __maybe_unused)
  926. {
  927. if (metrics) {
  928. char *tmp;
  929. if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
  930. return -ENOMEM;
  931. free(metrics);
  932. metrics = tmp;
  933. } else {
  934. metrics = strdup(str);
  935. if (!metrics)
  936. return -ENOMEM;
  937. }
  938. return 0;
  939. }
  940. static int parse_control_option(const struct option *opt,
  941. const char *str,
  942. int unset __maybe_unused)
  943. {
  944. struct perf_stat_config *config = opt->value;
  945. return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
  946. }
  947. static int parse_stat_cgroups(const struct option *opt,
  948. const char *str, int unset)
  949. {
  950. if (stat_config.cgroup_list) {
  951. pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
  952. return -1;
  953. }
  954. return parse_cgroups(opt, str, unset);
  955. }
  956. static int parse_hybrid_type(const struct option *opt,
  957. const char *str,
  958. int unset __maybe_unused)
  959. {
  960. struct evlist *evlist = *(struct evlist **)opt->value;
  961. if (!list_empty(&evlist->core.entries)) {
  962. fprintf(stderr, "Must define cputype before events/metrics\n");
  963. return -1;
  964. }
  965. evlist->hybrid_pmu_name = perf_pmu__hybrid_type_to_pmu(str);
  966. if (!evlist->hybrid_pmu_name) {
  967. fprintf(stderr, "--cputype %s is not supported!\n", str);
  968. return -1;
  969. }
  970. return 0;
  971. }
  972. static struct option stat_options[] = {
  973. OPT_BOOLEAN('T', "transaction", &transaction_run,
  974. "hardware transaction statistics"),
  975. OPT_CALLBACK('e', "event", &evsel_list, "event",
  976. "event selector. use 'perf list' to list available events",
  977. parse_events_option),
  978. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  979. "event filter", parse_filter),
  980. OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
  981. "child tasks do not inherit counters"),
  982. OPT_STRING('p', "pid", &target.pid, "pid",
  983. "stat events on existing process id"),
  984. OPT_STRING('t', "tid", &target.tid, "tid",
  985. "stat events on existing thread id"),
  986. #ifdef HAVE_BPF_SKEL
  987. OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
  988. "stat events on existing bpf program id"),
  989. OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
  990. "use bpf program to count events"),
  991. OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
  992. "path to perf_event_attr map"),
  993. #endif
  994. OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
  995. "system-wide collection from all CPUs"),
  996. OPT_BOOLEAN('g', "group", &group,
  997. "put the counters into a counter group"),
  998. OPT_BOOLEAN(0, "scale", &stat_config.scale,
  999. "Use --no-scale to disable counter scaling for multiplexing"),
  1000. OPT_INCR('v', "verbose", &verbose,
  1001. "be more verbose (show counter open errors, etc)"),
  1002. OPT_INTEGER('r', "repeat", &stat_config.run_count,
  1003. "repeat command and print average + stddev (max: 100, forever: 0)"),
  1004. OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
  1005. "display details about each run (only with -r option)"),
  1006. OPT_BOOLEAN('n', "null", &stat_config.null_run,
  1007. "null run - dont start any counters"),
  1008. OPT_INCR('d', "detailed", &detailed_run,
  1009. "detailed run - start a lot of events"),
  1010. OPT_BOOLEAN('S', "sync", &sync_run,
  1011. "call sync() before starting a run"),
  1012. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  1013. "print large numbers with thousands\' separators",
  1014. stat__set_big_num),
  1015. OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
  1016. "list of cpus to monitor in system-wide"),
  1017. OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
  1018. "disable CPU count aggregation", AGGR_NONE),
  1019. OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
  1020. OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
  1021. "Merge identical named hybrid events"),
  1022. OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
  1023. "print counts with custom separator"),
  1024. OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
  1025. "print counts in JSON format"),
  1026. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  1027. "monitor event in cgroup name only", parse_stat_cgroups),
  1028. OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
  1029. "expand events for each cgroup"),
  1030. OPT_STRING('o', "output", &output_name, "file", "output file name"),
  1031. OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
  1032. OPT_INTEGER(0, "log-fd", &output_fd,
  1033. "log output to fd, instead of stderr"),
  1034. OPT_STRING(0, "pre", &pre_cmd, "command",
  1035. "command to run prior to the measured command"),
  1036. OPT_STRING(0, "post", &post_cmd, "command",
  1037. "command to run after to the measured command"),
  1038. OPT_UINTEGER('I', "interval-print", &stat_config.interval,
  1039. "print counts at regular interval in ms "
  1040. "(overhead is possible for values <= 100ms)"),
  1041. OPT_INTEGER(0, "interval-count", &stat_config.times,
  1042. "print counts for fixed number of times"),
  1043. OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
  1044. "clear screen in between new interval"),
  1045. OPT_UINTEGER(0, "timeout", &stat_config.timeout,
  1046. "stop workload and print counts after a timeout period in ms (>= 10ms)"),
  1047. OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
  1048. "aggregate counts per processor socket", AGGR_SOCKET),
  1049. OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
  1050. "aggregate counts per processor die", AGGR_DIE),
  1051. OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
  1052. "aggregate counts per physical processor core", AGGR_CORE),
  1053. OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
  1054. "aggregate counts per thread", AGGR_THREAD),
  1055. OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
  1056. "aggregate counts per numa node", AGGR_NODE),
  1057. OPT_INTEGER('D', "delay", &target.initial_delay,
  1058. "ms to wait before starting measurement after program start (-1: start with events disabled)"),
  1059. OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
  1060. "Only print computed metrics. No raw values", enable_metric_only),
  1061. OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
  1062. "don't group metric events, impacts multiplexing"),
  1063. OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
  1064. "don't try to share events between metrics in a group"),
  1065. OPT_BOOLEAN(0, "topdown", &topdown_run,
  1066. "measure top-down statistics"),
  1067. OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
  1068. "Set the metrics level for the top-down statistics (0: max level)"),
  1069. OPT_BOOLEAN(0, "smi-cost", &smi_cost,
  1070. "measure SMI cost"),
  1071. OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
  1072. "monitor specified metrics or metric groups (separated by ,)",
  1073. append_metric_groups),
  1074. OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
  1075. "Configure all used events to run in kernel space.",
  1076. PARSE_OPT_EXCLUSIVE),
  1077. OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
  1078. "Configure all used events to run in user space.",
  1079. PARSE_OPT_EXCLUSIVE),
  1080. OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
  1081. "Use with 'percore' event qualifier to show the event "
  1082. "counts of one hardware thread by sum up total hardware "
  1083. "threads of same physical core"),
  1084. OPT_BOOLEAN(0, "summary", &stat_config.summary,
  1085. "print summary for interval mode"),
  1086. OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
  1087. "don't print 'summary' for CSV summary output"),
  1088. OPT_BOOLEAN(0, "quiet", &quiet,
  1089. "don't print any output, messages or warnings (useful with record)"),
  1090. OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
  1091. "Only enable events on applying cpu with this type "
  1092. "for hybrid platform (e.g. core or atom)",
  1093. parse_hybrid_type),
  1094. #ifdef HAVE_LIBPFM
  1095. OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
  1096. "libpfm4 event selector. use 'perf list' to list available events",
  1097. parse_libpfm_events_option),
  1098. #endif
  1099. OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
  1100. "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
  1101. "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
  1102. "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
  1103. parse_control_option),
  1104. OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
  1105. "measure I/O performance metrics provided by arch/platform",
  1106. iostat_parse),
  1107. OPT_END()
  1108. };
  1109. static const char *const aggr_mode__string[] = {
  1110. [AGGR_CORE] = "core",
  1111. [AGGR_DIE] = "die",
  1112. [AGGR_GLOBAL] = "global",
  1113. [AGGR_NODE] = "node",
  1114. [AGGR_NONE] = "none",
  1115. [AGGR_SOCKET] = "socket",
  1116. [AGGR_THREAD] = "thread",
  1117. [AGGR_UNSET] = "unset",
  1118. };
  1119. static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
  1120. struct perf_cpu cpu)
  1121. {
  1122. return aggr_cpu_id__socket(cpu, /*data=*/NULL);
  1123. }
  1124. static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
  1125. struct perf_cpu cpu)
  1126. {
  1127. return aggr_cpu_id__die(cpu, /*data=*/NULL);
  1128. }
  1129. static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
  1130. struct perf_cpu cpu)
  1131. {
  1132. return aggr_cpu_id__core(cpu, /*data=*/NULL);
  1133. }
  1134. static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
  1135. struct perf_cpu cpu)
  1136. {
  1137. return aggr_cpu_id__node(cpu, /*data=*/NULL);
  1138. }
  1139. static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
  1140. aggr_get_id_t get_id, struct perf_cpu cpu)
  1141. {
  1142. struct aggr_cpu_id id = aggr_cpu_id__empty();
  1143. if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
  1144. config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
  1145. id = config->cpus_aggr_map->map[cpu.cpu];
  1146. return id;
  1147. }
  1148. static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
  1149. struct perf_cpu cpu)
  1150. {
  1151. return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
  1152. }
  1153. static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
  1154. struct perf_cpu cpu)
  1155. {
  1156. return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
  1157. }
  1158. static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
  1159. struct perf_cpu cpu)
  1160. {
  1161. return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
  1162. }
  1163. static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
  1164. struct perf_cpu cpu)
  1165. {
  1166. return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
  1167. }
  1168. static bool term_percore_set(void)
  1169. {
  1170. struct evsel *counter;
  1171. evlist__for_each_entry(evsel_list, counter) {
  1172. if (counter->percore)
  1173. return true;
  1174. }
  1175. return false;
  1176. }
  1177. static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
  1178. {
  1179. switch (aggr_mode) {
  1180. case AGGR_SOCKET:
  1181. return aggr_cpu_id__socket;
  1182. case AGGR_DIE:
  1183. return aggr_cpu_id__die;
  1184. case AGGR_CORE:
  1185. return aggr_cpu_id__core;
  1186. case AGGR_NODE:
  1187. return aggr_cpu_id__node;
  1188. case AGGR_NONE:
  1189. if (term_percore_set())
  1190. return aggr_cpu_id__core;
  1191. return NULL;
  1192. case AGGR_GLOBAL:
  1193. case AGGR_THREAD:
  1194. case AGGR_UNSET:
  1195. case AGGR_MAX:
  1196. default:
  1197. return NULL;
  1198. }
  1199. }
  1200. static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
  1201. {
  1202. switch (aggr_mode) {
  1203. case AGGR_SOCKET:
  1204. return perf_stat__get_socket_cached;
  1205. case AGGR_DIE:
  1206. return perf_stat__get_die_cached;
  1207. case AGGR_CORE:
  1208. return perf_stat__get_core_cached;
  1209. case AGGR_NODE:
  1210. return perf_stat__get_node_cached;
  1211. case AGGR_NONE:
  1212. if (term_percore_set()) {
  1213. return perf_stat__get_core_cached;
  1214. }
  1215. return NULL;
  1216. case AGGR_GLOBAL:
  1217. case AGGR_THREAD:
  1218. case AGGR_UNSET:
  1219. case AGGR_MAX:
  1220. default:
  1221. return NULL;
  1222. }
  1223. }
  1224. static int perf_stat_init_aggr_mode(void)
  1225. {
  1226. int nr;
  1227. aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
  1228. if (get_id) {
  1229. stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
  1230. get_id, /*data=*/NULL);
  1231. if (!stat_config.aggr_map) {
  1232. pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
  1233. return -1;
  1234. }
  1235. stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
  1236. }
  1237. /*
  1238. * The evsel_list->cpus is the base we operate on,
  1239. * taking the highest cpu number to be the size of
  1240. * the aggregation translate cpumap.
  1241. */
  1242. if (!perf_cpu_map__empty(evsel_list->core.user_requested_cpus))
  1243. nr = perf_cpu_map__max(evsel_list->core.user_requested_cpus).cpu;
  1244. else
  1245. nr = 0;
  1246. stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
  1247. return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
  1248. }
  1249. static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
  1250. {
  1251. if (map) {
  1252. WARN_ONCE(refcount_read(&map->refcnt) != 0,
  1253. "cpu_aggr_map refcnt unbalanced\n");
  1254. free(map);
  1255. }
  1256. }
  1257. static void cpu_aggr_map__put(struct cpu_aggr_map *map)
  1258. {
  1259. if (map && refcount_dec_and_test(&map->refcnt))
  1260. cpu_aggr_map__delete(map);
  1261. }
  1262. static void perf_stat__exit_aggr_mode(void)
  1263. {
  1264. cpu_aggr_map__put(stat_config.aggr_map);
  1265. cpu_aggr_map__put(stat_config.cpus_aggr_map);
  1266. stat_config.aggr_map = NULL;
  1267. stat_config.cpus_aggr_map = NULL;
  1268. }
  1269. static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
  1270. {
  1271. struct perf_env *env = data;
  1272. struct aggr_cpu_id id = aggr_cpu_id__empty();
  1273. if (cpu.cpu != -1)
  1274. id.socket = env->cpu[cpu.cpu].socket_id;
  1275. return id;
  1276. }
  1277. static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
  1278. {
  1279. struct perf_env *env = data;
  1280. struct aggr_cpu_id id = aggr_cpu_id__empty();
  1281. if (cpu.cpu != -1) {
  1282. /*
  1283. * die_id is relative to socket, so start
  1284. * with the socket ID and then add die to
  1285. * make a unique ID.
  1286. */
  1287. id.socket = env->cpu[cpu.cpu].socket_id;
  1288. id.die = env->cpu[cpu.cpu].die_id;
  1289. }
  1290. return id;
  1291. }
  1292. static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
  1293. {
  1294. struct perf_env *env = data;
  1295. struct aggr_cpu_id id = aggr_cpu_id__empty();
  1296. if (cpu.cpu != -1) {
  1297. /*
  1298. * core_id is relative to socket and die,
  1299. * we need a global id. So we set
  1300. * socket, die id and core id
  1301. */
  1302. id.socket = env->cpu[cpu.cpu].socket_id;
  1303. id.die = env->cpu[cpu.cpu].die_id;
  1304. id.core = env->cpu[cpu.cpu].core_id;
  1305. }
  1306. return id;
  1307. }
  1308. static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
  1309. {
  1310. struct aggr_cpu_id id = aggr_cpu_id__empty();
  1311. id.node = perf_env__numa_node(data, cpu);
  1312. return id;
  1313. }
  1314. static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
  1315. struct perf_cpu cpu)
  1316. {
  1317. return perf_env__get_socket_aggr_by_cpu(cpu, &perf_stat.session->header.env);
  1318. }
  1319. static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
  1320. struct perf_cpu cpu)
  1321. {
  1322. return perf_env__get_die_aggr_by_cpu(cpu, &perf_stat.session->header.env);
  1323. }
  1324. static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
  1325. struct perf_cpu cpu)
  1326. {
  1327. return perf_env__get_core_aggr_by_cpu(cpu, &perf_stat.session->header.env);
  1328. }
  1329. static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
  1330. struct perf_cpu cpu)
  1331. {
  1332. return perf_env__get_node_aggr_by_cpu(cpu, &perf_stat.session->header.env);
  1333. }
  1334. static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
  1335. {
  1336. switch (aggr_mode) {
  1337. case AGGR_SOCKET:
  1338. return perf_env__get_socket_aggr_by_cpu;
  1339. case AGGR_DIE:
  1340. return perf_env__get_die_aggr_by_cpu;
  1341. case AGGR_CORE:
  1342. return perf_env__get_core_aggr_by_cpu;
  1343. case AGGR_NODE:
  1344. return perf_env__get_node_aggr_by_cpu;
  1345. case AGGR_NONE:
  1346. case AGGR_GLOBAL:
  1347. case AGGR_THREAD:
  1348. case AGGR_UNSET:
  1349. case AGGR_MAX:
  1350. default:
  1351. return NULL;
  1352. }
  1353. }
  1354. static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
  1355. {
  1356. switch (aggr_mode) {
  1357. case AGGR_SOCKET:
  1358. return perf_stat__get_socket_file;
  1359. case AGGR_DIE:
  1360. return perf_stat__get_die_file;
  1361. case AGGR_CORE:
  1362. return perf_stat__get_core_file;
  1363. case AGGR_NODE:
  1364. return perf_stat__get_node_file;
  1365. case AGGR_NONE:
  1366. case AGGR_GLOBAL:
  1367. case AGGR_THREAD:
  1368. case AGGR_UNSET:
  1369. case AGGR_MAX:
  1370. default:
  1371. return NULL;
  1372. }
  1373. }
  1374. static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
  1375. {
  1376. struct perf_env *env = &st->session->header.env;
  1377. aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
  1378. if (!get_id)
  1379. return 0;
  1380. stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus, get_id, env);
  1381. if (!stat_config.aggr_map) {
  1382. pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
  1383. return -1;
  1384. }
  1385. stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
  1386. return 0;
  1387. }
  1388. /*
  1389. * Add default attributes, if there were no attributes specified or
  1390. * if -d/--detailed, -d -d or -d -d -d is used:
  1391. */
  1392. static int add_default_attributes(void)
  1393. {
  1394. int err;
  1395. struct perf_event_attr default_attrs0[] = {
  1396. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  1397. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  1398. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  1399. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  1400. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  1401. };
  1402. struct perf_event_attr frontend_attrs[] = {
  1403. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
  1404. };
  1405. struct perf_event_attr backend_attrs[] = {
  1406. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
  1407. };
  1408. struct perf_event_attr default_attrs1[] = {
  1409. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  1410. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  1411. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  1412. };
  1413. /*
  1414. * Detailed stats (-d), covering the L1 and last level data caches:
  1415. */
  1416. struct perf_event_attr detailed_attrs[] = {
  1417. { .type = PERF_TYPE_HW_CACHE,
  1418. .config =
  1419. PERF_COUNT_HW_CACHE_L1D << 0 |
  1420. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1421. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1422. { .type = PERF_TYPE_HW_CACHE,
  1423. .config =
  1424. PERF_COUNT_HW_CACHE_L1D << 0 |
  1425. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1426. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1427. { .type = PERF_TYPE_HW_CACHE,
  1428. .config =
  1429. PERF_COUNT_HW_CACHE_LL << 0 |
  1430. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1431. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1432. { .type = PERF_TYPE_HW_CACHE,
  1433. .config =
  1434. PERF_COUNT_HW_CACHE_LL << 0 |
  1435. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1436. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1437. };
  1438. /*
  1439. * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
  1440. */
  1441. struct perf_event_attr very_detailed_attrs[] = {
  1442. { .type = PERF_TYPE_HW_CACHE,
  1443. .config =
  1444. PERF_COUNT_HW_CACHE_L1I << 0 |
  1445. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1446. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1447. { .type = PERF_TYPE_HW_CACHE,
  1448. .config =
  1449. PERF_COUNT_HW_CACHE_L1I << 0 |
  1450. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1451. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1452. { .type = PERF_TYPE_HW_CACHE,
  1453. .config =
  1454. PERF_COUNT_HW_CACHE_DTLB << 0 |
  1455. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1456. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1457. { .type = PERF_TYPE_HW_CACHE,
  1458. .config =
  1459. PERF_COUNT_HW_CACHE_DTLB << 0 |
  1460. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1461. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1462. { .type = PERF_TYPE_HW_CACHE,
  1463. .config =
  1464. PERF_COUNT_HW_CACHE_ITLB << 0 |
  1465. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1466. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1467. { .type = PERF_TYPE_HW_CACHE,
  1468. .config =
  1469. PERF_COUNT_HW_CACHE_ITLB << 0 |
  1470. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1471. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1472. };
  1473. /*
  1474. * Very, very detailed stats (-d -d -d), adding prefetch events:
  1475. */
  1476. struct perf_event_attr very_very_detailed_attrs[] = {
  1477. { .type = PERF_TYPE_HW_CACHE,
  1478. .config =
  1479. PERF_COUNT_HW_CACHE_L1D << 0 |
  1480. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  1481. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1482. { .type = PERF_TYPE_HW_CACHE,
  1483. .config =
  1484. PERF_COUNT_HW_CACHE_L1D << 0 |
  1485. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  1486. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1487. };
  1488. struct perf_event_attr default_null_attrs[] = {};
  1489. /* Set attrs if no event is selected and !null_run: */
  1490. if (stat_config.null_run)
  1491. return 0;
  1492. if (transaction_run) {
  1493. struct parse_events_error errinfo;
  1494. /* Handle -T as -M transaction. Once platform specific metrics
  1495. * support has been added to the json files, all architectures
  1496. * will use this approach. To determine transaction support
  1497. * on an architecture test for such a metric name.
  1498. */
  1499. if (metricgroup__has_metric("transaction")) {
  1500. return metricgroup__parse_groups(evsel_list, "transaction",
  1501. stat_config.metric_no_group,
  1502. stat_config.metric_no_merge,
  1503. stat_config.user_requested_cpu_list,
  1504. stat_config.system_wide,
  1505. &stat_config.metric_events);
  1506. }
  1507. parse_events_error__init(&errinfo);
  1508. if (pmu_have_event("cpu", "cycles-ct") &&
  1509. pmu_have_event("cpu", "el-start"))
  1510. err = parse_events(evsel_list, transaction_attrs,
  1511. &errinfo);
  1512. else
  1513. err = parse_events(evsel_list,
  1514. transaction_limited_attrs,
  1515. &errinfo);
  1516. if (err) {
  1517. fprintf(stderr, "Cannot set up transaction events\n");
  1518. parse_events_error__print(&errinfo, transaction_attrs);
  1519. }
  1520. parse_events_error__exit(&errinfo);
  1521. return err ? -1 : 0;
  1522. }
  1523. if (smi_cost) {
  1524. struct parse_events_error errinfo;
  1525. int smi;
  1526. if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
  1527. fprintf(stderr, "freeze_on_smi is not supported.\n");
  1528. return -1;
  1529. }
  1530. if (!smi) {
  1531. if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
  1532. fprintf(stderr, "Failed to set freeze_on_smi.\n");
  1533. return -1;
  1534. }
  1535. smi_reset = true;
  1536. }
  1537. if (!pmu_have_event("msr", "aperf") ||
  1538. !pmu_have_event("msr", "smi")) {
  1539. fprintf(stderr, "To measure SMI cost, it needs "
  1540. "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
  1541. return -1;
  1542. }
  1543. if (!force_metric_only)
  1544. stat_config.metric_only = true;
  1545. parse_events_error__init(&errinfo);
  1546. err = parse_events(evsel_list, smi_cost_attrs, &errinfo);
  1547. if (err) {
  1548. parse_events_error__print(&errinfo, smi_cost_attrs);
  1549. fprintf(stderr, "Cannot set up SMI cost events\n");
  1550. }
  1551. parse_events_error__exit(&errinfo);
  1552. return err ? -1 : 0;
  1553. }
  1554. if (topdown_run) {
  1555. const char **metric_attrs = topdown_metric_attrs;
  1556. unsigned int max_level = 1;
  1557. char *str = NULL;
  1558. bool warn = false;
  1559. const char *pmu_name = arch_get_topdown_pmu_name(evsel_list, true);
  1560. if (!force_metric_only)
  1561. stat_config.metric_only = true;
  1562. if (pmu_have_event(pmu_name, topdown_metric_L2_attrs[5])) {
  1563. metric_attrs = topdown_metric_L2_attrs;
  1564. max_level = 2;
  1565. }
  1566. if (stat_config.topdown_level > max_level) {
  1567. pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
  1568. return -1;
  1569. } else if (!stat_config.topdown_level)
  1570. stat_config.topdown_level = max_level;
  1571. if (topdown_filter_events(metric_attrs, &str, 1, pmu_name) < 0) {
  1572. pr_err("Out of memory\n");
  1573. return -1;
  1574. }
  1575. if (metric_attrs[0] && str) {
  1576. if (!stat_config.interval && !stat_config.metric_only) {
  1577. fprintf(stat_config.output,
  1578. "Topdown accuracy may decrease when measuring long periods.\n"
  1579. "Please print the result regularly, e.g. -I1000\n");
  1580. }
  1581. goto setup_metrics;
  1582. }
  1583. zfree(&str);
  1584. if (stat_config.aggr_mode != AGGR_GLOBAL &&
  1585. stat_config.aggr_mode != AGGR_CORE) {
  1586. pr_err("top down event configuration requires --per-core mode\n");
  1587. return -1;
  1588. }
  1589. stat_config.aggr_mode = AGGR_CORE;
  1590. if (nr_cgroups || !target__has_cpu(&target)) {
  1591. pr_err("top down event configuration requires system-wide mode (-a)\n");
  1592. return -1;
  1593. }
  1594. if (topdown_filter_events(topdown_attrs, &str,
  1595. arch_topdown_check_group(&warn),
  1596. pmu_name) < 0) {
  1597. pr_err("Out of memory\n");
  1598. return -1;
  1599. }
  1600. if (topdown_attrs[0] && str) {
  1601. struct parse_events_error errinfo;
  1602. if (warn)
  1603. arch_topdown_group_warn();
  1604. setup_metrics:
  1605. parse_events_error__init(&errinfo);
  1606. err = parse_events(evsel_list, str, &errinfo);
  1607. if (err) {
  1608. fprintf(stderr,
  1609. "Cannot set up top down events %s: %d\n",
  1610. str, err);
  1611. parse_events_error__print(&errinfo, str);
  1612. parse_events_error__exit(&errinfo);
  1613. free(str);
  1614. return -1;
  1615. }
  1616. parse_events_error__exit(&errinfo);
  1617. } else {
  1618. fprintf(stderr, "System does not support topdown\n");
  1619. return -1;
  1620. }
  1621. free(str);
  1622. }
  1623. if (!stat_config.topdown_level)
  1624. stat_config.topdown_level = TOPDOWN_MAX_LEVEL;
  1625. if (!evsel_list->core.nr_entries) {
  1626. if (target__has_cpu(&target))
  1627. default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
  1628. if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
  1629. return -1;
  1630. if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
  1631. if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
  1632. return -1;
  1633. }
  1634. if (pmu_have_event("cpu", "stalled-cycles-backend")) {
  1635. if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
  1636. return -1;
  1637. }
  1638. if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
  1639. return -1;
  1640. /* Platform specific attrs */
  1641. if (evlist__add_default_attrs(evsel_list, default_null_attrs) < 0)
  1642. return -1;
  1643. }
  1644. /* Detailed events get appended to the event list: */
  1645. if (detailed_run < 1)
  1646. return 0;
  1647. /* Append detailed run extra attributes: */
  1648. if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
  1649. return -1;
  1650. if (detailed_run < 2)
  1651. return 0;
  1652. /* Append very detailed run extra attributes: */
  1653. if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
  1654. return -1;
  1655. if (detailed_run < 3)
  1656. return 0;
  1657. /* Append very, very detailed run extra attributes: */
  1658. return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
  1659. }
  1660. static const char * const stat_record_usage[] = {
  1661. "perf stat record [<options>]",
  1662. NULL,
  1663. };
  1664. static void init_features(struct perf_session *session)
  1665. {
  1666. int feat;
  1667. for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
  1668. perf_header__set_feat(&session->header, feat);
  1669. perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
  1670. perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
  1671. perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
  1672. perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
  1673. perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
  1674. }
  1675. static int __cmd_record(int argc, const char **argv)
  1676. {
  1677. struct perf_session *session;
  1678. struct perf_data *data = &perf_stat.data;
  1679. argc = parse_options(argc, argv, stat_options, stat_record_usage,
  1680. PARSE_OPT_STOP_AT_NON_OPTION);
  1681. if (output_name)
  1682. data->path = output_name;
  1683. if (stat_config.run_count != 1 || forever) {
  1684. pr_err("Cannot use -r option with perf stat record.\n");
  1685. return -1;
  1686. }
  1687. session = perf_session__new(data, NULL);
  1688. if (IS_ERR(session)) {
  1689. pr_err("Perf session creation failed\n");
  1690. return PTR_ERR(session);
  1691. }
  1692. init_features(session);
  1693. session->evlist = evsel_list;
  1694. perf_stat.session = session;
  1695. perf_stat.record = true;
  1696. return argc;
  1697. }
  1698. static int process_stat_round_event(struct perf_session *session,
  1699. union perf_event *event)
  1700. {
  1701. struct perf_record_stat_round *stat_round = &event->stat_round;
  1702. struct evsel *counter;
  1703. struct timespec tsh, *ts = NULL;
  1704. const char **argv = session->header.env.cmdline_argv;
  1705. int argc = session->header.env.nr_cmdline;
  1706. evlist__for_each_entry(evsel_list, counter)
  1707. perf_stat_process_counter(&stat_config, counter);
  1708. if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
  1709. update_stats(&walltime_nsecs_stats, stat_round->time);
  1710. if (stat_config.interval && stat_round->time) {
  1711. tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
  1712. tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
  1713. ts = &tsh;
  1714. }
  1715. print_counters(ts, argc, argv);
  1716. return 0;
  1717. }
  1718. static
  1719. int process_stat_config_event(struct perf_session *session,
  1720. union perf_event *event)
  1721. {
  1722. struct perf_tool *tool = session->tool;
  1723. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  1724. perf_event__read_stat_config(&stat_config, &event->stat_config);
  1725. if (perf_cpu_map__empty(st->cpus)) {
  1726. if (st->aggr_mode != AGGR_UNSET)
  1727. pr_warning("warning: processing task data, aggregation mode not set\n");
  1728. return 0;
  1729. }
  1730. if (st->aggr_mode != AGGR_UNSET)
  1731. stat_config.aggr_mode = st->aggr_mode;
  1732. if (perf_stat.data.is_pipe)
  1733. perf_stat_init_aggr_mode();
  1734. else
  1735. perf_stat_init_aggr_mode_file(st);
  1736. return 0;
  1737. }
  1738. static int set_maps(struct perf_stat *st)
  1739. {
  1740. if (!st->cpus || !st->threads)
  1741. return 0;
  1742. if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
  1743. return -EINVAL;
  1744. perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
  1745. if (evlist__alloc_stats(evsel_list, true))
  1746. return -ENOMEM;
  1747. st->maps_allocated = true;
  1748. return 0;
  1749. }
  1750. static
  1751. int process_thread_map_event(struct perf_session *session,
  1752. union perf_event *event)
  1753. {
  1754. struct perf_tool *tool = session->tool;
  1755. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  1756. if (st->threads) {
  1757. pr_warning("Extra thread map event, ignoring.\n");
  1758. return 0;
  1759. }
  1760. st->threads = thread_map__new_event(&event->thread_map);
  1761. if (!st->threads)
  1762. return -ENOMEM;
  1763. return set_maps(st);
  1764. }
  1765. static
  1766. int process_cpu_map_event(struct perf_session *session,
  1767. union perf_event *event)
  1768. {
  1769. struct perf_tool *tool = session->tool;
  1770. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  1771. struct perf_cpu_map *cpus;
  1772. if (st->cpus) {
  1773. pr_warning("Extra cpu map event, ignoring.\n");
  1774. return 0;
  1775. }
  1776. cpus = cpu_map__new_data(&event->cpu_map.data);
  1777. if (!cpus)
  1778. return -ENOMEM;
  1779. st->cpus = cpus;
  1780. return set_maps(st);
  1781. }
  1782. static const char * const stat_report_usage[] = {
  1783. "perf stat report [<options>]",
  1784. NULL,
  1785. };
  1786. static struct perf_stat perf_stat = {
  1787. .tool = {
  1788. .attr = perf_event__process_attr,
  1789. .event_update = perf_event__process_event_update,
  1790. .thread_map = process_thread_map_event,
  1791. .cpu_map = process_cpu_map_event,
  1792. .stat_config = process_stat_config_event,
  1793. .stat = perf_event__process_stat_event,
  1794. .stat_round = process_stat_round_event,
  1795. },
  1796. .aggr_mode = AGGR_UNSET,
  1797. };
  1798. static int __cmd_report(int argc, const char **argv)
  1799. {
  1800. struct perf_session *session;
  1801. const struct option options[] = {
  1802. OPT_STRING('i', "input", &input_name, "file", "input file name"),
  1803. OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
  1804. "aggregate counts per processor socket", AGGR_SOCKET),
  1805. OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
  1806. "aggregate counts per processor die", AGGR_DIE),
  1807. OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
  1808. "aggregate counts per physical processor core", AGGR_CORE),
  1809. OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
  1810. "aggregate counts per numa node", AGGR_NODE),
  1811. OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
  1812. "disable CPU count aggregation", AGGR_NONE),
  1813. OPT_END()
  1814. };
  1815. struct stat st;
  1816. int ret;
  1817. argc = parse_options(argc, argv, options, stat_report_usage, 0);
  1818. if (!input_name || !strlen(input_name)) {
  1819. if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
  1820. input_name = "-";
  1821. else
  1822. input_name = "perf.data";
  1823. }
  1824. perf_stat__init_shadow_stats();
  1825. perf_stat.data.path = input_name;
  1826. perf_stat.data.mode = PERF_DATA_MODE_READ;
  1827. session = perf_session__new(&perf_stat.data, &perf_stat.tool);
  1828. if (IS_ERR(session))
  1829. return PTR_ERR(session);
  1830. perf_stat.session = session;
  1831. stat_config.output = stderr;
  1832. evsel_list = session->evlist;
  1833. ret = perf_session__process_events(session);
  1834. if (ret)
  1835. return ret;
  1836. perf_session__delete(session);
  1837. return 0;
  1838. }
  1839. static void setup_system_wide(int forks)
  1840. {
  1841. /*
  1842. * Make system wide (-a) the default target if
  1843. * no target was specified and one of following
  1844. * conditions is met:
  1845. *
  1846. * - there's no workload specified
  1847. * - there is workload specified but all requested
  1848. * events are system wide events
  1849. */
  1850. if (!target__none(&target))
  1851. return;
  1852. if (!forks)
  1853. target.system_wide = true;
  1854. else {
  1855. struct evsel *counter;
  1856. evlist__for_each_entry(evsel_list, counter) {
  1857. if (!counter->core.requires_cpu &&
  1858. strcmp(counter->name, "duration_time")) {
  1859. return;
  1860. }
  1861. }
  1862. if (evsel_list->core.nr_entries)
  1863. target.system_wide = true;
  1864. }
  1865. }
  1866. int cmd_stat(int argc, const char **argv)
  1867. {
  1868. const char * const stat_usage[] = {
  1869. "perf stat [<options>] [<command>]",
  1870. NULL
  1871. };
  1872. int status = -EINVAL, run_idx, err;
  1873. const char *mode;
  1874. FILE *output = stderr;
  1875. unsigned int interval, timeout;
  1876. const char * const stat_subcommands[] = { "record", "report" };
  1877. char errbuf[BUFSIZ];
  1878. setlocale(LC_ALL, "");
  1879. evsel_list = evlist__new();
  1880. if (evsel_list == NULL)
  1881. return -ENOMEM;
  1882. parse_events__shrink_config_terms();
  1883. /* String-parsing callback-based options would segfault when negated */
  1884. set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
  1885. set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
  1886. set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
  1887. argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
  1888. (const char **) stat_usage,
  1889. PARSE_OPT_STOP_AT_NON_OPTION);
  1890. if (stat_config.csv_sep) {
  1891. stat_config.csv_output = true;
  1892. if (!strcmp(stat_config.csv_sep, "\\t"))
  1893. stat_config.csv_sep = "\t";
  1894. } else
  1895. stat_config.csv_sep = DEFAULT_SEPARATOR;
  1896. if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
  1897. argc = __cmd_record(argc, argv);
  1898. if (argc < 0)
  1899. return -1;
  1900. } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
  1901. return __cmd_report(argc, argv);
  1902. interval = stat_config.interval;
  1903. timeout = stat_config.timeout;
  1904. /*
  1905. * For record command the -o is already taken care of.
  1906. */
  1907. if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
  1908. output = NULL;
  1909. if (output_name && output_fd) {
  1910. fprintf(stderr, "cannot use both --output and --log-fd\n");
  1911. parse_options_usage(stat_usage, stat_options, "o", 1);
  1912. parse_options_usage(NULL, stat_options, "log-fd", 0);
  1913. goto out;
  1914. }
  1915. if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
  1916. fprintf(stderr, "--metric-only is not supported with --per-thread\n");
  1917. goto out;
  1918. }
  1919. if (stat_config.metric_only && stat_config.run_count > 1) {
  1920. fprintf(stderr, "--metric-only is not supported with -r\n");
  1921. goto out;
  1922. }
  1923. if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
  1924. fprintf(stderr, "--table is only supported with -r\n");
  1925. parse_options_usage(stat_usage, stat_options, "r", 1);
  1926. parse_options_usage(NULL, stat_options, "table", 0);
  1927. goto out;
  1928. }
  1929. if (output_fd < 0) {
  1930. fprintf(stderr, "argument to --log-fd must be a > 0\n");
  1931. parse_options_usage(stat_usage, stat_options, "log-fd", 0);
  1932. goto out;
  1933. }
  1934. if (!output && !quiet) {
  1935. struct timespec tm;
  1936. mode = append_file ? "a" : "w";
  1937. output = fopen(output_name, mode);
  1938. if (!output) {
  1939. perror("failed to create output file");
  1940. return -1;
  1941. }
  1942. clock_gettime(CLOCK_REALTIME, &tm);
  1943. fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
  1944. } else if (output_fd > 0) {
  1945. mode = append_file ? "a" : "w";
  1946. output = fdopen(output_fd, mode);
  1947. if (!output) {
  1948. perror("Failed opening logfd");
  1949. return -errno;
  1950. }
  1951. }
  1952. stat_config.output = output;
  1953. /*
  1954. * let the spreadsheet do the pretty-printing
  1955. */
  1956. if (stat_config.csv_output) {
  1957. /* User explicitly passed -B? */
  1958. if (big_num_opt == 1) {
  1959. fprintf(stderr, "-B option not supported with -x\n");
  1960. parse_options_usage(stat_usage, stat_options, "B", 1);
  1961. parse_options_usage(NULL, stat_options, "x", 1);
  1962. goto out;
  1963. } else /* Nope, so disable big number formatting */
  1964. stat_config.big_num = false;
  1965. } else if (big_num_opt == 0) /* User passed --no-big-num */
  1966. stat_config.big_num = false;
  1967. err = target__validate(&target);
  1968. if (err) {
  1969. target__strerror(&target, err, errbuf, BUFSIZ);
  1970. pr_warning("%s\n", errbuf);
  1971. }
  1972. setup_system_wide(argc);
  1973. /*
  1974. * Display user/system times only for single
  1975. * run and when there's specified tracee.
  1976. */
  1977. if ((stat_config.run_count == 1) && target__none(&target))
  1978. stat_config.ru_display = true;
  1979. if (stat_config.run_count < 0) {
  1980. pr_err("Run count must be a positive number\n");
  1981. parse_options_usage(stat_usage, stat_options, "r", 1);
  1982. goto out;
  1983. } else if (stat_config.run_count == 0) {
  1984. forever = true;
  1985. stat_config.run_count = 1;
  1986. }
  1987. if (stat_config.walltime_run_table) {
  1988. stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
  1989. if (!stat_config.walltime_run) {
  1990. pr_err("failed to setup -r option");
  1991. goto out;
  1992. }
  1993. }
  1994. if ((stat_config.aggr_mode == AGGR_THREAD) &&
  1995. !target__has_task(&target)) {
  1996. if (!target.system_wide || target.cpu_list) {
  1997. fprintf(stderr, "The --per-thread option is only "
  1998. "available when monitoring via -p -t -a "
  1999. "options or only --per-thread.\n");
  2000. parse_options_usage(NULL, stat_options, "p", 1);
  2001. parse_options_usage(NULL, stat_options, "t", 1);
  2002. goto out;
  2003. }
  2004. }
  2005. /*
  2006. * no_aggr, cgroup are for system-wide only
  2007. * --per-thread is aggregated per thread, we dont mix it with cpu mode
  2008. */
  2009. if (((stat_config.aggr_mode != AGGR_GLOBAL &&
  2010. stat_config.aggr_mode != AGGR_THREAD) ||
  2011. (nr_cgroups || stat_config.cgroup_list)) &&
  2012. !target__has_cpu(&target)) {
  2013. fprintf(stderr, "both cgroup and no-aggregation "
  2014. "modes only available in system-wide mode\n");
  2015. parse_options_usage(stat_usage, stat_options, "G", 1);
  2016. parse_options_usage(NULL, stat_options, "A", 1);
  2017. parse_options_usage(NULL, stat_options, "a", 1);
  2018. parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
  2019. goto out;
  2020. }
  2021. if (stat_config.iostat_run) {
  2022. status = iostat_prepare(evsel_list, &stat_config);
  2023. if (status)
  2024. goto out;
  2025. if (iostat_mode == IOSTAT_LIST) {
  2026. iostat_list(evsel_list, &stat_config);
  2027. goto out;
  2028. } else if (verbose)
  2029. iostat_list(evsel_list, &stat_config);
  2030. if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
  2031. target.system_wide = true;
  2032. }
  2033. if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
  2034. target.per_thread = true;
  2035. stat_config.system_wide = target.system_wide;
  2036. if (target.cpu_list) {
  2037. stat_config.user_requested_cpu_list = strdup(target.cpu_list);
  2038. if (!stat_config.user_requested_cpu_list) {
  2039. status = -ENOMEM;
  2040. goto out;
  2041. }
  2042. }
  2043. /*
  2044. * Metric parsing needs to be delayed as metrics may optimize events
  2045. * knowing the target is system-wide.
  2046. */
  2047. if (metrics) {
  2048. metricgroup__parse_groups(evsel_list, metrics,
  2049. stat_config.metric_no_group,
  2050. stat_config.metric_no_merge,
  2051. stat_config.user_requested_cpu_list,
  2052. stat_config.system_wide,
  2053. &stat_config.metric_events);
  2054. zfree(&metrics);
  2055. }
  2056. perf_stat__collect_metric_expr(evsel_list);
  2057. perf_stat__init_shadow_stats();
  2058. if (add_default_attributes())
  2059. goto out;
  2060. if (stat_config.cgroup_list) {
  2061. if (nr_cgroups > 0) {
  2062. pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
  2063. parse_options_usage(stat_usage, stat_options, "G", 1);
  2064. parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
  2065. goto out;
  2066. }
  2067. if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
  2068. &stat_config.metric_events, true) < 0) {
  2069. parse_options_usage(stat_usage, stat_options,
  2070. "for-each-cgroup", 0);
  2071. goto out;
  2072. }
  2073. }
  2074. if (evlist__fix_hybrid_cpus(evsel_list, target.cpu_list)) {
  2075. pr_err("failed to use cpu list %s\n", target.cpu_list);
  2076. goto out;
  2077. }
  2078. target.hybrid = perf_pmu__has_hybrid();
  2079. if (evlist__create_maps(evsel_list, &target) < 0) {
  2080. if (target__has_task(&target)) {
  2081. pr_err("Problems finding threads of monitor\n");
  2082. parse_options_usage(stat_usage, stat_options, "p", 1);
  2083. parse_options_usage(NULL, stat_options, "t", 1);
  2084. } else if (target__has_cpu(&target)) {
  2085. perror("failed to parse CPUs map");
  2086. parse_options_usage(stat_usage, stat_options, "C", 1);
  2087. parse_options_usage(NULL, stat_options, "a", 1);
  2088. }
  2089. goto out;
  2090. }
  2091. evlist__check_cpu_maps(evsel_list);
  2092. /*
  2093. * Initialize thread_map with comm names,
  2094. * so we could print it out on output.
  2095. */
  2096. if (stat_config.aggr_mode == AGGR_THREAD) {
  2097. thread_map__read_comms(evsel_list->core.threads);
  2098. }
  2099. if (stat_config.aggr_mode == AGGR_NODE)
  2100. cpu__setup_cpunode_map();
  2101. if (stat_config.times && interval)
  2102. interval_count = true;
  2103. else if (stat_config.times && !interval) {
  2104. pr_err("interval-count option should be used together with "
  2105. "interval-print.\n");
  2106. parse_options_usage(stat_usage, stat_options, "interval-count", 0);
  2107. parse_options_usage(stat_usage, stat_options, "I", 1);
  2108. goto out;
  2109. }
  2110. if (timeout && timeout < 100) {
  2111. if (timeout < 10) {
  2112. pr_err("timeout must be >= 10ms.\n");
  2113. parse_options_usage(stat_usage, stat_options, "timeout", 0);
  2114. goto out;
  2115. } else
  2116. pr_warning("timeout < 100ms. "
  2117. "The overhead percentage could be high in some cases. "
  2118. "Please proceed with caution.\n");
  2119. }
  2120. if (timeout && interval) {
  2121. pr_err("timeout option is not supported with interval-print.\n");
  2122. parse_options_usage(stat_usage, stat_options, "timeout", 0);
  2123. parse_options_usage(stat_usage, stat_options, "I", 1);
  2124. goto out;
  2125. }
  2126. if (evlist__alloc_stats(evsel_list, interval))
  2127. goto out;
  2128. if (perf_stat_init_aggr_mode())
  2129. goto out;
  2130. /*
  2131. * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
  2132. * while avoiding that older tools show confusing messages.
  2133. *
  2134. * However for pipe sessions we need to keep it zero,
  2135. * because script's perf_evsel__check_attr is triggered
  2136. * by attr->sample_type != 0, and we can't run it on
  2137. * stat sessions.
  2138. */
  2139. stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
  2140. /*
  2141. * We dont want to block the signals - that would cause
  2142. * child tasks to inherit that and Ctrl-C would not work.
  2143. * What we want is for Ctrl-C to work in the exec()-ed
  2144. * task, but being ignored by perf stat itself:
  2145. */
  2146. atexit(sig_atexit);
  2147. if (!forever)
  2148. signal(SIGINT, skip_signal);
  2149. signal(SIGCHLD, skip_signal);
  2150. signal(SIGALRM, skip_signal);
  2151. signal(SIGABRT, skip_signal);
  2152. if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
  2153. goto out;
  2154. /* Enable ignoring missing threads when -p option is defined. */
  2155. evlist__first(evsel_list)->ignore_missing_thread = target.pid;
  2156. status = 0;
  2157. for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
  2158. if (stat_config.run_count != 1 && verbose > 0)
  2159. fprintf(output, "[ perf stat: executing run #%d ... ]\n",
  2160. run_idx + 1);
  2161. if (run_idx != 0)
  2162. evlist__reset_prev_raw_counts(evsel_list);
  2163. status = run_perf_stat(argc, argv, run_idx);
  2164. if (forever && status != -1 && !interval) {
  2165. print_counters(NULL, argc, argv);
  2166. perf_stat__reset_stats();
  2167. }
  2168. }
  2169. if (!forever && status != -1 && (!interval || stat_config.summary))
  2170. print_counters(NULL, argc, argv);
  2171. evlist__finalize_ctlfd(evsel_list);
  2172. if (STAT_RECORD) {
  2173. /*
  2174. * We synthesize the kernel mmap record just so that older tools
  2175. * don't emit warnings about not being able to resolve symbols
  2176. * due to /proc/sys/kernel/kptr_restrict settings and instead provide
  2177. * a saner message about no samples being in the perf.data file.
  2178. *
  2179. * This also serves to suppress a warning about f_header.data.size == 0
  2180. * in header.c at the moment 'perf stat record' gets introduced, which
  2181. * is not really needed once we start adding the stat specific PERF_RECORD_
  2182. * records, but the need to suppress the kptr_restrict messages in older
  2183. * tools remain -acme
  2184. */
  2185. int fd = perf_data__fd(&perf_stat.data);
  2186. err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
  2187. process_synthesized_event,
  2188. &perf_stat.session->machines.host);
  2189. if (err) {
  2190. pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
  2191. "older tools may produce warnings about this file\n.");
  2192. }
  2193. if (!interval) {
  2194. if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
  2195. pr_err("failed to write stat round event\n");
  2196. }
  2197. if (!perf_stat.data.is_pipe) {
  2198. perf_stat.session->header.data_size += perf_stat.bytes_written;
  2199. perf_session__write_header(perf_stat.session, evsel_list, fd, true);
  2200. }
  2201. evlist__close(evsel_list);
  2202. perf_session__delete(perf_stat.session);
  2203. }
  2204. perf_stat__exit_aggr_mode();
  2205. evlist__free_stats(evsel_list);
  2206. out:
  2207. if (stat_config.iostat_run)
  2208. iostat_release(evsel_list);
  2209. zfree(&stat_config.walltime_run);
  2210. zfree(&stat_config.user_requested_cpu_list);
  2211. if (smi_cost && smi_reset)
  2212. sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
  2213. evlist__delete(evsel_list);
  2214. metricgroup__rblist_exit(&stat_config.metric_events);
  2215. evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);
  2216. return status;
  2217. }