builtin-stat.c 69 KB

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