builtin-stat.c 81 KB

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