builtin-stat.c 70 KB

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