builtin-stat.c 68 KB

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