builtin-stat.c 77 KB

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