builtin-stat.c 59 KB

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