builtin-stat.c 77 KB

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