builtin-stat.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. /*
  2. * builtin-stat.c
  3. *
  4. * Builtin stat command: Give a precise performance counters summary
  5. * overview about any workload, CPU or specific PID.
  6. *
  7. * Sample output:
  8. $ perf stat ./hackbench 10
  9. Time: 0.118
  10. Performance counter stats for './hackbench 10':
  11. 1708.761321 task-clock # 11.037 CPUs utilized
  12. 41,190 context-switches # 0.024 M/sec
  13. 6,735 CPU-migrations # 0.004 M/sec
  14. 17,318 page-faults # 0.010 M/sec
  15. 5,205,202,243 cycles # 3.046 GHz
  16. 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
  17. 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
  18. 2,603,501,247 instructions # 0.50 insns per cycle
  19. # 1.48 stalled cycles per insn
  20. 484,357,498 branches # 283.455 M/sec
  21. 6,388,934 branch-misses # 1.32% of all branches
  22. 0.154822978 seconds time elapsed
  23. *
  24. * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
  25. *
  26. * Improvements and fixes by:
  27. *
  28. * Arjan van de Ven <arjan@linux.intel.com>
  29. * Yanmin Zhang <yanmin.zhang@intel.com>
  30. * Wu Fengguang <fengguang.wu@intel.com>
  31. * Mike Galbraith <efault@gmx.de>
  32. * Paul Mackerras <paulus@samba.org>
  33. * Jaswinder Singh Rajput <jaswinder@kernel.org>
  34. *
  35. * Released under the GPL v2. (and only v2, not any later version)
  36. */
  37. #include "perf.h"
  38. #include "builtin.h"
  39. #include "util/cgroup.h"
  40. #include "util/util.h"
  41. #include <subcmd/parse-options.h>
  42. #include "util/parse-events.h"
  43. #include "util/pmu.h"
  44. #include "util/event.h"
  45. #include "util/evlist.h"
  46. #include "util/evsel.h"
  47. #include "util/debug.h"
  48. #include "util/drv_configs.h"
  49. #include "util/color.h"
  50. #include "util/stat.h"
  51. #include "util/header.h"
  52. #include "util/cpumap.h"
  53. #include "util/thread.h"
  54. #include "util/thread_map.h"
  55. #include "util/counts.h"
  56. #include "util/group.h"
  57. #include "util/session.h"
  58. #include "util/tool.h"
  59. #include "util/string2.h"
  60. #include "util/metricgroup.h"
  61. #include "asm/bug.h"
  62. #include <linux/time64.h>
  63. #include <api/fs/fs.h>
  64. #include <errno.h>
  65. #include <signal.h>
  66. #include <stdlib.h>
  67. #include <sys/prctl.h>
  68. #include <inttypes.h>
  69. #include <locale.h>
  70. #include <math.h>
  71. #include <sys/types.h>
  72. #include <sys/stat.h>
  73. #include <sys/wait.h>
  74. #include <unistd.h>
  75. #include "sane_ctype.h"
  76. #define DEFAULT_SEPARATOR " "
  77. #define CNTR_NOT_SUPPORTED "<not supported>"
  78. #define CNTR_NOT_COUNTED "<not counted>"
  79. #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
  80. static void print_counters(struct timespec *ts, int argc, const char **argv);
  81. /* Default events used for perf stat -T */
  82. static const char *transaction_attrs = {
  83. "task-clock,"
  84. "{"
  85. "instructions,"
  86. "cycles,"
  87. "cpu/cycles-t/,"
  88. "cpu/tx-start/,"
  89. "cpu/el-start/,"
  90. "cpu/cycles-ct/"
  91. "}"
  92. };
  93. /* More limited version when the CPU does not have all events. */
  94. static const char * transaction_limited_attrs = {
  95. "task-clock,"
  96. "{"
  97. "instructions,"
  98. "cycles,"
  99. "cpu/cycles-t/,"
  100. "cpu/tx-start/"
  101. "}"
  102. };
  103. static const char * topdown_attrs[] = {
  104. "topdown-total-slots",
  105. "topdown-slots-retired",
  106. "topdown-recovery-bubbles",
  107. "topdown-fetch-bubbles",
  108. "topdown-slots-issued",
  109. NULL,
  110. };
  111. static const char *smi_cost_attrs = {
  112. "{"
  113. "msr/aperf/,"
  114. "msr/smi/,"
  115. "cycles"
  116. "}"
  117. };
  118. static struct perf_evlist *evsel_list;
  119. static struct rblist metric_events;
  120. static struct target target = {
  121. .uid = UINT_MAX,
  122. };
  123. typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
  124. static int run_count = 1;
  125. static bool no_inherit = false;
  126. static volatile pid_t child_pid = -1;
  127. static bool null_run = false;
  128. static int detailed_run = 0;
  129. static bool transaction_run;
  130. static bool topdown_run = false;
  131. static bool smi_cost = false;
  132. static bool smi_reset = false;
  133. static bool big_num = true;
  134. static int big_num_opt = -1;
  135. static const char *csv_sep = NULL;
  136. static bool csv_output = false;
  137. static bool group = false;
  138. static const char *pre_cmd = NULL;
  139. static const char *post_cmd = NULL;
  140. static bool sync_run = false;
  141. static unsigned int initial_delay = 0;
  142. static unsigned int unit_width = 4; /* strlen("unit") */
  143. static bool forever = false;
  144. static bool metric_only = false;
  145. static bool force_metric_only = false;
  146. static bool no_merge = false;
  147. static struct timespec ref_time;
  148. static struct cpu_map *aggr_map;
  149. static aggr_get_id_t aggr_get_id;
  150. static bool append_file;
  151. static const char *output_name;
  152. static int output_fd;
  153. static int print_free_counters_hint;
  154. struct perf_stat {
  155. bool record;
  156. struct perf_data data;
  157. struct perf_session *session;
  158. u64 bytes_written;
  159. struct perf_tool tool;
  160. bool maps_allocated;
  161. struct cpu_map *cpus;
  162. struct thread_map *threads;
  163. enum aggr_mode aggr_mode;
  164. };
  165. static struct perf_stat perf_stat;
  166. #define STAT_RECORD perf_stat.record
  167. static volatile int done = 0;
  168. static struct perf_stat_config stat_config = {
  169. .aggr_mode = AGGR_GLOBAL,
  170. .scale = true,
  171. };
  172. static bool is_duration_time(struct perf_evsel *evsel)
  173. {
  174. return !strcmp(evsel->name, "duration_time");
  175. }
  176. static inline void diff_timespec(struct timespec *r, struct timespec *a,
  177. struct timespec *b)
  178. {
  179. r->tv_sec = a->tv_sec - b->tv_sec;
  180. if (a->tv_nsec < b->tv_nsec) {
  181. r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
  182. r->tv_sec--;
  183. } else {
  184. r->tv_nsec = a->tv_nsec - b->tv_nsec ;
  185. }
  186. }
  187. static void perf_stat__reset_stats(void)
  188. {
  189. int i;
  190. perf_evlist__reset_stats(evsel_list);
  191. perf_stat__reset_shadow_stats();
  192. for (i = 0; i < stat_config.stats_num; i++)
  193. perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
  194. }
  195. static int create_perf_stat_counter(struct perf_evsel *evsel)
  196. {
  197. struct perf_event_attr *attr = &evsel->attr;
  198. struct perf_evsel *leader = evsel->leader;
  199. if (stat_config.scale) {
  200. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  201. PERF_FORMAT_TOTAL_TIME_RUNNING;
  202. }
  203. /*
  204. * The event is part of non trivial group, let's enable
  205. * the group read (for leader) and ID retrieval for all
  206. * members.
  207. */
  208. if (leader->nr_members > 1)
  209. attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
  210. attr->inherit = !no_inherit;
  211. /*
  212. * Some events get initialized with sample_(period/type) set,
  213. * like tracepoints. Clear it up for counting.
  214. */
  215. attr->sample_period = 0;
  216. /*
  217. * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
  218. * while avoiding that older tools show confusing messages.
  219. *
  220. * However for pipe sessions we need to keep it zero,
  221. * because script's perf_evsel__check_attr is triggered
  222. * by attr->sample_type != 0, and we can't run it on
  223. * stat sessions.
  224. */
  225. if (!(STAT_RECORD && perf_stat.data.is_pipe))
  226. attr->sample_type = PERF_SAMPLE_IDENTIFIER;
  227. /*
  228. * Disabling all counters initially, they will be enabled
  229. * either manually by us or by kernel via enable_on_exec
  230. * set later.
  231. */
  232. if (perf_evsel__is_group_leader(evsel)) {
  233. attr->disabled = 1;
  234. /*
  235. * In case of initial_delay we enable tracee
  236. * events manually.
  237. */
  238. if (target__none(&target) && !initial_delay)
  239. attr->enable_on_exec = 1;
  240. }
  241. if (target__has_cpu(&target) && !target__has_per_thread(&target))
  242. return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
  243. return perf_evsel__open_per_thread(evsel, evsel_list->threads);
  244. }
  245. /*
  246. * Does the counter have nsecs as a unit?
  247. */
  248. static inline int nsec_counter(struct perf_evsel *evsel)
  249. {
  250. if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
  251. perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  252. return 1;
  253. return 0;
  254. }
  255. static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
  256. union perf_event *event,
  257. struct perf_sample *sample __maybe_unused,
  258. struct machine *machine __maybe_unused)
  259. {
  260. if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
  261. pr_err("failed to write perf data, error: %m\n");
  262. return -1;
  263. }
  264. perf_stat.bytes_written += event->header.size;
  265. return 0;
  266. }
  267. static int write_stat_round_event(u64 tm, u64 type)
  268. {
  269. return perf_event__synthesize_stat_round(NULL, tm, type,
  270. process_synthesized_event,
  271. NULL);
  272. }
  273. #define WRITE_STAT_ROUND_EVENT(time, interval) \
  274. write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
  275. #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
  276. static int
  277. perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
  278. struct perf_counts_values *count)
  279. {
  280. struct perf_sample_id *sid = SID(counter, cpu, thread);
  281. return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
  282. process_synthesized_event, NULL);
  283. }
  284. /*
  285. * Read out the results of a single counter:
  286. * do not aggregate counts across CPUs in system-wide mode
  287. */
  288. static int read_counter(struct perf_evsel *counter)
  289. {
  290. int nthreads = thread_map__nr(evsel_list->threads);
  291. int ncpus, cpu, thread;
  292. if (target__has_cpu(&target) && !target__has_per_thread(&target))
  293. ncpus = perf_evsel__nr_cpus(counter);
  294. else
  295. ncpus = 1;
  296. if (!counter->supported)
  297. return -ENOENT;
  298. if (counter->system_wide)
  299. nthreads = 1;
  300. for (thread = 0; thread < nthreads; thread++) {
  301. for (cpu = 0; cpu < ncpus; cpu++) {
  302. struct perf_counts_values *count;
  303. count = perf_counts(counter->counts, cpu, thread);
  304. /*
  305. * The leader's group read loads data into its group members
  306. * (via perf_evsel__read_counter) and sets threir count->loaded.
  307. */
  308. if (!count->loaded &&
  309. perf_evsel__read_counter(counter, cpu, thread)) {
  310. counter->counts->scaled = -1;
  311. perf_counts(counter->counts, cpu, thread)->ena = 0;
  312. perf_counts(counter->counts, cpu, thread)->run = 0;
  313. return -1;
  314. }
  315. count->loaded = false;
  316. if (STAT_RECORD) {
  317. if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
  318. pr_err("failed to write stat event\n");
  319. return -1;
  320. }
  321. }
  322. if (verbose > 1) {
  323. fprintf(stat_config.output,
  324. "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  325. perf_evsel__name(counter),
  326. cpu,
  327. count->val, count->ena, count->run);
  328. }
  329. }
  330. }
  331. return 0;
  332. }
  333. static void read_counters(void)
  334. {
  335. struct perf_evsel *counter;
  336. int ret;
  337. evlist__for_each_entry(evsel_list, counter) {
  338. ret = read_counter(counter);
  339. if (ret)
  340. pr_debug("failed to read counter %s\n", counter->name);
  341. if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
  342. pr_warning("failed to process counter %s\n", counter->name);
  343. }
  344. }
  345. static void process_interval(void)
  346. {
  347. struct timespec ts, rs;
  348. read_counters();
  349. clock_gettime(CLOCK_MONOTONIC, &ts);
  350. diff_timespec(&rs, &ts, &ref_time);
  351. if (STAT_RECORD) {
  352. if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
  353. pr_err("failed to write stat round event\n");
  354. }
  355. init_stats(&walltime_nsecs_stats);
  356. update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
  357. print_counters(&rs, 0, NULL);
  358. }
  359. static void enable_counters(void)
  360. {
  361. if (initial_delay)
  362. usleep(initial_delay * USEC_PER_MSEC);
  363. /*
  364. * We need to enable counters only if:
  365. * - we don't have tracee (attaching to task or cpu)
  366. * - we have initial delay configured
  367. */
  368. if (!target__none(&target) || initial_delay)
  369. perf_evlist__enable(evsel_list);
  370. }
  371. static void disable_counters(void)
  372. {
  373. /*
  374. * If we don't have tracee (attaching to task or cpu), counters may
  375. * still be running. To get accurate group ratios, we must stop groups
  376. * from counting before reading their constituent counters.
  377. */
  378. if (!target__none(&target))
  379. perf_evlist__disable(evsel_list);
  380. }
  381. static volatile int workload_exec_errno;
  382. /*
  383. * perf_evlist__prepare_workload will send a SIGUSR1
  384. * if the fork fails, since we asked by setting its
  385. * want_signal to true.
  386. */
  387. static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
  388. void *ucontext __maybe_unused)
  389. {
  390. workload_exec_errno = info->si_value.sival_int;
  391. }
  392. static int perf_stat_synthesize_config(bool is_pipe)
  393. {
  394. int err;
  395. if (is_pipe) {
  396. err = perf_event__synthesize_attrs(NULL, perf_stat.session,
  397. process_synthesized_event);
  398. if (err < 0) {
  399. pr_err("Couldn't synthesize attrs.\n");
  400. return err;
  401. }
  402. }
  403. err = perf_event__synthesize_extra_attr(NULL,
  404. evsel_list,
  405. process_synthesized_event,
  406. is_pipe);
  407. err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
  408. process_synthesized_event,
  409. NULL);
  410. if (err < 0) {
  411. pr_err("Couldn't synthesize thread map.\n");
  412. return err;
  413. }
  414. err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
  415. process_synthesized_event, NULL);
  416. if (err < 0) {
  417. pr_err("Couldn't synthesize thread map.\n");
  418. return err;
  419. }
  420. err = perf_event__synthesize_stat_config(NULL, &stat_config,
  421. process_synthesized_event, NULL);
  422. if (err < 0) {
  423. pr_err("Couldn't synthesize config.\n");
  424. return err;
  425. }
  426. return 0;
  427. }
  428. #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
  429. static int __store_counter_ids(struct perf_evsel *counter,
  430. struct cpu_map *cpus,
  431. struct thread_map *threads)
  432. {
  433. int cpu, thread;
  434. for (cpu = 0; cpu < cpus->nr; cpu++) {
  435. for (thread = 0; thread < threads->nr; thread++) {
  436. int fd = FD(counter, cpu, thread);
  437. if (perf_evlist__id_add_fd(evsel_list, counter,
  438. cpu, thread, fd) < 0)
  439. return -1;
  440. }
  441. }
  442. return 0;
  443. }
  444. static int store_counter_ids(struct perf_evsel *counter)
  445. {
  446. struct cpu_map *cpus = counter->cpus;
  447. struct thread_map *threads = counter->threads;
  448. if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
  449. return -ENOMEM;
  450. return __store_counter_ids(counter, cpus, threads);
  451. }
  452. static bool perf_evsel__should_store_id(struct perf_evsel *counter)
  453. {
  454. return STAT_RECORD || counter->attr.read_format & PERF_FORMAT_ID;
  455. }
  456. static struct perf_evsel *perf_evsel__reset_weak_group(struct perf_evsel *evsel)
  457. {
  458. struct perf_evsel *c2, *leader;
  459. bool is_open = true;
  460. leader = evsel->leader;
  461. pr_debug("Weak group for %s/%d failed\n",
  462. leader->name, leader->nr_members);
  463. /*
  464. * for_each_group_member doesn't work here because it doesn't
  465. * include the first entry.
  466. */
  467. evlist__for_each_entry(evsel_list, c2) {
  468. if (c2 == evsel)
  469. is_open = false;
  470. if (c2->leader == leader) {
  471. if (is_open)
  472. perf_evsel__close(c2);
  473. c2->leader = c2;
  474. c2->nr_members = 0;
  475. }
  476. }
  477. return leader;
  478. }
  479. static int __run_perf_stat(int argc, const char **argv)
  480. {
  481. int interval = stat_config.interval;
  482. char msg[BUFSIZ];
  483. unsigned long long t0, t1;
  484. struct perf_evsel *counter;
  485. struct timespec ts;
  486. size_t l;
  487. int status = 0;
  488. const bool forks = (argc > 0);
  489. bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
  490. struct perf_evsel_config_term *err_term;
  491. if (interval) {
  492. ts.tv_sec = interval / USEC_PER_MSEC;
  493. ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
  494. } else {
  495. ts.tv_sec = 1;
  496. ts.tv_nsec = 0;
  497. }
  498. if (forks) {
  499. if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
  500. workload_exec_failed_signal) < 0) {
  501. perror("failed to prepare workload");
  502. return -1;
  503. }
  504. child_pid = evsel_list->workload.pid;
  505. }
  506. if (group)
  507. perf_evlist__set_leader(evsel_list);
  508. evlist__for_each_entry(evsel_list, counter) {
  509. try_again:
  510. if (create_perf_stat_counter(counter) < 0) {
  511. /* Weak group failed. Reset the group. */
  512. if ((errno == EINVAL || errno == EBADF) &&
  513. counter->leader != counter &&
  514. counter->weak_group) {
  515. counter = perf_evsel__reset_weak_group(counter);
  516. goto try_again;
  517. }
  518. /*
  519. * PPC returns ENXIO for HW counters until 2.6.37
  520. * (behavior changed with commit b0a873e).
  521. */
  522. if (errno == EINVAL || errno == ENOSYS ||
  523. errno == ENOENT || errno == EOPNOTSUPP ||
  524. errno == ENXIO) {
  525. if (verbose > 0)
  526. ui__warning("%s event is not supported by the kernel.\n",
  527. perf_evsel__name(counter));
  528. counter->supported = false;
  529. if ((counter->leader != counter) ||
  530. !(counter->leader->nr_members > 1))
  531. continue;
  532. } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  533. if (verbose > 0)
  534. ui__warning("%s\n", msg);
  535. goto try_again;
  536. }
  537. perf_evsel__open_strerror(counter, &target,
  538. errno, msg, sizeof(msg));
  539. ui__error("%s\n", msg);
  540. if (child_pid != -1)
  541. kill(child_pid, SIGTERM);
  542. return -1;
  543. }
  544. counter->supported = true;
  545. l = strlen(counter->unit);
  546. if (l > unit_width)
  547. unit_width = l;
  548. if (perf_evsel__should_store_id(counter) &&
  549. store_counter_ids(counter))
  550. return -1;
  551. }
  552. if (perf_evlist__apply_filters(evsel_list, &counter)) {
  553. pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
  554. counter->filter, perf_evsel__name(counter), errno,
  555. str_error_r(errno, msg, sizeof(msg)));
  556. return -1;
  557. }
  558. if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
  559. pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
  560. err_term->val.drv_cfg, perf_evsel__name(counter), errno,
  561. str_error_r(errno, msg, sizeof(msg)));
  562. return -1;
  563. }
  564. if (STAT_RECORD) {
  565. int err, fd = perf_data__fd(&perf_stat.data);
  566. if (is_pipe) {
  567. err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
  568. } else {
  569. err = perf_session__write_header(perf_stat.session, evsel_list,
  570. fd, false);
  571. }
  572. if (err < 0)
  573. return err;
  574. err = perf_stat_synthesize_config(is_pipe);
  575. if (err < 0)
  576. return err;
  577. }
  578. /*
  579. * Enable counters and exec the command:
  580. */
  581. t0 = rdclock();
  582. clock_gettime(CLOCK_MONOTONIC, &ref_time);
  583. if (forks) {
  584. perf_evlist__start_workload(evsel_list);
  585. enable_counters();
  586. if (interval) {
  587. while (!waitpid(child_pid, &status, WNOHANG)) {
  588. nanosleep(&ts, NULL);
  589. process_interval();
  590. }
  591. }
  592. waitpid(child_pid, &status, 0);
  593. if (workload_exec_errno) {
  594. const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
  595. pr_err("Workload failed: %s\n", emsg);
  596. return -1;
  597. }
  598. if (WIFSIGNALED(status))
  599. psignal(WTERMSIG(status), argv[0]);
  600. } else {
  601. enable_counters();
  602. while (!done) {
  603. nanosleep(&ts, NULL);
  604. if (interval)
  605. process_interval();
  606. }
  607. }
  608. disable_counters();
  609. t1 = rdclock();
  610. update_stats(&walltime_nsecs_stats, t1 - t0);
  611. /*
  612. * Closing a group leader splits the group, and as we only disable
  613. * group leaders, results in remaining events becoming enabled. To
  614. * avoid arbitrary skew, we must read all counters before closing any
  615. * group leaders.
  616. */
  617. read_counters();
  618. perf_evlist__close(evsel_list);
  619. return WEXITSTATUS(status);
  620. }
  621. static int run_perf_stat(int argc, const char **argv)
  622. {
  623. int ret;
  624. if (pre_cmd) {
  625. ret = system(pre_cmd);
  626. if (ret)
  627. return ret;
  628. }
  629. if (sync_run)
  630. sync();
  631. ret = __run_perf_stat(argc, argv);
  632. if (ret)
  633. return ret;
  634. if (post_cmd) {
  635. ret = system(post_cmd);
  636. if (ret)
  637. return ret;
  638. }
  639. return ret;
  640. }
  641. static void print_running(u64 run, u64 ena)
  642. {
  643. if (csv_output) {
  644. fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
  645. csv_sep,
  646. run,
  647. csv_sep,
  648. ena ? 100.0 * run / ena : 100.0);
  649. } else if (run != ena) {
  650. fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
  651. }
  652. }
  653. static void print_noise_pct(double total, double avg)
  654. {
  655. double pct = rel_stddev_stats(total, avg);
  656. if (csv_output)
  657. fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
  658. else if (pct)
  659. fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
  660. }
  661. static void print_noise(struct perf_evsel *evsel, double avg)
  662. {
  663. struct perf_stat_evsel *ps;
  664. if (run_count == 1)
  665. return;
  666. ps = evsel->stats;
  667. print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
  668. }
  669. static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
  670. {
  671. switch (stat_config.aggr_mode) {
  672. case AGGR_CORE:
  673. fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
  674. cpu_map__id_to_socket(id),
  675. csv_output ? 0 : -8,
  676. cpu_map__id_to_cpu(id),
  677. csv_sep,
  678. csv_output ? 0 : 4,
  679. nr,
  680. csv_sep);
  681. break;
  682. case AGGR_SOCKET:
  683. fprintf(stat_config.output, "S%*d%s%*d%s",
  684. csv_output ? 0 : -5,
  685. id,
  686. csv_sep,
  687. csv_output ? 0 : 4,
  688. nr,
  689. csv_sep);
  690. break;
  691. case AGGR_NONE:
  692. fprintf(stat_config.output, "CPU%*d%s",
  693. csv_output ? 0 : -4,
  694. perf_evsel__cpus(evsel)->map[id], csv_sep);
  695. break;
  696. case AGGR_THREAD:
  697. fprintf(stat_config.output, "%*s-%*d%s",
  698. csv_output ? 0 : 16,
  699. thread_map__comm(evsel->threads, id),
  700. csv_output ? 0 : -8,
  701. thread_map__pid(evsel->threads, id),
  702. csv_sep);
  703. break;
  704. case AGGR_GLOBAL:
  705. case AGGR_UNSET:
  706. default:
  707. break;
  708. }
  709. }
  710. struct outstate {
  711. FILE *fh;
  712. bool newline;
  713. const char *prefix;
  714. int nfields;
  715. int id, nr;
  716. struct perf_evsel *evsel;
  717. };
  718. #define METRIC_LEN 35
  719. static void new_line_std(void *ctx)
  720. {
  721. struct outstate *os = ctx;
  722. os->newline = true;
  723. }
  724. static void do_new_line_std(struct outstate *os)
  725. {
  726. fputc('\n', os->fh);
  727. fputs(os->prefix, os->fh);
  728. aggr_printout(os->evsel, os->id, os->nr);
  729. if (stat_config.aggr_mode == AGGR_NONE)
  730. fprintf(os->fh, " ");
  731. fprintf(os->fh, " ");
  732. }
  733. static void print_metric_std(void *ctx, const char *color, const char *fmt,
  734. const char *unit, double val)
  735. {
  736. struct outstate *os = ctx;
  737. FILE *out = os->fh;
  738. int n;
  739. bool newline = os->newline;
  740. os->newline = false;
  741. if (unit == NULL || fmt == NULL) {
  742. fprintf(out, "%-*s", METRIC_LEN, "");
  743. return;
  744. }
  745. if (newline)
  746. do_new_line_std(os);
  747. n = fprintf(out, " # ");
  748. if (color)
  749. n += color_fprintf(out, color, fmt, val);
  750. else
  751. n += fprintf(out, fmt, val);
  752. fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
  753. }
  754. static void new_line_csv(void *ctx)
  755. {
  756. struct outstate *os = ctx;
  757. int i;
  758. fputc('\n', os->fh);
  759. if (os->prefix)
  760. fprintf(os->fh, "%s%s", os->prefix, csv_sep);
  761. aggr_printout(os->evsel, os->id, os->nr);
  762. for (i = 0; i < os->nfields; i++)
  763. fputs(csv_sep, os->fh);
  764. }
  765. static void print_metric_csv(void *ctx,
  766. const char *color __maybe_unused,
  767. const char *fmt, const char *unit, double val)
  768. {
  769. struct outstate *os = ctx;
  770. FILE *out = os->fh;
  771. char buf[64], *vals, *ends;
  772. if (unit == NULL || fmt == NULL) {
  773. fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
  774. return;
  775. }
  776. snprintf(buf, sizeof(buf), fmt, val);
  777. ends = vals = ltrim(buf);
  778. while (isdigit(*ends) || *ends == '.')
  779. ends++;
  780. *ends = 0;
  781. while (isspace(*unit))
  782. unit++;
  783. fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
  784. }
  785. #define METRIC_ONLY_LEN 20
  786. /* Filter out some columns that don't work well in metrics only mode */
  787. static bool valid_only_metric(const char *unit)
  788. {
  789. if (!unit)
  790. return false;
  791. if (strstr(unit, "/sec") ||
  792. strstr(unit, "hz") ||
  793. strstr(unit, "Hz") ||
  794. strstr(unit, "CPUs utilized"))
  795. return false;
  796. return true;
  797. }
  798. static const char *fixunit(char *buf, struct perf_evsel *evsel,
  799. const char *unit)
  800. {
  801. if (!strncmp(unit, "of all", 6)) {
  802. snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
  803. unit);
  804. return buf;
  805. }
  806. return unit;
  807. }
  808. static void print_metric_only(void *ctx, const char *color, const char *fmt,
  809. const char *unit, double val)
  810. {
  811. struct outstate *os = ctx;
  812. FILE *out = os->fh;
  813. int n;
  814. char buf[1024];
  815. unsigned mlen = METRIC_ONLY_LEN;
  816. if (!valid_only_metric(unit))
  817. return;
  818. unit = fixunit(buf, os->evsel, unit);
  819. if (color)
  820. n = color_fprintf(out, color, fmt, val);
  821. else
  822. n = fprintf(out, fmt, val);
  823. if (n > METRIC_ONLY_LEN)
  824. n = METRIC_ONLY_LEN;
  825. if (mlen < strlen(unit))
  826. mlen = strlen(unit) + 1;
  827. fprintf(out, "%*s", mlen - n, "");
  828. }
  829. static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
  830. const char *fmt,
  831. const char *unit, double val)
  832. {
  833. struct outstate *os = ctx;
  834. FILE *out = os->fh;
  835. char buf[64], *vals, *ends;
  836. char tbuf[1024];
  837. if (!valid_only_metric(unit))
  838. return;
  839. unit = fixunit(tbuf, os->evsel, unit);
  840. snprintf(buf, sizeof buf, fmt, val);
  841. ends = vals = ltrim(buf);
  842. while (isdigit(*ends) || *ends == '.')
  843. ends++;
  844. *ends = 0;
  845. fprintf(out, "%s%s", vals, csv_sep);
  846. }
  847. static void new_line_metric(void *ctx __maybe_unused)
  848. {
  849. }
  850. static void print_metric_header(void *ctx, const char *color __maybe_unused,
  851. const char *fmt __maybe_unused,
  852. const char *unit, double val __maybe_unused)
  853. {
  854. struct outstate *os = ctx;
  855. char tbuf[1024];
  856. if (!valid_only_metric(unit))
  857. return;
  858. unit = fixunit(tbuf, os->evsel, unit);
  859. if (csv_output)
  860. fprintf(os->fh, "%s%s", unit, csv_sep);
  861. else
  862. fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
  863. }
  864. static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
  865. {
  866. FILE *output = stat_config.output;
  867. double msecs = avg / NSEC_PER_MSEC;
  868. const char *fmt_v, *fmt_n;
  869. char name[25];
  870. fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
  871. fmt_n = csv_output ? "%s" : "%-25s";
  872. aggr_printout(evsel, id, nr);
  873. scnprintf(name, sizeof(name), "%s%s",
  874. perf_evsel__name(evsel), csv_output ? "" : " (msec)");
  875. fprintf(output, fmt_v, msecs, csv_sep);
  876. if (csv_output)
  877. fprintf(output, "%s%s", evsel->unit, csv_sep);
  878. else
  879. fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
  880. fprintf(output, fmt_n, name);
  881. if (evsel->cgrp)
  882. fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
  883. }
  884. static int first_shadow_cpu(struct perf_evsel *evsel, int id)
  885. {
  886. int i;
  887. if (!aggr_get_id)
  888. return 0;
  889. if (stat_config.aggr_mode == AGGR_NONE)
  890. return id;
  891. if (stat_config.aggr_mode == AGGR_GLOBAL)
  892. return 0;
  893. for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
  894. int cpu2 = perf_evsel__cpus(evsel)->map[i];
  895. if (aggr_get_id(evsel_list->cpus, cpu2) == id)
  896. return cpu2;
  897. }
  898. return 0;
  899. }
  900. static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
  901. {
  902. FILE *output = stat_config.output;
  903. double sc = evsel->scale;
  904. const char *fmt;
  905. if (csv_output) {
  906. fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
  907. } else {
  908. if (big_num)
  909. fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
  910. else
  911. fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
  912. }
  913. aggr_printout(evsel, id, nr);
  914. fprintf(output, fmt, avg, csv_sep);
  915. if (evsel->unit)
  916. fprintf(output, "%-*s%s",
  917. csv_output ? 0 : unit_width,
  918. evsel->unit, csv_sep);
  919. fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
  920. if (evsel->cgrp)
  921. fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
  922. }
  923. static void printout(int id, int nr, struct perf_evsel *counter, double uval,
  924. char *prefix, u64 run, u64 ena, double noise,
  925. struct runtime_stat *st)
  926. {
  927. struct perf_stat_output_ctx out;
  928. struct outstate os = {
  929. .fh = stat_config.output,
  930. .prefix = prefix ? prefix : "",
  931. .id = id,
  932. .nr = nr,
  933. .evsel = counter,
  934. };
  935. print_metric_t pm = print_metric_std;
  936. void (*nl)(void *);
  937. if (metric_only) {
  938. nl = new_line_metric;
  939. if (csv_output)
  940. pm = print_metric_only_csv;
  941. else
  942. pm = print_metric_only;
  943. } else
  944. nl = new_line_std;
  945. if (csv_output && !metric_only) {
  946. static int aggr_fields[] = {
  947. [AGGR_GLOBAL] = 0,
  948. [AGGR_THREAD] = 1,
  949. [AGGR_NONE] = 1,
  950. [AGGR_SOCKET] = 2,
  951. [AGGR_CORE] = 2,
  952. };
  953. pm = print_metric_csv;
  954. nl = new_line_csv;
  955. os.nfields = 3;
  956. os.nfields += aggr_fields[stat_config.aggr_mode];
  957. if (counter->cgrp)
  958. os.nfields++;
  959. }
  960. if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
  961. if (metric_only) {
  962. pm(&os, NULL, "", "", 0);
  963. return;
  964. }
  965. aggr_printout(counter, id, nr);
  966. fprintf(stat_config.output, "%*s%s",
  967. csv_output ? 0 : 18,
  968. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  969. csv_sep);
  970. if (counter->supported)
  971. print_free_counters_hint = 1;
  972. fprintf(stat_config.output, "%-*s%s",
  973. csv_output ? 0 : unit_width,
  974. counter->unit, csv_sep);
  975. fprintf(stat_config.output, "%*s",
  976. csv_output ? 0 : -25,
  977. perf_evsel__name(counter));
  978. if (counter->cgrp)
  979. fprintf(stat_config.output, "%s%s",
  980. csv_sep, counter->cgrp->name);
  981. if (!csv_output)
  982. pm(&os, NULL, NULL, "", 0);
  983. print_noise(counter, noise);
  984. print_running(run, ena);
  985. if (csv_output)
  986. pm(&os, NULL, NULL, "", 0);
  987. return;
  988. }
  989. if (metric_only)
  990. /* nothing */;
  991. else if (nsec_counter(counter))
  992. nsec_printout(id, nr, counter, uval);
  993. else
  994. abs_printout(id, nr, counter, uval);
  995. out.print_metric = pm;
  996. out.new_line = nl;
  997. out.ctx = &os;
  998. out.force_header = false;
  999. if (csv_output && !metric_only) {
  1000. print_noise(counter, noise);
  1001. print_running(run, ena);
  1002. }
  1003. perf_stat__print_shadow_stats(counter, uval,
  1004. first_shadow_cpu(counter, id),
  1005. &out, &metric_events, st);
  1006. if (!csv_output && !metric_only) {
  1007. print_noise(counter, noise);
  1008. print_running(run, ena);
  1009. }
  1010. }
  1011. static void aggr_update_shadow(void)
  1012. {
  1013. int cpu, s2, id, s;
  1014. u64 val;
  1015. struct perf_evsel *counter;
  1016. for (s = 0; s < aggr_map->nr; s++) {
  1017. id = aggr_map->map[s];
  1018. evlist__for_each_entry(evsel_list, counter) {
  1019. val = 0;
  1020. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  1021. s2 = aggr_get_id(evsel_list->cpus, cpu);
  1022. if (s2 != id)
  1023. continue;
  1024. val += perf_counts(counter->counts, cpu, 0)->val;
  1025. }
  1026. perf_stat__update_shadow_stats(counter, val,
  1027. first_shadow_cpu(counter, id),
  1028. &rt_stat);
  1029. }
  1030. }
  1031. }
  1032. static void collect_all_aliases(struct perf_evsel *counter,
  1033. void (*cb)(struct perf_evsel *counter, void *data,
  1034. bool first),
  1035. void *data)
  1036. {
  1037. struct perf_evsel *alias;
  1038. alias = list_prepare_entry(counter, &(evsel_list->entries), node);
  1039. list_for_each_entry_continue (alias, &evsel_list->entries, node) {
  1040. if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
  1041. alias->scale != counter->scale ||
  1042. alias->cgrp != counter->cgrp ||
  1043. strcmp(alias->unit, counter->unit) ||
  1044. nsec_counter(alias) != nsec_counter(counter))
  1045. break;
  1046. alias->merged_stat = true;
  1047. cb(alias, data, false);
  1048. }
  1049. }
  1050. static bool collect_data(struct perf_evsel *counter,
  1051. void (*cb)(struct perf_evsel *counter, void *data,
  1052. bool first),
  1053. void *data)
  1054. {
  1055. if (counter->merged_stat)
  1056. return false;
  1057. cb(counter, data, true);
  1058. if (!no_merge && counter->auto_merge_stats)
  1059. collect_all_aliases(counter, cb, data);
  1060. return true;
  1061. }
  1062. struct aggr_data {
  1063. u64 ena, run, val;
  1064. int id;
  1065. int nr;
  1066. int cpu;
  1067. };
  1068. static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
  1069. {
  1070. struct aggr_data *ad = data;
  1071. int cpu, s2;
  1072. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  1073. struct perf_counts_values *counts;
  1074. s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
  1075. if (s2 != ad->id)
  1076. continue;
  1077. if (first)
  1078. ad->nr++;
  1079. counts = perf_counts(counter->counts, cpu, 0);
  1080. /*
  1081. * When any result is bad, make them all to give
  1082. * consistent output in interval mode.
  1083. */
  1084. if (counts->ena == 0 || counts->run == 0 ||
  1085. counter->counts->scaled == -1) {
  1086. ad->ena = 0;
  1087. ad->run = 0;
  1088. break;
  1089. }
  1090. ad->val += counts->val;
  1091. ad->ena += counts->ena;
  1092. ad->run += counts->run;
  1093. }
  1094. }
  1095. static void print_aggr(char *prefix)
  1096. {
  1097. FILE *output = stat_config.output;
  1098. struct perf_evsel *counter;
  1099. int s, id, nr;
  1100. double uval;
  1101. u64 ena, run, val;
  1102. bool first;
  1103. if (!(aggr_map || aggr_get_id))
  1104. return;
  1105. aggr_update_shadow();
  1106. /*
  1107. * With metric_only everything is on a single line.
  1108. * Without each counter has its own line.
  1109. */
  1110. for (s = 0; s < aggr_map->nr; s++) {
  1111. struct aggr_data ad;
  1112. if (prefix && metric_only)
  1113. fprintf(output, "%s", prefix);
  1114. ad.id = id = aggr_map->map[s];
  1115. first = true;
  1116. evlist__for_each_entry(evsel_list, counter) {
  1117. if (is_duration_time(counter))
  1118. continue;
  1119. ad.val = ad.ena = ad.run = 0;
  1120. ad.nr = 0;
  1121. if (!collect_data(counter, aggr_cb, &ad))
  1122. continue;
  1123. nr = ad.nr;
  1124. ena = ad.ena;
  1125. run = ad.run;
  1126. val = ad.val;
  1127. if (first && metric_only) {
  1128. first = false;
  1129. aggr_printout(counter, id, nr);
  1130. }
  1131. if (prefix && !metric_only)
  1132. fprintf(output, "%s", prefix);
  1133. uval = val * counter->scale;
  1134. printout(id, nr, counter, uval, prefix, run, ena, 1.0,
  1135. &rt_stat);
  1136. if (!metric_only)
  1137. fputc('\n', output);
  1138. }
  1139. if (metric_only)
  1140. fputc('\n', output);
  1141. }
  1142. }
  1143. static int cmp_val(const void *a, const void *b)
  1144. {
  1145. return ((struct perf_aggr_thread_value *)b)->val -
  1146. ((struct perf_aggr_thread_value *)a)->val;
  1147. }
  1148. static struct perf_aggr_thread_value *sort_aggr_thread(
  1149. struct perf_evsel *counter,
  1150. int nthreads, int ncpus,
  1151. int *ret)
  1152. {
  1153. int cpu, thread, i = 0;
  1154. double uval;
  1155. struct perf_aggr_thread_value *buf;
  1156. buf = calloc(nthreads, sizeof(struct perf_aggr_thread_value));
  1157. if (!buf)
  1158. return NULL;
  1159. for (thread = 0; thread < nthreads; thread++) {
  1160. u64 ena = 0, run = 0, val = 0;
  1161. for (cpu = 0; cpu < ncpus; cpu++) {
  1162. val += perf_counts(counter->counts, cpu, thread)->val;
  1163. ena += perf_counts(counter->counts, cpu, thread)->ena;
  1164. run += perf_counts(counter->counts, cpu, thread)->run;
  1165. }
  1166. uval = val * counter->scale;
  1167. /*
  1168. * Skip value 0 when enabling --per-thread globally,
  1169. * otherwise too many 0 output.
  1170. */
  1171. if (uval == 0.0 && target__has_per_thread(&target))
  1172. continue;
  1173. buf[i].counter = counter;
  1174. buf[i].id = thread;
  1175. buf[i].uval = uval;
  1176. buf[i].val = val;
  1177. buf[i].run = run;
  1178. buf[i].ena = ena;
  1179. i++;
  1180. }
  1181. qsort(buf, i, sizeof(struct perf_aggr_thread_value), cmp_val);
  1182. if (ret)
  1183. *ret = i;
  1184. return buf;
  1185. }
  1186. static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
  1187. {
  1188. FILE *output = stat_config.output;
  1189. int nthreads = thread_map__nr(counter->threads);
  1190. int ncpus = cpu_map__nr(counter->cpus);
  1191. int thread, sorted_threads, id;
  1192. struct perf_aggr_thread_value *buf;
  1193. buf = sort_aggr_thread(counter, nthreads, ncpus, &sorted_threads);
  1194. if (!buf) {
  1195. perror("cannot sort aggr thread");
  1196. return;
  1197. }
  1198. for (thread = 0; thread < sorted_threads; thread++) {
  1199. if (prefix)
  1200. fprintf(output, "%s", prefix);
  1201. id = buf[thread].id;
  1202. if (stat_config.stats)
  1203. printout(id, 0, buf[thread].counter, buf[thread].uval,
  1204. prefix, buf[thread].run, buf[thread].ena, 1.0,
  1205. &stat_config.stats[id]);
  1206. else
  1207. printout(id, 0, buf[thread].counter, buf[thread].uval,
  1208. prefix, buf[thread].run, buf[thread].ena, 1.0,
  1209. &rt_stat);
  1210. fputc('\n', output);
  1211. }
  1212. free(buf);
  1213. }
  1214. struct caggr_data {
  1215. double avg, avg_enabled, avg_running;
  1216. };
  1217. static void counter_aggr_cb(struct perf_evsel *counter, void *data,
  1218. bool first __maybe_unused)
  1219. {
  1220. struct caggr_data *cd = data;
  1221. struct perf_stat_evsel *ps = counter->stats;
  1222. cd->avg += avg_stats(&ps->res_stats[0]);
  1223. cd->avg_enabled += avg_stats(&ps->res_stats[1]);
  1224. cd->avg_running += avg_stats(&ps->res_stats[2]);
  1225. }
  1226. /*
  1227. * Print out the results of a single counter:
  1228. * aggregated counts in system-wide mode
  1229. */
  1230. static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
  1231. {
  1232. FILE *output = stat_config.output;
  1233. double uval;
  1234. struct caggr_data cd = { .avg = 0.0 };
  1235. if (!collect_data(counter, counter_aggr_cb, &cd))
  1236. return;
  1237. if (prefix && !metric_only)
  1238. fprintf(output, "%s", prefix);
  1239. uval = cd.avg * counter->scale;
  1240. printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled,
  1241. cd.avg, &rt_stat);
  1242. if (!metric_only)
  1243. fprintf(output, "\n");
  1244. }
  1245. static void counter_cb(struct perf_evsel *counter, void *data,
  1246. bool first __maybe_unused)
  1247. {
  1248. struct aggr_data *ad = data;
  1249. ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
  1250. ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
  1251. ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
  1252. }
  1253. /*
  1254. * Print out the results of a single counter:
  1255. * does not use aggregated count in system-wide
  1256. */
  1257. static void print_counter(struct perf_evsel *counter, char *prefix)
  1258. {
  1259. FILE *output = stat_config.output;
  1260. u64 ena, run, val;
  1261. double uval;
  1262. int cpu;
  1263. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  1264. struct aggr_data ad = { .cpu = cpu };
  1265. if (!collect_data(counter, counter_cb, &ad))
  1266. return;
  1267. val = ad.val;
  1268. ena = ad.ena;
  1269. run = ad.run;
  1270. if (prefix)
  1271. fprintf(output, "%s", prefix);
  1272. uval = val * counter->scale;
  1273. printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
  1274. &rt_stat);
  1275. fputc('\n', output);
  1276. }
  1277. }
  1278. static void print_no_aggr_metric(char *prefix)
  1279. {
  1280. int cpu;
  1281. int nrcpus = 0;
  1282. struct perf_evsel *counter;
  1283. u64 ena, run, val;
  1284. double uval;
  1285. nrcpus = evsel_list->cpus->nr;
  1286. for (cpu = 0; cpu < nrcpus; cpu++) {
  1287. bool first = true;
  1288. if (prefix)
  1289. fputs(prefix, stat_config.output);
  1290. evlist__for_each_entry(evsel_list, counter) {
  1291. if (is_duration_time(counter))
  1292. continue;
  1293. if (first) {
  1294. aggr_printout(counter, cpu, 0);
  1295. first = false;
  1296. }
  1297. val = perf_counts(counter->counts, cpu, 0)->val;
  1298. ena = perf_counts(counter->counts, cpu, 0)->ena;
  1299. run = perf_counts(counter->counts, cpu, 0)->run;
  1300. uval = val * counter->scale;
  1301. printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
  1302. &rt_stat);
  1303. }
  1304. fputc('\n', stat_config.output);
  1305. }
  1306. }
  1307. static int aggr_header_lens[] = {
  1308. [AGGR_CORE] = 18,
  1309. [AGGR_SOCKET] = 12,
  1310. [AGGR_NONE] = 6,
  1311. [AGGR_THREAD] = 24,
  1312. [AGGR_GLOBAL] = 0,
  1313. };
  1314. static const char *aggr_header_csv[] = {
  1315. [AGGR_CORE] = "core,cpus,",
  1316. [AGGR_SOCKET] = "socket,cpus",
  1317. [AGGR_NONE] = "cpu,",
  1318. [AGGR_THREAD] = "comm-pid,",
  1319. [AGGR_GLOBAL] = ""
  1320. };
  1321. static void print_metric_headers(const char *prefix, bool no_indent)
  1322. {
  1323. struct perf_stat_output_ctx out;
  1324. struct perf_evsel *counter;
  1325. struct outstate os = {
  1326. .fh = stat_config.output
  1327. };
  1328. if (prefix)
  1329. fprintf(stat_config.output, "%s", prefix);
  1330. if (!csv_output && !no_indent)
  1331. fprintf(stat_config.output, "%*s",
  1332. aggr_header_lens[stat_config.aggr_mode], "");
  1333. if (csv_output) {
  1334. if (stat_config.interval)
  1335. fputs("time,", stat_config.output);
  1336. fputs(aggr_header_csv[stat_config.aggr_mode],
  1337. stat_config.output);
  1338. }
  1339. /* Print metrics headers only */
  1340. evlist__for_each_entry(evsel_list, counter) {
  1341. if (is_duration_time(counter))
  1342. continue;
  1343. os.evsel = counter;
  1344. out.ctx = &os;
  1345. out.print_metric = print_metric_header;
  1346. out.new_line = new_line_metric;
  1347. out.force_header = true;
  1348. os.evsel = counter;
  1349. perf_stat__print_shadow_stats(counter, 0,
  1350. 0,
  1351. &out,
  1352. &metric_events,
  1353. &rt_stat);
  1354. }
  1355. fputc('\n', stat_config.output);
  1356. }
  1357. static void print_interval(char *prefix, struct timespec *ts)
  1358. {
  1359. FILE *output = stat_config.output;
  1360. static int num_print_interval;
  1361. sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
  1362. if (num_print_interval == 0 && !csv_output) {
  1363. switch (stat_config.aggr_mode) {
  1364. case AGGR_SOCKET:
  1365. fprintf(output, "# time socket cpus");
  1366. if (!metric_only)
  1367. fprintf(output, " counts %*s events\n", unit_width, "unit");
  1368. break;
  1369. case AGGR_CORE:
  1370. fprintf(output, "# time core cpus");
  1371. if (!metric_only)
  1372. fprintf(output, " counts %*s events\n", unit_width, "unit");
  1373. break;
  1374. case AGGR_NONE:
  1375. fprintf(output, "# time CPU");
  1376. if (!metric_only)
  1377. fprintf(output, " counts %*s events\n", unit_width, "unit");
  1378. break;
  1379. case AGGR_THREAD:
  1380. fprintf(output, "# time comm-pid");
  1381. if (!metric_only)
  1382. fprintf(output, " counts %*s events\n", unit_width, "unit");
  1383. break;
  1384. case AGGR_GLOBAL:
  1385. default:
  1386. fprintf(output, "# time");
  1387. if (!metric_only)
  1388. fprintf(output, " counts %*s events\n", unit_width, "unit");
  1389. case AGGR_UNSET:
  1390. break;
  1391. }
  1392. }
  1393. if (num_print_interval == 0 && metric_only)
  1394. print_metric_headers(" ", true);
  1395. if (++num_print_interval == 25)
  1396. num_print_interval = 0;
  1397. }
  1398. static void print_header(int argc, const char **argv)
  1399. {
  1400. FILE *output = stat_config.output;
  1401. int i;
  1402. fflush(stdout);
  1403. if (!csv_output) {
  1404. fprintf(output, "\n");
  1405. fprintf(output, " Performance counter stats for ");
  1406. if (target.system_wide)
  1407. fprintf(output, "\'system wide");
  1408. else if (target.cpu_list)
  1409. fprintf(output, "\'CPU(s) %s", target.cpu_list);
  1410. else if (!target__has_task(&target)) {
  1411. fprintf(output, "\'%s", argv ? argv[0] : "pipe");
  1412. for (i = 1; argv && (i < argc); i++)
  1413. fprintf(output, " %s", argv[i]);
  1414. } else if (target.pid)
  1415. fprintf(output, "process id \'%s", target.pid);
  1416. else
  1417. fprintf(output, "thread id \'%s", target.tid);
  1418. fprintf(output, "\'");
  1419. if (run_count > 1)
  1420. fprintf(output, " (%d runs)", run_count);
  1421. fprintf(output, ":\n\n");
  1422. }
  1423. }
  1424. static void print_footer(void)
  1425. {
  1426. FILE *output = stat_config.output;
  1427. int n;
  1428. if (!null_run)
  1429. fprintf(output, "\n");
  1430. fprintf(output, " %17.9f seconds time elapsed",
  1431. avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
  1432. if (run_count > 1) {
  1433. fprintf(output, " ");
  1434. print_noise_pct(stddev_stats(&walltime_nsecs_stats),
  1435. avg_stats(&walltime_nsecs_stats));
  1436. }
  1437. fprintf(output, "\n\n");
  1438. if (print_free_counters_hint &&
  1439. sysctl__read_int("kernel/nmi_watchdog", &n) >= 0 &&
  1440. n > 0)
  1441. fprintf(output,
  1442. "Some events weren't counted. Try disabling the NMI watchdog:\n"
  1443. " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
  1444. " perf stat ...\n"
  1445. " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
  1446. }
  1447. static void print_counters(struct timespec *ts, int argc, const char **argv)
  1448. {
  1449. int interval = stat_config.interval;
  1450. struct perf_evsel *counter;
  1451. char buf[64], *prefix = NULL;
  1452. /* Do not print anything if we record to the pipe. */
  1453. if (STAT_RECORD && perf_stat.data.is_pipe)
  1454. return;
  1455. if (interval)
  1456. print_interval(prefix = buf, ts);
  1457. else
  1458. print_header(argc, argv);
  1459. if (metric_only) {
  1460. static int num_print_iv;
  1461. if (num_print_iv == 0 && !interval)
  1462. print_metric_headers(prefix, false);
  1463. if (num_print_iv++ == 25)
  1464. num_print_iv = 0;
  1465. if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
  1466. fprintf(stat_config.output, "%s", prefix);
  1467. }
  1468. switch (stat_config.aggr_mode) {
  1469. case AGGR_CORE:
  1470. case AGGR_SOCKET:
  1471. print_aggr(prefix);
  1472. break;
  1473. case AGGR_THREAD:
  1474. evlist__for_each_entry(evsel_list, counter) {
  1475. if (is_duration_time(counter))
  1476. continue;
  1477. print_aggr_thread(counter, prefix);
  1478. }
  1479. break;
  1480. case AGGR_GLOBAL:
  1481. evlist__for_each_entry(evsel_list, counter) {
  1482. if (is_duration_time(counter))
  1483. continue;
  1484. print_counter_aggr(counter, prefix);
  1485. }
  1486. if (metric_only)
  1487. fputc('\n', stat_config.output);
  1488. break;
  1489. case AGGR_NONE:
  1490. if (metric_only)
  1491. print_no_aggr_metric(prefix);
  1492. else {
  1493. evlist__for_each_entry(evsel_list, counter) {
  1494. if (is_duration_time(counter))
  1495. continue;
  1496. print_counter(counter, prefix);
  1497. }
  1498. }
  1499. break;
  1500. case AGGR_UNSET:
  1501. default:
  1502. break;
  1503. }
  1504. if (!interval && !csv_output)
  1505. print_footer();
  1506. fflush(stat_config.output);
  1507. }
  1508. static volatile int signr = -1;
  1509. static void skip_signal(int signo)
  1510. {
  1511. if ((child_pid == -1) || stat_config.interval)
  1512. done = 1;
  1513. signr = signo;
  1514. /*
  1515. * render child_pid harmless
  1516. * won't send SIGTERM to a random
  1517. * process in case of race condition
  1518. * and fast PID recycling
  1519. */
  1520. child_pid = -1;
  1521. }
  1522. static void sig_atexit(void)
  1523. {
  1524. sigset_t set, oset;
  1525. /*
  1526. * avoid race condition with SIGCHLD handler
  1527. * in skip_signal() which is modifying child_pid
  1528. * goal is to avoid send SIGTERM to a random
  1529. * process
  1530. */
  1531. sigemptyset(&set);
  1532. sigaddset(&set, SIGCHLD);
  1533. sigprocmask(SIG_BLOCK, &set, &oset);
  1534. if (child_pid != -1)
  1535. kill(child_pid, SIGTERM);
  1536. sigprocmask(SIG_SETMASK, &oset, NULL);
  1537. if (signr == -1)
  1538. return;
  1539. signal(signr, SIG_DFL);
  1540. kill(getpid(), signr);
  1541. }
  1542. static int stat__set_big_num(const struct option *opt __maybe_unused,
  1543. const char *s __maybe_unused, int unset)
  1544. {
  1545. big_num_opt = unset ? 0 : 1;
  1546. return 0;
  1547. }
  1548. static int enable_metric_only(const struct option *opt __maybe_unused,
  1549. const char *s __maybe_unused, int unset)
  1550. {
  1551. force_metric_only = true;
  1552. metric_only = !unset;
  1553. return 0;
  1554. }
  1555. static int parse_metric_groups(const struct option *opt,
  1556. const char *str,
  1557. int unset __maybe_unused)
  1558. {
  1559. return metricgroup__parse_groups(opt, str, &metric_events);
  1560. }
  1561. static const struct option stat_options[] = {
  1562. OPT_BOOLEAN('T', "transaction", &transaction_run,
  1563. "hardware transaction statistics"),
  1564. OPT_CALLBACK('e', "event", &evsel_list, "event",
  1565. "event selector. use 'perf list' to list available events",
  1566. parse_events_option),
  1567. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  1568. "event filter", parse_filter),
  1569. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  1570. "child tasks do not inherit counters"),
  1571. OPT_STRING('p', "pid", &target.pid, "pid",
  1572. "stat events on existing process id"),
  1573. OPT_STRING('t', "tid", &target.tid, "tid",
  1574. "stat events on existing thread id"),
  1575. OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
  1576. "system-wide collection from all CPUs"),
  1577. OPT_BOOLEAN('g', "group", &group,
  1578. "put the counters into a counter group"),
  1579. OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
  1580. OPT_INCR('v', "verbose", &verbose,
  1581. "be more verbose (show counter open errors, etc)"),
  1582. OPT_INTEGER('r', "repeat", &run_count,
  1583. "repeat command and print average + stddev (max: 100, forever: 0)"),
  1584. OPT_BOOLEAN('n', "null", &null_run,
  1585. "null run - dont start any counters"),
  1586. OPT_INCR('d', "detailed", &detailed_run,
  1587. "detailed run - start a lot of events"),
  1588. OPT_BOOLEAN('S', "sync", &sync_run,
  1589. "call sync() before starting a run"),
  1590. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  1591. "print large numbers with thousands\' separators",
  1592. stat__set_big_num),
  1593. OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
  1594. "list of cpus to monitor in system-wide"),
  1595. OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
  1596. "disable CPU count aggregation", AGGR_NONE),
  1597. OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
  1598. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  1599. "print counts with custom separator"),
  1600. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  1601. "monitor event in cgroup name only", parse_cgroups),
  1602. OPT_STRING('o', "output", &output_name, "file", "output file name"),
  1603. OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
  1604. OPT_INTEGER(0, "log-fd", &output_fd,
  1605. "log output to fd, instead of stderr"),
  1606. OPT_STRING(0, "pre", &pre_cmd, "command",
  1607. "command to run prior to the measured command"),
  1608. OPT_STRING(0, "post", &post_cmd, "command",
  1609. "command to run after to the measured command"),
  1610. OPT_UINTEGER('I', "interval-print", &stat_config.interval,
  1611. "print counts at regular interval in ms (>= 10)"),
  1612. OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
  1613. "aggregate counts per processor socket", AGGR_SOCKET),
  1614. OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
  1615. "aggregate counts per physical processor core", AGGR_CORE),
  1616. OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
  1617. "aggregate counts per thread", AGGR_THREAD),
  1618. OPT_UINTEGER('D', "delay", &initial_delay,
  1619. "ms to wait before starting measurement after program start"),
  1620. OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
  1621. "Only print computed metrics. No raw values", enable_metric_only),
  1622. OPT_BOOLEAN(0, "topdown", &topdown_run,
  1623. "measure topdown level 1 statistics"),
  1624. OPT_BOOLEAN(0, "smi-cost", &smi_cost,
  1625. "measure SMI cost"),
  1626. OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
  1627. "monitor specified metrics or metric groups (separated by ,)",
  1628. parse_metric_groups),
  1629. OPT_END()
  1630. };
  1631. static int perf_stat__get_socket(struct cpu_map *map, int cpu)
  1632. {
  1633. return cpu_map__get_socket(map, cpu, NULL);
  1634. }
  1635. static int perf_stat__get_core(struct cpu_map *map, int cpu)
  1636. {
  1637. return cpu_map__get_core(map, cpu, NULL);
  1638. }
  1639. static int cpu_map__get_max(struct cpu_map *map)
  1640. {
  1641. int i, max = -1;
  1642. for (i = 0; i < map->nr; i++) {
  1643. if (map->map[i] > max)
  1644. max = map->map[i];
  1645. }
  1646. return max;
  1647. }
  1648. static struct cpu_map *cpus_aggr_map;
  1649. static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
  1650. {
  1651. int cpu;
  1652. if (idx >= map->nr)
  1653. return -1;
  1654. cpu = map->map[idx];
  1655. if (cpus_aggr_map->map[cpu] == -1)
  1656. cpus_aggr_map->map[cpu] = get_id(map, idx);
  1657. return cpus_aggr_map->map[cpu];
  1658. }
  1659. static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
  1660. {
  1661. return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
  1662. }
  1663. static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
  1664. {
  1665. return perf_stat__get_aggr(perf_stat__get_core, map, idx);
  1666. }
  1667. static int perf_stat_init_aggr_mode(void)
  1668. {
  1669. int nr;
  1670. switch (stat_config.aggr_mode) {
  1671. case AGGR_SOCKET:
  1672. if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
  1673. perror("cannot build socket map");
  1674. return -1;
  1675. }
  1676. aggr_get_id = perf_stat__get_socket_cached;
  1677. break;
  1678. case AGGR_CORE:
  1679. if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
  1680. perror("cannot build core map");
  1681. return -1;
  1682. }
  1683. aggr_get_id = perf_stat__get_core_cached;
  1684. break;
  1685. case AGGR_NONE:
  1686. case AGGR_GLOBAL:
  1687. case AGGR_THREAD:
  1688. case AGGR_UNSET:
  1689. default:
  1690. break;
  1691. }
  1692. /*
  1693. * The evsel_list->cpus is the base we operate on,
  1694. * taking the highest cpu number to be the size of
  1695. * the aggregation translate cpumap.
  1696. */
  1697. nr = cpu_map__get_max(evsel_list->cpus);
  1698. cpus_aggr_map = cpu_map__empty_new(nr + 1);
  1699. return cpus_aggr_map ? 0 : -ENOMEM;
  1700. }
  1701. static void perf_stat__exit_aggr_mode(void)
  1702. {
  1703. cpu_map__put(aggr_map);
  1704. cpu_map__put(cpus_aggr_map);
  1705. aggr_map = NULL;
  1706. cpus_aggr_map = NULL;
  1707. }
  1708. static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
  1709. {
  1710. int cpu;
  1711. if (idx > map->nr)
  1712. return -1;
  1713. cpu = map->map[idx];
  1714. if (cpu >= env->nr_cpus_avail)
  1715. return -1;
  1716. return cpu;
  1717. }
  1718. static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
  1719. {
  1720. struct perf_env *env = data;
  1721. int cpu = perf_env__get_cpu(env, map, idx);
  1722. return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
  1723. }
  1724. static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
  1725. {
  1726. struct perf_env *env = data;
  1727. int core = -1, cpu = perf_env__get_cpu(env, map, idx);
  1728. if (cpu != -1) {
  1729. int socket_id = env->cpu[cpu].socket_id;
  1730. /*
  1731. * Encode socket in upper 16 bits
  1732. * core_id is relative to socket, and
  1733. * we need a global id. So we combine
  1734. * socket + core id.
  1735. */
  1736. core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
  1737. }
  1738. return core;
  1739. }
  1740. static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
  1741. struct cpu_map **sockp)
  1742. {
  1743. return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
  1744. }
  1745. static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
  1746. struct cpu_map **corep)
  1747. {
  1748. return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
  1749. }
  1750. static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
  1751. {
  1752. return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
  1753. }
  1754. static int perf_stat__get_core_file(struct cpu_map *map, int idx)
  1755. {
  1756. return perf_env__get_core(map, idx, &perf_stat.session->header.env);
  1757. }
  1758. static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
  1759. {
  1760. struct perf_env *env = &st->session->header.env;
  1761. switch (stat_config.aggr_mode) {
  1762. case AGGR_SOCKET:
  1763. if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
  1764. perror("cannot build socket map");
  1765. return -1;
  1766. }
  1767. aggr_get_id = perf_stat__get_socket_file;
  1768. break;
  1769. case AGGR_CORE:
  1770. if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
  1771. perror("cannot build core map");
  1772. return -1;
  1773. }
  1774. aggr_get_id = perf_stat__get_core_file;
  1775. break;
  1776. case AGGR_NONE:
  1777. case AGGR_GLOBAL:
  1778. case AGGR_THREAD:
  1779. case AGGR_UNSET:
  1780. default:
  1781. break;
  1782. }
  1783. return 0;
  1784. }
  1785. static int topdown_filter_events(const char **attr, char **str, bool use_group)
  1786. {
  1787. int off = 0;
  1788. int i;
  1789. int len = 0;
  1790. char *s;
  1791. for (i = 0; attr[i]; i++) {
  1792. if (pmu_have_event("cpu", attr[i])) {
  1793. len += strlen(attr[i]) + 1;
  1794. attr[i - off] = attr[i];
  1795. } else
  1796. off++;
  1797. }
  1798. attr[i - off] = NULL;
  1799. *str = malloc(len + 1 + 2);
  1800. if (!*str)
  1801. return -1;
  1802. s = *str;
  1803. if (i - off == 0) {
  1804. *s = 0;
  1805. return 0;
  1806. }
  1807. if (use_group)
  1808. *s++ = '{';
  1809. for (i = 0; attr[i]; i++) {
  1810. strcpy(s, attr[i]);
  1811. s += strlen(s);
  1812. *s++ = ',';
  1813. }
  1814. if (use_group) {
  1815. s[-1] = '}';
  1816. *s = 0;
  1817. } else
  1818. s[-1] = 0;
  1819. return 0;
  1820. }
  1821. __weak bool arch_topdown_check_group(bool *warn)
  1822. {
  1823. *warn = false;
  1824. return false;
  1825. }
  1826. __weak void arch_topdown_group_warn(void)
  1827. {
  1828. }
  1829. /*
  1830. * Add default attributes, if there were no attributes specified or
  1831. * if -d/--detailed, -d -d or -d -d -d is used:
  1832. */
  1833. static int add_default_attributes(void)
  1834. {
  1835. int err;
  1836. struct perf_event_attr default_attrs0[] = {
  1837. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  1838. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  1839. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  1840. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  1841. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  1842. };
  1843. struct perf_event_attr frontend_attrs[] = {
  1844. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
  1845. };
  1846. struct perf_event_attr backend_attrs[] = {
  1847. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
  1848. };
  1849. struct perf_event_attr default_attrs1[] = {
  1850. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  1851. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  1852. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  1853. };
  1854. /*
  1855. * Detailed stats (-d), covering the L1 and last level data caches:
  1856. */
  1857. struct perf_event_attr detailed_attrs[] = {
  1858. { .type = PERF_TYPE_HW_CACHE,
  1859. .config =
  1860. PERF_COUNT_HW_CACHE_L1D << 0 |
  1861. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1862. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1863. { .type = PERF_TYPE_HW_CACHE,
  1864. .config =
  1865. PERF_COUNT_HW_CACHE_L1D << 0 |
  1866. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1867. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1868. { .type = PERF_TYPE_HW_CACHE,
  1869. .config =
  1870. PERF_COUNT_HW_CACHE_LL << 0 |
  1871. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1872. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1873. { .type = PERF_TYPE_HW_CACHE,
  1874. .config =
  1875. PERF_COUNT_HW_CACHE_LL << 0 |
  1876. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1877. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1878. };
  1879. /*
  1880. * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
  1881. */
  1882. struct perf_event_attr very_detailed_attrs[] = {
  1883. { .type = PERF_TYPE_HW_CACHE,
  1884. .config =
  1885. PERF_COUNT_HW_CACHE_L1I << 0 |
  1886. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1887. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1888. { .type = PERF_TYPE_HW_CACHE,
  1889. .config =
  1890. PERF_COUNT_HW_CACHE_L1I << 0 |
  1891. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1892. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1893. { .type = PERF_TYPE_HW_CACHE,
  1894. .config =
  1895. PERF_COUNT_HW_CACHE_DTLB << 0 |
  1896. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1897. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1898. { .type = PERF_TYPE_HW_CACHE,
  1899. .config =
  1900. PERF_COUNT_HW_CACHE_DTLB << 0 |
  1901. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1902. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1903. { .type = PERF_TYPE_HW_CACHE,
  1904. .config =
  1905. PERF_COUNT_HW_CACHE_ITLB << 0 |
  1906. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1907. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1908. { .type = PERF_TYPE_HW_CACHE,
  1909. .config =
  1910. PERF_COUNT_HW_CACHE_ITLB << 0 |
  1911. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1912. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1913. };
  1914. /*
  1915. * Very, very detailed stats (-d -d -d), adding prefetch events:
  1916. */
  1917. struct perf_event_attr very_very_detailed_attrs[] = {
  1918. { .type = PERF_TYPE_HW_CACHE,
  1919. .config =
  1920. PERF_COUNT_HW_CACHE_L1D << 0 |
  1921. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  1922. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1923. { .type = PERF_TYPE_HW_CACHE,
  1924. .config =
  1925. PERF_COUNT_HW_CACHE_L1D << 0 |
  1926. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  1927. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1928. };
  1929. /* Set attrs if no event is selected and !null_run: */
  1930. if (null_run)
  1931. return 0;
  1932. if (transaction_run) {
  1933. if (pmu_have_event("cpu", "cycles-ct") &&
  1934. pmu_have_event("cpu", "el-start"))
  1935. err = parse_events(evsel_list, transaction_attrs, NULL);
  1936. else
  1937. err = parse_events(evsel_list, transaction_limited_attrs, NULL);
  1938. if (err) {
  1939. fprintf(stderr, "Cannot set up transaction events\n");
  1940. return -1;
  1941. }
  1942. return 0;
  1943. }
  1944. if (smi_cost) {
  1945. int smi;
  1946. if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
  1947. fprintf(stderr, "freeze_on_smi is not supported.\n");
  1948. return -1;
  1949. }
  1950. if (!smi) {
  1951. if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
  1952. fprintf(stderr, "Failed to set freeze_on_smi.\n");
  1953. return -1;
  1954. }
  1955. smi_reset = true;
  1956. }
  1957. if (pmu_have_event("msr", "aperf") &&
  1958. pmu_have_event("msr", "smi")) {
  1959. if (!force_metric_only)
  1960. metric_only = true;
  1961. err = parse_events(evsel_list, smi_cost_attrs, NULL);
  1962. } else {
  1963. fprintf(stderr, "To measure SMI cost, it needs "
  1964. "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
  1965. return -1;
  1966. }
  1967. if (err) {
  1968. fprintf(stderr, "Cannot set up SMI cost events\n");
  1969. return -1;
  1970. }
  1971. return 0;
  1972. }
  1973. if (topdown_run) {
  1974. char *str = NULL;
  1975. bool warn = false;
  1976. if (stat_config.aggr_mode != AGGR_GLOBAL &&
  1977. stat_config.aggr_mode != AGGR_CORE) {
  1978. pr_err("top down event configuration requires --per-core mode\n");
  1979. return -1;
  1980. }
  1981. stat_config.aggr_mode = AGGR_CORE;
  1982. if (nr_cgroups || !target__has_cpu(&target)) {
  1983. pr_err("top down event configuration requires system-wide mode (-a)\n");
  1984. return -1;
  1985. }
  1986. if (!force_metric_only)
  1987. metric_only = true;
  1988. if (topdown_filter_events(topdown_attrs, &str,
  1989. arch_topdown_check_group(&warn)) < 0) {
  1990. pr_err("Out of memory\n");
  1991. return -1;
  1992. }
  1993. if (topdown_attrs[0] && str) {
  1994. if (warn)
  1995. arch_topdown_group_warn();
  1996. err = parse_events(evsel_list, str, NULL);
  1997. if (err) {
  1998. fprintf(stderr,
  1999. "Cannot set up top down events %s: %d\n",
  2000. str, err);
  2001. free(str);
  2002. return -1;
  2003. }
  2004. } else {
  2005. fprintf(stderr, "System does not support topdown\n");
  2006. return -1;
  2007. }
  2008. free(str);
  2009. }
  2010. if (!evsel_list->nr_entries) {
  2011. if (target__has_cpu(&target))
  2012. default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
  2013. if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
  2014. return -1;
  2015. if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
  2016. if (perf_evlist__add_default_attrs(evsel_list,
  2017. frontend_attrs) < 0)
  2018. return -1;
  2019. }
  2020. if (pmu_have_event("cpu", "stalled-cycles-backend")) {
  2021. if (perf_evlist__add_default_attrs(evsel_list,
  2022. backend_attrs) < 0)
  2023. return -1;
  2024. }
  2025. if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
  2026. return -1;
  2027. }
  2028. /* Detailed events get appended to the event list: */
  2029. if (detailed_run < 1)
  2030. return 0;
  2031. /* Append detailed run extra attributes: */
  2032. if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
  2033. return -1;
  2034. if (detailed_run < 2)
  2035. return 0;
  2036. /* Append very detailed run extra attributes: */
  2037. if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
  2038. return -1;
  2039. if (detailed_run < 3)
  2040. return 0;
  2041. /* Append very, very detailed run extra attributes: */
  2042. return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
  2043. }
  2044. static const char * const stat_record_usage[] = {
  2045. "perf stat record [<options>]",
  2046. NULL,
  2047. };
  2048. static void init_features(struct perf_session *session)
  2049. {
  2050. int feat;
  2051. for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
  2052. perf_header__set_feat(&session->header, feat);
  2053. perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
  2054. perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
  2055. perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
  2056. perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
  2057. }
  2058. static int __cmd_record(int argc, const char **argv)
  2059. {
  2060. struct perf_session *session;
  2061. struct perf_data *data = &perf_stat.data;
  2062. argc = parse_options(argc, argv, stat_options, stat_record_usage,
  2063. PARSE_OPT_STOP_AT_NON_OPTION);
  2064. if (output_name)
  2065. data->file.path = output_name;
  2066. if (run_count != 1 || forever) {
  2067. pr_err("Cannot use -r option with perf stat record.\n");
  2068. return -1;
  2069. }
  2070. session = perf_session__new(data, false, NULL);
  2071. if (session == NULL) {
  2072. pr_err("Perf session creation failed.\n");
  2073. return -1;
  2074. }
  2075. init_features(session);
  2076. session->evlist = evsel_list;
  2077. perf_stat.session = session;
  2078. perf_stat.record = true;
  2079. return argc;
  2080. }
  2081. static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
  2082. union perf_event *event,
  2083. struct perf_session *session)
  2084. {
  2085. struct stat_round_event *stat_round = &event->stat_round;
  2086. struct perf_evsel *counter;
  2087. struct timespec tsh, *ts = NULL;
  2088. const char **argv = session->header.env.cmdline_argv;
  2089. int argc = session->header.env.nr_cmdline;
  2090. evlist__for_each_entry(evsel_list, counter)
  2091. perf_stat_process_counter(&stat_config, counter);
  2092. if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
  2093. update_stats(&walltime_nsecs_stats, stat_round->time);
  2094. if (stat_config.interval && stat_round->time) {
  2095. tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
  2096. tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
  2097. ts = &tsh;
  2098. }
  2099. print_counters(ts, argc, argv);
  2100. return 0;
  2101. }
  2102. static
  2103. int process_stat_config_event(struct perf_tool *tool,
  2104. union perf_event *event,
  2105. struct perf_session *session __maybe_unused)
  2106. {
  2107. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  2108. perf_event__read_stat_config(&stat_config, &event->stat_config);
  2109. if (cpu_map__empty(st->cpus)) {
  2110. if (st->aggr_mode != AGGR_UNSET)
  2111. pr_warning("warning: processing task data, aggregation mode not set\n");
  2112. return 0;
  2113. }
  2114. if (st->aggr_mode != AGGR_UNSET)
  2115. stat_config.aggr_mode = st->aggr_mode;
  2116. if (perf_stat.data.is_pipe)
  2117. perf_stat_init_aggr_mode();
  2118. else
  2119. perf_stat_init_aggr_mode_file(st);
  2120. return 0;
  2121. }
  2122. static int set_maps(struct perf_stat *st)
  2123. {
  2124. if (!st->cpus || !st->threads)
  2125. return 0;
  2126. if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
  2127. return -EINVAL;
  2128. perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
  2129. if (perf_evlist__alloc_stats(evsel_list, true))
  2130. return -ENOMEM;
  2131. st->maps_allocated = true;
  2132. return 0;
  2133. }
  2134. static
  2135. int process_thread_map_event(struct perf_tool *tool,
  2136. union perf_event *event,
  2137. struct perf_session *session __maybe_unused)
  2138. {
  2139. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  2140. if (st->threads) {
  2141. pr_warning("Extra thread map event, ignoring.\n");
  2142. return 0;
  2143. }
  2144. st->threads = thread_map__new_event(&event->thread_map);
  2145. if (!st->threads)
  2146. return -ENOMEM;
  2147. return set_maps(st);
  2148. }
  2149. static
  2150. int process_cpu_map_event(struct perf_tool *tool,
  2151. union perf_event *event,
  2152. struct perf_session *session __maybe_unused)
  2153. {
  2154. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  2155. struct cpu_map *cpus;
  2156. if (st->cpus) {
  2157. pr_warning("Extra cpu map event, ignoring.\n");
  2158. return 0;
  2159. }
  2160. cpus = cpu_map__new_data(&event->cpu_map.data);
  2161. if (!cpus)
  2162. return -ENOMEM;
  2163. st->cpus = cpus;
  2164. return set_maps(st);
  2165. }
  2166. static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
  2167. {
  2168. int i;
  2169. config->stats = calloc(nthreads, sizeof(struct runtime_stat));
  2170. if (!config->stats)
  2171. return -1;
  2172. config->stats_num = nthreads;
  2173. for (i = 0; i < nthreads; i++)
  2174. runtime_stat__init(&config->stats[i]);
  2175. return 0;
  2176. }
  2177. static void runtime_stat_delete(struct perf_stat_config *config)
  2178. {
  2179. int i;
  2180. if (!config->stats)
  2181. return;
  2182. for (i = 0; i < config->stats_num; i++)
  2183. runtime_stat__exit(&config->stats[i]);
  2184. free(config->stats);
  2185. }
  2186. static const char * const stat_report_usage[] = {
  2187. "perf stat report [<options>]",
  2188. NULL,
  2189. };
  2190. static struct perf_stat perf_stat = {
  2191. .tool = {
  2192. .attr = perf_event__process_attr,
  2193. .event_update = perf_event__process_event_update,
  2194. .thread_map = process_thread_map_event,
  2195. .cpu_map = process_cpu_map_event,
  2196. .stat_config = process_stat_config_event,
  2197. .stat = perf_event__process_stat_event,
  2198. .stat_round = process_stat_round_event,
  2199. },
  2200. .aggr_mode = AGGR_UNSET,
  2201. };
  2202. static int __cmd_report(int argc, const char **argv)
  2203. {
  2204. struct perf_session *session;
  2205. const struct option options[] = {
  2206. OPT_STRING('i', "input", &input_name, "file", "input file name"),
  2207. OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
  2208. "aggregate counts per processor socket", AGGR_SOCKET),
  2209. OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
  2210. "aggregate counts per physical processor core", AGGR_CORE),
  2211. OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
  2212. "disable CPU count aggregation", AGGR_NONE),
  2213. OPT_END()
  2214. };
  2215. struct stat st;
  2216. int ret;
  2217. argc = parse_options(argc, argv, options, stat_report_usage, 0);
  2218. if (!input_name || !strlen(input_name)) {
  2219. if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
  2220. input_name = "-";
  2221. else
  2222. input_name = "perf.data";
  2223. }
  2224. perf_stat.data.file.path = input_name;
  2225. perf_stat.data.mode = PERF_DATA_MODE_READ;
  2226. session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
  2227. if (session == NULL)
  2228. return -1;
  2229. perf_stat.session = session;
  2230. stat_config.output = stderr;
  2231. evsel_list = session->evlist;
  2232. ret = perf_session__process_events(session);
  2233. if (ret)
  2234. return ret;
  2235. perf_session__delete(session);
  2236. return 0;
  2237. }
  2238. static void setup_system_wide(int forks)
  2239. {
  2240. /*
  2241. * Make system wide (-a) the default target if
  2242. * no target was specified and one of following
  2243. * conditions is met:
  2244. *
  2245. * - there's no workload specified
  2246. * - there is workload specified but all requested
  2247. * events are system wide events
  2248. */
  2249. if (!target__none(&target))
  2250. return;
  2251. if (!forks)
  2252. target.system_wide = true;
  2253. else {
  2254. struct perf_evsel *counter;
  2255. evlist__for_each_entry(evsel_list, counter) {
  2256. if (!counter->system_wide)
  2257. return;
  2258. }
  2259. if (evsel_list->nr_entries)
  2260. target.system_wide = true;
  2261. }
  2262. }
  2263. int cmd_stat(int argc, const char **argv)
  2264. {
  2265. const char * const stat_usage[] = {
  2266. "perf stat [<options>] [<command>]",
  2267. NULL
  2268. };
  2269. int status = -EINVAL, run_idx;
  2270. const char *mode;
  2271. FILE *output = stderr;
  2272. unsigned int interval;
  2273. const char * const stat_subcommands[] = { "record", "report" };
  2274. setlocale(LC_ALL, "");
  2275. evsel_list = perf_evlist__new();
  2276. if (evsel_list == NULL)
  2277. return -ENOMEM;
  2278. parse_events__shrink_config_terms();
  2279. argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
  2280. (const char **) stat_usage,
  2281. PARSE_OPT_STOP_AT_NON_OPTION);
  2282. perf_stat__collect_metric_expr(evsel_list);
  2283. perf_stat__init_shadow_stats();
  2284. if (csv_sep) {
  2285. csv_output = true;
  2286. if (!strcmp(csv_sep, "\\t"))
  2287. csv_sep = "\t";
  2288. } else
  2289. csv_sep = DEFAULT_SEPARATOR;
  2290. if (argc && !strncmp(argv[0], "rec", 3)) {
  2291. argc = __cmd_record(argc, argv);
  2292. if (argc < 0)
  2293. return -1;
  2294. } else if (argc && !strncmp(argv[0], "rep", 3))
  2295. return __cmd_report(argc, argv);
  2296. interval = stat_config.interval;
  2297. /*
  2298. * For record command the -o is already taken care of.
  2299. */
  2300. if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
  2301. output = NULL;
  2302. if (output_name && output_fd) {
  2303. fprintf(stderr, "cannot use both --output and --log-fd\n");
  2304. parse_options_usage(stat_usage, stat_options, "o", 1);
  2305. parse_options_usage(NULL, stat_options, "log-fd", 0);
  2306. goto out;
  2307. }
  2308. if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
  2309. fprintf(stderr, "--metric-only is not supported with --per-thread\n");
  2310. goto out;
  2311. }
  2312. if (metric_only && run_count > 1) {
  2313. fprintf(stderr, "--metric-only is not supported with -r\n");
  2314. goto out;
  2315. }
  2316. if (output_fd < 0) {
  2317. fprintf(stderr, "argument to --log-fd must be a > 0\n");
  2318. parse_options_usage(stat_usage, stat_options, "log-fd", 0);
  2319. goto out;
  2320. }
  2321. if (!output) {
  2322. struct timespec tm;
  2323. mode = append_file ? "a" : "w";
  2324. output = fopen(output_name, mode);
  2325. if (!output) {
  2326. perror("failed to create output file");
  2327. return -1;
  2328. }
  2329. clock_gettime(CLOCK_REALTIME, &tm);
  2330. fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
  2331. } else if (output_fd > 0) {
  2332. mode = append_file ? "a" : "w";
  2333. output = fdopen(output_fd, mode);
  2334. if (!output) {
  2335. perror("Failed opening logfd");
  2336. return -errno;
  2337. }
  2338. }
  2339. stat_config.output = output;
  2340. /*
  2341. * let the spreadsheet do the pretty-printing
  2342. */
  2343. if (csv_output) {
  2344. /* User explicitly passed -B? */
  2345. if (big_num_opt == 1) {
  2346. fprintf(stderr, "-B option not supported with -x\n");
  2347. parse_options_usage(stat_usage, stat_options, "B", 1);
  2348. parse_options_usage(NULL, stat_options, "x", 1);
  2349. goto out;
  2350. } else /* Nope, so disable big number formatting */
  2351. big_num = false;
  2352. } else if (big_num_opt == 0) /* User passed --no-big-num */
  2353. big_num = false;
  2354. setup_system_wide(argc);
  2355. if (run_count < 0) {
  2356. pr_err("Run count must be a positive number\n");
  2357. parse_options_usage(stat_usage, stat_options, "r", 1);
  2358. goto out;
  2359. } else if (run_count == 0) {
  2360. forever = true;
  2361. run_count = 1;
  2362. }
  2363. if ((stat_config.aggr_mode == AGGR_THREAD) &&
  2364. !target__has_task(&target)) {
  2365. if (!target.system_wide || target.cpu_list) {
  2366. fprintf(stderr, "The --per-thread option is only "
  2367. "available when monitoring via -p -t -a "
  2368. "options or only --per-thread.\n");
  2369. parse_options_usage(NULL, stat_options, "p", 1);
  2370. parse_options_usage(NULL, stat_options, "t", 1);
  2371. goto out;
  2372. }
  2373. }
  2374. /*
  2375. * no_aggr, cgroup are for system-wide only
  2376. * --per-thread is aggregated per thread, we dont mix it with cpu mode
  2377. */
  2378. if (((stat_config.aggr_mode != AGGR_GLOBAL &&
  2379. stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
  2380. !target__has_cpu(&target)) {
  2381. fprintf(stderr, "both cgroup and no-aggregation "
  2382. "modes only available in system-wide mode\n");
  2383. parse_options_usage(stat_usage, stat_options, "G", 1);
  2384. parse_options_usage(NULL, stat_options, "A", 1);
  2385. parse_options_usage(NULL, stat_options, "a", 1);
  2386. goto out;
  2387. }
  2388. if (add_default_attributes())
  2389. goto out;
  2390. target__validate(&target);
  2391. if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
  2392. target.per_thread = true;
  2393. if (perf_evlist__create_maps(evsel_list, &target) < 0) {
  2394. if (target__has_task(&target)) {
  2395. pr_err("Problems finding threads of monitor\n");
  2396. parse_options_usage(stat_usage, stat_options, "p", 1);
  2397. parse_options_usage(NULL, stat_options, "t", 1);
  2398. } else if (target__has_cpu(&target)) {
  2399. perror("failed to parse CPUs map");
  2400. parse_options_usage(stat_usage, stat_options, "C", 1);
  2401. parse_options_usage(NULL, stat_options, "a", 1);
  2402. }
  2403. goto out;
  2404. }
  2405. /*
  2406. * Initialize thread_map with comm names,
  2407. * so we could print it out on output.
  2408. */
  2409. if (stat_config.aggr_mode == AGGR_THREAD) {
  2410. thread_map__read_comms(evsel_list->threads);
  2411. if (target.system_wide) {
  2412. if (runtime_stat_new(&stat_config,
  2413. thread_map__nr(evsel_list->threads))) {
  2414. goto out;
  2415. }
  2416. }
  2417. }
  2418. if (interval && interval < 100) {
  2419. if (interval < 10) {
  2420. pr_err("print interval must be >= 10ms\n");
  2421. parse_options_usage(stat_usage, stat_options, "I", 1);
  2422. goto out;
  2423. } else
  2424. pr_warning("print interval < 100ms. "
  2425. "The overhead percentage could be high in some cases. "
  2426. "Please proceed with caution.\n");
  2427. }
  2428. if (perf_evlist__alloc_stats(evsel_list, interval))
  2429. goto out;
  2430. if (perf_stat_init_aggr_mode())
  2431. goto out;
  2432. /*
  2433. * We dont want to block the signals - that would cause
  2434. * child tasks to inherit that and Ctrl-C would not work.
  2435. * What we want is for Ctrl-C to work in the exec()-ed
  2436. * task, but being ignored by perf stat itself:
  2437. */
  2438. atexit(sig_atexit);
  2439. if (!forever)
  2440. signal(SIGINT, skip_signal);
  2441. signal(SIGCHLD, skip_signal);
  2442. signal(SIGALRM, skip_signal);
  2443. signal(SIGABRT, skip_signal);
  2444. status = 0;
  2445. for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
  2446. if (run_count != 1 && verbose > 0)
  2447. fprintf(output, "[ perf stat: executing run #%d ... ]\n",
  2448. run_idx + 1);
  2449. status = run_perf_stat(argc, argv);
  2450. if (forever && status != -1) {
  2451. print_counters(NULL, argc, argv);
  2452. perf_stat__reset_stats();
  2453. }
  2454. }
  2455. if (!forever && status != -1 && !interval)
  2456. print_counters(NULL, argc, argv);
  2457. if (STAT_RECORD) {
  2458. /*
  2459. * We synthesize the kernel mmap record just so that older tools
  2460. * don't emit warnings about not being able to resolve symbols
  2461. * due to /proc/sys/kernel/kptr_restrict settings and instear provide
  2462. * a saner message about no samples being in the perf.data file.
  2463. *
  2464. * This also serves to suppress a warning about f_header.data.size == 0
  2465. * in header.c at the moment 'perf stat record' gets introduced, which
  2466. * is not really needed once we start adding the stat specific PERF_RECORD_
  2467. * records, but the need to suppress the kptr_restrict messages in older
  2468. * tools remain -acme
  2469. */
  2470. int fd = perf_data__fd(&perf_stat.data);
  2471. int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
  2472. process_synthesized_event,
  2473. &perf_stat.session->machines.host);
  2474. if (err) {
  2475. pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
  2476. "older tools may produce warnings about this file\n.");
  2477. }
  2478. if (!interval) {
  2479. if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
  2480. pr_err("failed to write stat round event\n");
  2481. }
  2482. if (!perf_stat.data.is_pipe) {
  2483. perf_stat.session->header.data_size += perf_stat.bytes_written;
  2484. perf_session__write_header(perf_stat.session, evsel_list, fd, true);
  2485. }
  2486. perf_session__delete(perf_stat.session);
  2487. }
  2488. perf_stat__exit_aggr_mode();
  2489. perf_evlist__free_stats(evsel_list);
  2490. out:
  2491. if (smi_cost && smi_reset)
  2492. sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
  2493. perf_evlist__delete(evsel_list);
  2494. runtime_stat_delete(&stat_config);
  2495. return status;
  2496. }