builtin-stat.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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/util.h"
  40. #include "util/parse-options.h"
  41. #include "util/parse-events.h"
  42. #include "util/pmu.h"
  43. #include "util/event.h"
  44. #include "util/evlist.h"
  45. #include "util/evsel.h"
  46. #include "util/debug.h"
  47. #include "util/color.h"
  48. #include "util/stat.h"
  49. #include "util/header.h"
  50. #include "util/cpumap.h"
  51. #include "util/thread.h"
  52. #include "util/thread_map.h"
  53. #include <stdlib.h>
  54. #include <sys/prctl.h>
  55. #include <locale.h>
  56. #define DEFAULT_SEPARATOR " "
  57. #define CNTR_NOT_SUPPORTED "<not supported>"
  58. #define CNTR_NOT_COUNTED "<not counted>"
  59. static void print_stat(int argc, const char **argv);
  60. static void print_counter_aggr(struct perf_evsel *counter, char *prefix);
  61. static void print_counter(struct perf_evsel *counter, char *prefix);
  62. static void print_aggr(char *prefix);
  63. /* Default events used for perf stat -T */
  64. static const char * const transaction_attrs[] = {
  65. "task-clock",
  66. "{"
  67. "instructions,"
  68. "cycles,"
  69. "cpu/cycles-t/,"
  70. "cpu/tx-start/,"
  71. "cpu/el-start/,"
  72. "cpu/cycles-ct/"
  73. "}"
  74. };
  75. /* More limited version when the CPU does not have all events. */
  76. static const char * const transaction_limited_attrs[] = {
  77. "task-clock",
  78. "{"
  79. "instructions,"
  80. "cycles,"
  81. "cpu/cycles-t/,"
  82. "cpu/tx-start/"
  83. "}"
  84. };
  85. /* must match transaction_attrs and the beginning limited_attrs */
  86. enum {
  87. T_TASK_CLOCK,
  88. T_INSTRUCTIONS,
  89. T_CYCLES,
  90. T_CYCLES_IN_TX,
  91. T_TRANSACTION_START,
  92. T_ELISION_START,
  93. T_CYCLES_IN_TX_CP,
  94. };
  95. static struct perf_evlist *evsel_list;
  96. static struct perf_target target = {
  97. .uid = UINT_MAX,
  98. };
  99. enum aggr_mode {
  100. AGGR_NONE,
  101. AGGR_GLOBAL,
  102. AGGR_SOCKET,
  103. AGGR_CORE,
  104. };
  105. static int run_count = 1;
  106. static bool no_inherit = false;
  107. static bool scale = true;
  108. static enum aggr_mode aggr_mode = AGGR_GLOBAL;
  109. static volatile pid_t child_pid = -1;
  110. static bool null_run = false;
  111. static int detailed_run = 0;
  112. static bool transaction_run;
  113. static bool big_num = true;
  114. static int big_num_opt = -1;
  115. static const char *csv_sep = NULL;
  116. static bool csv_output = false;
  117. static bool group = false;
  118. static FILE *output = NULL;
  119. static const char *pre_cmd = NULL;
  120. static const char *post_cmd = NULL;
  121. static bool sync_run = false;
  122. static unsigned int interval = 0;
  123. static unsigned int initial_delay = 0;
  124. static bool forever = false;
  125. static struct timespec ref_time;
  126. static struct cpu_map *aggr_map;
  127. static int (*aggr_get_id)(struct cpu_map *m, int cpu);
  128. static volatile int done = 0;
  129. struct perf_stat {
  130. struct stats res_stats[3];
  131. };
  132. static inline void diff_timespec(struct timespec *r, struct timespec *a,
  133. struct timespec *b)
  134. {
  135. r->tv_sec = a->tv_sec - b->tv_sec;
  136. if (a->tv_nsec < b->tv_nsec) {
  137. r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
  138. r->tv_sec--;
  139. } else {
  140. r->tv_nsec = a->tv_nsec - b->tv_nsec ;
  141. }
  142. }
  143. static inline struct cpu_map *perf_evsel__cpus(struct perf_evsel *evsel)
  144. {
  145. return (evsel->cpus && !target.cpu_list) ? evsel->cpus : evsel_list->cpus;
  146. }
  147. static inline int perf_evsel__nr_cpus(struct perf_evsel *evsel)
  148. {
  149. return perf_evsel__cpus(evsel)->nr;
  150. }
  151. static void perf_evsel__reset_stat_priv(struct perf_evsel *evsel)
  152. {
  153. memset(evsel->priv, 0, sizeof(struct perf_stat));
  154. }
  155. static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
  156. {
  157. evsel->priv = zalloc(sizeof(struct perf_stat));
  158. return evsel->priv == NULL ? -ENOMEM : 0;
  159. }
  160. static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
  161. {
  162. free(evsel->priv);
  163. evsel->priv = NULL;
  164. }
  165. static int perf_evsel__alloc_prev_raw_counts(struct perf_evsel *evsel)
  166. {
  167. void *addr;
  168. size_t sz;
  169. sz = sizeof(*evsel->counts) +
  170. (perf_evsel__nr_cpus(evsel) * sizeof(struct perf_counts_values));
  171. addr = zalloc(sz);
  172. if (!addr)
  173. return -ENOMEM;
  174. evsel->prev_raw_counts = addr;
  175. return 0;
  176. }
  177. static void perf_evsel__free_prev_raw_counts(struct perf_evsel *evsel)
  178. {
  179. free(evsel->prev_raw_counts);
  180. evsel->prev_raw_counts = NULL;
  181. }
  182. static void perf_evlist__free_stats(struct perf_evlist *evlist)
  183. {
  184. struct perf_evsel *evsel;
  185. list_for_each_entry(evsel, &evlist->entries, node) {
  186. perf_evsel__free_stat_priv(evsel);
  187. perf_evsel__free_counts(evsel);
  188. perf_evsel__free_prev_raw_counts(evsel);
  189. }
  190. }
  191. static int perf_evlist__alloc_stats(struct perf_evlist *evlist, bool alloc_raw)
  192. {
  193. struct perf_evsel *evsel;
  194. list_for_each_entry(evsel, &evlist->entries, node) {
  195. if (perf_evsel__alloc_stat_priv(evsel) < 0 ||
  196. perf_evsel__alloc_counts(evsel, perf_evsel__nr_cpus(evsel)) < 0 ||
  197. (alloc_raw && perf_evsel__alloc_prev_raw_counts(evsel) < 0))
  198. goto out_free;
  199. }
  200. return 0;
  201. out_free:
  202. perf_evlist__free_stats(evlist);
  203. return -1;
  204. }
  205. static struct stats runtime_nsecs_stats[MAX_NR_CPUS];
  206. static struct stats runtime_cycles_stats[MAX_NR_CPUS];
  207. static struct stats runtime_stalled_cycles_front_stats[MAX_NR_CPUS];
  208. static struct stats runtime_stalled_cycles_back_stats[MAX_NR_CPUS];
  209. static struct stats runtime_branches_stats[MAX_NR_CPUS];
  210. static struct stats runtime_cacherefs_stats[MAX_NR_CPUS];
  211. static struct stats runtime_l1_dcache_stats[MAX_NR_CPUS];
  212. static struct stats runtime_l1_icache_stats[MAX_NR_CPUS];
  213. static struct stats runtime_ll_cache_stats[MAX_NR_CPUS];
  214. static struct stats runtime_itlb_cache_stats[MAX_NR_CPUS];
  215. static struct stats runtime_dtlb_cache_stats[MAX_NR_CPUS];
  216. static struct stats runtime_cycles_in_tx_stats[MAX_NR_CPUS];
  217. static struct stats walltime_nsecs_stats;
  218. static struct stats runtime_transaction_stats[MAX_NR_CPUS];
  219. static struct stats runtime_elision_stats[MAX_NR_CPUS];
  220. static void perf_stat__reset_stats(struct perf_evlist *evlist)
  221. {
  222. struct perf_evsel *evsel;
  223. list_for_each_entry(evsel, &evlist->entries, node) {
  224. perf_evsel__reset_stat_priv(evsel);
  225. perf_evsel__reset_counts(evsel, perf_evsel__nr_cpus(evsel));
  226. }
  227. memset(runtime_nsecs_stats, 0, sizeof(runtime_nsecs_stats));
  228. memset(runtime_cycles_stats, 0, sizeof(runtime_cycles_stats));
  229. memset(runtime_stalled_cycles_front_stats, 0, sizeof(runtime_stalled_cycles_front_stats));
  230. memset(runtime_stalled_cycles_back_stats, 0, sizeof(runtime_stalled_cycles_back_stats));
  231. memset(runtime_branches_stats, 0, sizeof(runtime_branches_stats));
  232. memset(runtime_cacherefs_stats, 0, sizeof(runtime_cacherefs_stats));
  233. memset(runtime_l1_dcache_stats, 0, sizeof(runtime_l1_dcache_stats));
  234. memset(runtime_l1_icache_stats, 0, sizeof(runtime_l1_icache_stats));
  235. memset(runtime_ll_cache_stats, 0, sizeof(runtime_ll_cache_stats));
  236. memset(runtime_itlb_cache_stats, 0, sizeof(runtime_itlb_cache_stats));
  237. memset(runtime_dtlb_cache_stats, 0, sizeof(runtime_dtlb_cache_stats));
  238. memset(runtime_cycles_in_tx_stats, 0,
  239. sizeof(runtime_cycles_in_tx_stats));
  240. memset(runtime_transaction_stats, 0,
  241. sizeof(runtime_transaction_stats));
  242. memset(runtime_elision_stats, 0, sizeof(runtime_elision_stats));
  243. memset(&walltime_nsecs_stats, 0, sizeof(walltime_nsecs_stats));
  244. }
  245. static int create_perf_stat_counter(struct perf_evsel *evsel)
  246. {
  247. struct perf_event_attr *attr = &evsel->attr;
  248. if (scale)
  249. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  250. PERF_FORMAT_TOTAL_TIME_RUNNING;
  251. attr->inherit = !no_inherit;
  252. if (perf_target__has_cpu(&target))
  253. return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
  254. if (!perf_target__has_task(&target) &&
  255. perf_evsel__is_group_leader(evsel)) {
  256. attr->disabled = 1;
  257. if (!initial_delay)
  258. attr->enable_on_exec = 1;
  259. }
  260. return perf_evsel__open_per_thread(evsel, evsel_list->threads);
  261. }
  262. /*
  263. * Does the counter have nsecs as a unit?
  264. */
  265. static inline int nsec_counter(struct perf_evsel *evsel)
  266. {
  267. if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
  268. perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  269. return 1;
  270. return 0;
  271. }
  272. static struct perf_evsel *nth_evsel(int n)
  273. {
  274. static struct perf_evsel **array;
  275. static int array_len;
  276. struct perf_evsel *ev;
  277. int j;
  278. /* Assumes this only called when evsel_list does not change anymore. */
  279. if (!array) {
  280. list_for_each_entry(ev, &evsel_list->entries, node)
  281. array_len++;
  282. array = malloc(array_len * sizeof(void *));
  283. if (!array)
  284. exit(ENOMEM);
  285. j = 0;
  286. list_for_each_entry(ev, &evsel_list->entries, node)
  287. array[j++] = ev;
  288. }
  289. if (n < array_len)
  290. return array[n];
  291. return NULL;
  292. }
  293. /*
  294. * Update various tracking values we maintain to print
  295. * more semantic information such as miss/hit ratios,
  296. * instruction rates, etc:
  297. */
  298. static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
  299. {
  300. if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
  301. update_stats(&runtime_nsecs_stats[0], count[0]);
  302. else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
  303. update_stats(&runtime_cycles_stats[0], count[0]);
  304. else if (transaction_run &&
  305. perf_evsel__cmp(counter, nth_evsel(T_CYCLES_IN_TX)))
  306. update_stats(&runtime_cycles_in_tx_stats[0], count[0]);
  307. else if (transaction_run &&
  308. perf_evsel__cmp(counter, nth_evsel(T_TRANSACTION_START)))
  309. update_stats(&runtime_transaction_stats[0], count[0]);
  310. else if (transaction_run &&
  311. perf_evsel__cmp(counter, nth_evsel(T_ELISION_START)))
  312. update_stats(&runtime_elision_stats[0], count[0]);
  313. else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES_FRONTEND))
  314. update_stats(&runtime_stalled_cycles_front_stats[0], count[0]);
  315. else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES_BACKEND))
  316. update_stats(&runtime_stalled_cycles_back_stats[0], count[0]);
  317. else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
  318. update_stats(&runtime_branches_stats[0], count[0]);
  319. else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
  320. update_stats(&runtime_cacherefs_stats[0], count[0]);
  321. else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_L1D))
  322. update_stats(&runtime_l1_dcache_stats[0], count[0]);
  323. else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_L1I))
  324. update_stats(&runtime_l1_icache_stats[0], count[0]);
  325. else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_LL))
  326. update_stats(&runtime_ll_cache_stats[0], count[0]);
  327. else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_DTLB))
  328. update_stats(&runtime_dtlb_cache_stats[0], count[0]);
  329. else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_ITLB))
  330. update_stats(&runtime_itlb_cache_stats[0], count[0]);
  331. }
  332. /*
  333. * Read out the results of a single counter:
  334. * aggregate counts across CPUs in system-wide mode
  335. */
  336. static int read_counter_aggr(struct perf_evsel *counter)
  337. {
  338. struct perf_stat *ps = counter->priv;
  339. u64 *count = counter->counts->aggr.values;
  340. int i;
  341. if (__perf_evsel__read(counter, perf_evsel__nr_cpus(counter),
  342. thread_map__nr(evsel_list->threads), scale) < 0)
  343. return -1;
  344. for (i = 0; i < 3; i++)
  345. update_stats(&ps->res_stats[i], count[i]);
  346. if (verbose) {
  347. fprintf(output, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  348. perf_evsel__name(counter), count[0], count[1], count[2]);
  349. }
  350. /*
  351. * Save the full runtime - to allow normalization during printout:
  352. */
  353. update_shadow_stats(counter, count);
  354. return 0;
  355. }
  356. /*
  357. * Read out the results of a single counter:
  358. * do not aggregate counts across CPUs in system-wide mode
  359. */
  360. static int read_counter(struct perf_evsel *counter)
  361. {
  362. u64 *count;
  363. int cpu;
  364. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  365. if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
  366. return -1;
  367. count = counter->counts->cpu[cpu].values;
  368. update_shadow_stats(counter, count);
  369. }
  370. return 0;
  371. }
  372. static void print_interval(void)
  373. {
  374. static int num_print_interval;
  375. struct perf_evsel *counter;
  376. struct perf_stat *ps;
  377. struct timespec ts, rs;
  378. char prefix[64];
  379. if (aggr_mode == AGGR_GLOBAL) {
  380. list_for_each_entry(counter, &evsel_list->entries, node) {
  381. ps = counter->priv;
  382. memset(ps->res_stats, 0, sizeof(ps->res_stats));
  383. read_counter_aggr(counter);
  384. }
  385. } else {
  386. list_for_each_entry(counter, &evsel_list->entries, node) {
  387. ps = counter->priv;
  388. memset(ps->res_stats, 0, sizeof(ps->res_stats));
  389. read_counter(counter);
  390. }
  391. }
  392. clock_gettime(CLOCK_MONOTONIC, &ts);
  393. diff_timespec(&rs, &ts, &ref_time);
  394. sprintf(prefix, "%6lu.%09lu%s", rs.tv_sec, rs.tv_nsec, csv_sep);
  395. if (num_print_interval == 0 && !csv_output) {
  396. switch (aggr_mode) {
  397. case AGGR_SOCKET:
  398. fprintf(output, "# time socket cpus counts events\n");
  399. break;
  400. case AGGR_CORE:
  401. fprintf(output, "# time core cpus counts events\n");
  402. break;
  403. case AGGR_NONE:
  404. fprintf(output, "# time CPU counts events\n");
  405. break;
  406. case AGGR_GLOBAL:
  407. default:
  408. fprintf(output, "# time counts events\n");
  409. }
  410. }
  411. if (++num_print_interval == 25)
  412. num_print_interval = 0;
  413. switch (aggr_mode) {
  414. case AGGR_CORE:
  415. case AGGR_SOCKET:
  416. print_aggr(prefix);
  417. break;
  418. case AGGR_NONE:
  419. list_for_each_entry(counter, &evsel_list->entries, node)
  420. print_counter(counter, prefix);
  421. break;
  422. case AGGR_GLOBAL:
  423. default:
  424. list_for_each_entry(counter, &evsel_list->entries, node)
  425. print_counter_aggr(counter, prefix);
  426. }
  427. fflush(output);
  428. }
  429. static void handle_initial_delay(void)
  430. {
  431. struct perf_evsel *counter;
  432. if (initial_delay) {
  433. const int ncpus = cpu_map__nr(evsel_list->cpus),
  434. nthreads = thread_map__nr(evsel_list->threads);
  435. usleep(initial_delay * 1000);
  436. list_for_each_entry(counter, &evsel_list->entries, node)
  437. perf_evsel__enable(counter, ncpus, nthreads);
  438. }
  439. }
  440. static int __run_perf_stat(int argc, const char **argv)
  441. {
  442. char msg[512];
  443. unsigned long long t0, t1;
  444. struct perf_evsel *counter;
  445. struct timespec ts;
  446. int status = 0;
  447. const bool forks = (argc > 0);
  448. if (interval) {
  449. ts.tv_sec = interval / 1000;
  450. ts.tv_nsec = (interval % 1000) * 1000000;
  451. } else {
  452. ts.tv_sec = 1;
  453. ts.tv_nsec = 0;
  454. }
  455. if (forks) {
  456. if (perf_evlist__prepare_workload(evsel_list, &target, argv,
  457. false, false) < 0) {
  458. perror("failed to prepare workload");
  459. return -1;
  460. }
  461. child_pid = evsel_list->workload.pid;
  462. }
  463. if (group)
  464. perf_evlist__set_leader(evsel_list);
  465. list_for_each_entry(counter, &evsel_list->entries, node) {
  466. if (create_perf_stat_counter(counter) < 0) {
  467. /*
  468. * PPC returns ENXIO for HW counters until 2.6.37
  469. * (behavior changed with commit b0a873e).
  470. */
  471. if (errno == EINVAL || errno == ENOSYS ||
  472. errno == ENOENT || errno == EOPNOTSUPP ||
  473. errno == ENXIO) {
  474. if (verbose)
  475. ui__warning("%s event is not supported by the kernel.\n",
  476. perf_evsel__name(counter));
  477. counter->supported = false;
  478. continue;
  479. }
  480. perf_evsel__open_strerror(counter, &target,
  481. errno, msg, sizeof(msg));
  482. ui__error("%s\n", msg);
  483. if (child_pid != -1)
  484. kill(child_pid, SIGTERM);
  485. return -1;
  486. }
  487. counter->supported = true;
  488. }
  489. if (perf_evlist__apply_filters(evsel_list)) {
  490. error("failed to set filter with %d (%s)\n", errno,
  491. strerror(errno));
  492. return -1;
  493. }
  494. /*
  495. * Enable counters and exec the command:
  496. */
  497. t0 = rdclock();
  498. clock_gettime(CLOCK_MONOTONIC, &ref_time);
  499. if (forks) {
  500. perf_evlist__start_workload(evsel_list);
  501. handle_initial_delay();
  502. if (interval) {
  503. while (!waitpid(child_pid, &status, WNOHANG)) {
  504. nanosleep(&ts, NULL);
  505. print_interval();
  506. }
  507. }
  508. wait(&status);
  509. if (WIFSIGNALED(status))
  510. psignal(WTERMSIG(status), argv[0]);
  511. } else {
  512. handle_initial_delay();
  513. while (!done) {
  514. nanosleep(&ts, NULL);
  515. if (interval)
  516. print_interval();
  517. }
  518. }
  519. t1 = rdclock();
  520. update_stats(&walltime_nsecs_stats, t1 - t0);
  521. if (aggr_mode == AGGR_GLOBAL) {
  522. list_for_each_entry(counter, &evsel_list->entries, node) {
  523. read_counter_aggr(counter);
  524. perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
  525. thread_map__nr(evsel_list->threads));
  526. }
  527. } else {
  528. list_for_each_entry(counter, &evsel_list->entries, node) {
  529. read_counter(counter);
  530. perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter), 1);
  531. }
  532. }
  533. return WEXITSTATUS(status);
  534. }
  535. static int run_perf_stat(int argc __maybe_unused, const char **argv)
  536. {
  537. int ret;
  538. if (pre_cmd) {
  539. ret = system(pre_cmd);
  540. if (ret)
  541. return ret;
  542. }
  543. if (sync_run)
  544. sync();
  545. ret = __run_perf_stat(argc, argv);
  546. if (ret)
  547. return ret;
  548. if (post_cmd) {
  549. ret = system(post_cmd);
  550. if (ret)
  551. return ret;
  552. }
  553. return ret;
  554. }
  555. static void print_noise_pct(double total, double avg)
  556. {
  557. double pct = rel_stddev_stats(total, avg);
  558. if (csv_output)
  559. fprintf(output, "%s%.2f%%", csv_sep, pct);
  560. else if (pct)
  561. fprintf(output, " ( +-%6.2f%% )", pct);
  562. }
  563. static void print_noise(struct perf_evsel *evsel, double avg)
  564. {
  565. struct perf_stat *ps;
  566. if (run_count == 1)
  567. return;
  568. ps = evsel->priv;
  569. print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
  570. }
  571. static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
  572. {
  573. switch (aggr_mode) {
  574. case AGGR_CORE:
  575. fprintf(output, "S%d-C%*d%s%*d%s",
  576. cpu_map__id_to_socket(id),
  577. csv_output ? 0 : -8,
  578. cpu_map__id_to_cpu(id),
  579. csv_sep,
  580. csv_output ? 0 : 4,
  581. nr,
  582. csv_sep);
  583. break;
  584. case AGGR_SOCKET:
  585. fprintf(output, "S%*d%s%*d%s",
  586. csv_output ? 0 : -5,
  587. id,
  588. csv_sep,
  589. csv_output ? 0 : 4,
  590. nr,
  591. csv_sep);
  592. break;
  593. case AGGR_NONE:
  594. fprintf(output, "CPU%*d%s",
  595. csv_output ? 0 : -4,
  596. perf_evsel__cpus(evsel)->map[id], csv_sep);
  597. break;
  598. case AGGR_GLOBAL:
  599. default:
  600. break;
  601. }
  602. }
  603. static void nsec_printout(int cpu, int nr, struct perf_evsel *evsel, double avg)
  604. {
  605. double msecs = avg / 1e6;
  606. const char *fmt = csv_output ? "%.6f%s%s" : "%18.6f%s%-25s";
  607. char name[25];
  608. aggr_printout(evsel, cpu, nr);
  609. scnprintf(name, sizeof(name), "%s%s",
  610. perf_evsel__name(evsel), csv_output ? "" : " (msec)");
  611. fprintf(output, fmt, msecs, csv_sep, name);
  612. if (evsel->cgrp)
  613. fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
  614. if (csv_output || interval)
  615. return;
  616. if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  617. fprintf(output, " # %8.3f CPUs utilized ",
  618. avg / avg_stats(&walltime_nsecs_stats));
  619. else
  620. fprintf(output, " ");
  621. }
  622. /* used for get_ratio_color() */
  623. enum grc_type {
  624. GRC_STALLED_CYCLES_FE,
  625. GRC_STALLED_CYCLES_BE,
  626. GRC_CACHE_MISSES,
  627. GRC_MAX_NR
  628. };
  629. static const char *get_ratio_color(enum grc_type type, double ratio)
  630. {
  631. static const double grc_table[GRC_MAX_NR][3] = {
  632. [GRC_STALLED_CYCLES_FE] = { 50.0, 30.0, 10.0 },
  633. [GRC_STALLED_CYCLES_BE] = { 75.0, 50.0, 20.0 },
  634. [GRC_CACHE_MISSES] = { 20.0, 10.0, 5.0 },
  635. };
  636. const char *color = PERF_COLOR_NORMAL;
  637. if (ratio > grc_table[type][0])
  638. color = PERF_COLOR_RED;
  639. else if (ratio > grc_table[type][1])
  640. color = PERF_COLOR_MAGENTA;
  641. else if (ratio > grc_table[type][2])
  642. color = PERF_COLOR_YELLOW;
  643. return color;
  644. }
  645. static void print_stalled_cycles_frontend(int cpu,
  646. struct perf_evsel *evsel
  647. __maybe_unused, double avg)
  648. {
  649. double total, ratio = 0.0;
  650. const char *color;
  651. total = avg_stats(&runtime_cycles_stats[cpu]);
  652. if (total)
  653. ratio = avg / total * 100.0;
  654. color = get_ratio_color(GRC_STALLED_CYCLES_FE, ratio);
  655. fprintf(output, " # ");
  656. color_fprintf(output, color, "%6.2f%%", ratio);
  657. fprintf(output, " frontend cycles idle ");
  658. }
  659. static void print_stalled_cycles_backend(int cpu,
  660. struct perf_evsel *evsel
  661. __maybe_unused, double avg)
  662. {
  663. double total, ratio = 0.0;
  664. const char *color;
  665. total = avg_stats(&runtime_cycles_stats[cpu]);
  666. if (total)
  667. ratio = avg / total * 100.0;
  668. color = get_ratio_color(GRC_STALLED_CYCLES_BE, ratio);
  669. fprintf(output, " # ");
  670. color_fprintf(output, color, "%6.2f%%", ratio);
  671. fprintf(output, " backend cycles idle ");
  672. }
  673. static void print_branch_misses(int cpu,
  674. struct perf_evsel *evsel __maybe_unused,
  675. double avg)
  676. {
  677. double total, ratio = 0.0;
  678. const char *color;
  679. total = avg_stats(&runtime_branches_stats[cpu]);
  680. if (total)
  681. ratio = avg / total * 100.0;
  682. color = get_ratio_color(GRC_CACHE_MISSES, ratio);
  683. fprintf(output, " # ");
  684. color_fprintf(output, color, "%6.2f%%", ratio);
  685. fprintf(output, " of all branches ");
  686. }
  687. static void print_l1_dcache_misses(int cpu,
  688. struct perf_evsel *evsel __maybe_unused,
  689. double avg)
  690. {
  691. double total, ratio = 0.0;
  692. const char *color;
  693. total = avg_stats(&runtime_l1_dcache_stats[cpu]);
  694. if (total)
  695. ratio = avg / total * 100.0;
  696. color = get_ratio_color(GRC_CACHE_MISSES, ratio);
  697. fprintf(output, " # ");
  698. color_fprintf(output, color, "%6.2f%%", ratio);
  699. fprintf(output, " of all L1-dcache hits ");
  700. }
  701. static void print_l1_icache_misses(int cpu,
  702. struct perf_evsel *evsel __maybe_unused,
  703. double avg)
  704. {
  705. double total, ratio = 0.0;
  706. const char *color;
  707. total = avg_stats(&runtime_l1_icache_stats[cpu]);
  708. if (total)
  709. ratio = avg / total * 100.0;
  710. color = get_ratio_color(GRC_CACHE_MISSES, ratio);
  711. fprintf(output, " # ");
  712. color_fprintf(output, color, "%6.2f%%", ratio);
  713. fprintf(output, " of all L1-icache hits ");
  714. }
  715. static void print_dtlb_cache_misses(int cpu,
  716. struct perf_evsel *evsel __maybe_unused,
  717. double avg)
  718. {
  719. double total, ratio = 0.0;
  720. const char *color;
  721. total = avg_stats(&runtime_dtlb_cache_stats[cpu]);
  722. if (total)
  723. ratio = avg / total * 100.0;
  724. color = get_ratio_color(GRC_CACHE_MISSES, ratio);
  725. fprintf(output, " # ");
  726. color_fprintf(output, color, "%6.2f%%", ratio);
  727. fprintf(output, " of all dTLB cache hits ");
  728. }
  729. static void print_itlb_cache_misses(int cpu,
  730. struct perf_evsel *evsel __maybe_unused,
  731. double avg)
  732. {
  733. double total, ratio = 0.0;
  734. const char *color;
  735. total = avg_stats(&runtime_itlb_cache_stats[cpu]);
  736. if (total)
  737. ratio = avg / total * 100.0;
  738. color = get_ratio_color(GRC_CACHE_MISSES, ratio);
  739. fprintf(output, " # ");
  740. color_fprintf(output, color, "%6.2f%%", ratio);
  741. fprintf(output, " of all iTLB cache hits ");
  742. }
  743. static void print_ll_cache_misses(int cpu,
  744. struct perf_evsel *evsel __maybe_unused,
  745. double avg)
  746. {
  747. double total, ratio = 0.0;
  748. const char *color;
  749. total = avg_stats(&runtime_ll_cache_stats[cpu]);
  750. if (total)
  751. ratio = avg / total * 100.0;
  752. color = get_ratio_color(GRC_CACHE_MISSES, ratio);
  753. fprintf(output, " # ");
  754. color_fprintf(output, color, "%6.2f%%", ratio);
  755. fprintf(output, " of all LL-cache hits ");
  756. }
  757. static void abs_printout(int cpu, int nr, struct perf_evsel *evsel, double avg)
  758. {
  759. double total, ratio = 0.0, total2;
  760. const char *fmt;
  761. if (csv_output)
  762. fmt = "%.0f%s%s";
  763. else if (big_num)
  764. fmt = "%'18.0f%s%-25s";
  765. else
  766. fmt = "%18.0f%s%-25s";
  767. aggr_printout(evsel, cpu, nr);
  768. if (aggr_mode == AGGR_GLOBAL)
  769. cpu = 0;
  770. fprintf(output, fmt, avg, csv_sep, perf_evsel__name(evsel));
  771. if (evsel->cgrp)
  772. fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
  773. if (csv_output || interval)
  774. return;
  775. if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
  776. total = avg_stats(&runtime_cycles_stats[cpu]);
  777. if (total) {
  778. ratio = avg / total;
  779. fprintf(output, " # %5.2f insns per cycle ", ratio);
  780. }
  781. total = avg_stats(&runtime_stalled_cycles_front_stats[cpu]);
  782. total = max(total, avg_stats(&runtime_stalled_cycles_back_stats[cpu]));
  783. if (total && avg) {
  784. ratio = total / avg;
  785. fprintf(output, "\n # %5.2f stalled cycles per insn", ratio);
  786. }
  787. } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
  788. runtime_branches_stats[cpu].n != 0) {
  789. print_branch_misses(cpu, evsel, avg);
  790. } else if (
  791. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  792. evsel->attr.config == ( PERF_COUNT_HW_CACHE_L1D |
  793. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  794. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  795. runtime_l1_dcache_stats[cpu].n != 0) {
  796. print_l1_dcache_misses(cpu, evsel, avg);
  797. } else if (
  798. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  799. evsel->attr.config == ( PERF_COUNT_HW_CACHE_L1I |
  800. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  801. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  802. runtime_l1_icache_stats[cpu].n != 0) {
  803. print_l1_icache_misses(cpu, evsel, avg);
  804. } else if (
  805. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  806. evsel->attr.config == ( PERF_COUNT_HW_CACHE_DTLB |
  807. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  808. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  809. runtime_dtlb_cache_stats[cpu].n != 0) {
  810. print_dtlb_cache_misses(cpu, evsel, avg);
  811. } else if (
  812. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  813. evsel->attr.config == ( PERF_COUNT_HW_CACHE_ITLB |
  814. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  815. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  816. runtime_itlb_cache_stats[cpu].n != 0) {
  817. print_itlb_cache_misses(cpu, evsel, avg);
  818. } else if (
  819. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  820. evsel->attr.config == ( PERF_COUNT_HW_CACHE_LL |
  821. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  822. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  823. runtime_ll_cache_stats[cpu].n != 0) {
  824. print_ll_cache_misses(cpu, evsel, avg);
  825. } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
  826. runtime_cacherefs_stats[cpu].n != 0) {
  827. total = avg_stats(&runtime_cacherefs_stats[cpu]);
  828. if (total)
  829. ratio = avg * 100 / total;
  830. fprintf(output, " # %8.3f %% of all cache refs ", ratio);
  831. } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_FRONTEND)) {
  832. print_stalled_cycles_frontend(cpu, evsel, avg);
  833. } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_BACKEND)) {
  834. print_stalled_cycles_backend(cpu, evsel, avg);
  835. } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
  836. total = avg_stats(&runtime_nsecs_stats[cpu]);
  837. if (total) {
  838. ratio = avg / total;
  839. fprintf(output, " # %8.3f GHz ", ratio);
  840. }
  841. } else if (transaction_run &&
  842. perf_evsel__cmp(evsel, nth_evsel(T_CYCLES_IN_TX))) {
  843. total = avg_stats(&runtime_cycles_stats[cpu]);
  844. if (total)
  845. fprintf(output,
  846. " # %5.2f%% transactional cycles ",
  847. 100.0 * (avg / total));
  848. } else if (transaction_run &&
  849. perf_evsel__cmp(evsel, nth_evsel(T_CYCLES_IN_TX_CP))) {
  850. total = avg_stats(&runtime_cycles_stats[cpu]);
  851. total2 = avg_stats(&runtime_cycles_in_tx_stats[cpu]);
  852. if (total2 < avg)
  853. total2 = avg;
  854. if (total)
  855. fprintf(output,
  856. " # %5.2f%% aborted cycles ",
  857. 100.0 * ((total2-avg) / total));
  858. } else if (transaction_run &&
  859. perf_evsel__cmp(evsel, nth_evsel(T_TRANSACTION_START)) &&
  860. avg > 0 &&
  861. runtime_cycles_in_tx_stats[cpu].n != 0) {
  862. total = avg_stats(&runtime_cycles_in_tx_stats[cpu]);
  863. if (total)
  864. ratio = total / avg;
  865. fprintf(output, " # %8.0f cycles / transaction ", ratio);
  866. } else if (transaction_run &&
  867. perf_evsel__cmp(evsel, nth_evsel(T_ELISION_START)) &&
  868. avg > 0 &&
  869. runtime_cycles_in_tx_stats[cpu].n != 0) {
  870. total = avg_stats(&runtime_cycles_in_tx_stats[cpu]);
  871. if (total)
  872. ratio = total / avg;
  873. fprintf(output, " # %8.0f cycles / elision ", ratio);
  874. } else if (runtime_nsecs_stats[cpu].n != 0) {
  875. char unit = 'M';
  876. total = avg_stats(&runtime_nsecs_stats[cpu]);
  877. if (total)
  878. ratio = 1000.0 * avg / total;
  879. if (ratio < 0.001) {
  880. ratio *= 1000;
  881. unit = 'K';
  882. }
  883. fprintf(output, " # %8.3f %c/sec ", ratio, unit);
  884. } else {
  885. fprintf(output, " ");
  886. }
  887. }
  888. static void print_aggr(char *prefix)
  889. {
  890. struct perf_evsel *counter;
  891. int cpu, cpu2, s, s2, id, nr;
  892. u64 ena, run, val;
  893. if (!(aggr_map || aggr_get_id))
  894. return;
  895. for (s = 0; s < aggr_map->nr; s++) {
  896. id = aggr_map->map[s];
  897. list_for_each_entry(counter, &evsel_list->entries, node) {
  898. val = ena = run = 0;
  899. nr = 0;
  900. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  901. cpu2 = perf_evsel__cpus(counter)->map[cpu];
  902. s2 = aggr_get_id(evsel_list->cpus, cpu2);
  903. if (s2 != id)
  904. continue;
  905. val += counter->counts->cpu[cpu].val;
  906. ena += counter->counts->cpu[cpu].ena;
  907. run += counter->counts->cpu[cpu].run;
  908. nr++;
  909. }
  910. if (prefix)
  911. fprintf(output, "%s", prefix);
  912. if (run == 0 || ena == 0) {
  913. aggr_printout(counter, id, nr);
  914. fprintf(output, "%*s%s%*s",
  915. csv_output ? 0 : 18,
  916. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  917. csv_sep,
  918. csv_output ? 0 : -24,
  919. perf_evsel__name(counter));
  920. if (counter->cgrp)
  921. fprintf(output, "%s%s",
  922. csv_sep, counter->cgrp->name);
  923. fputc('\n', output);
  924. continue;
  925. }
  926. if (nsec_counter(counter))
  927. nsec_printout(id, nr, counter, val);
  928. else
  929. abs_printout(id, nr, counter, val);
  930. if (!csv_output) {
  931. print_noise(counter, 1.0);
  932. if (run != ena)
  933. fprintf(output, " (%.2f%%)",
  934. 100.0 * run / ena);
  935. }
  936. fputc('\n', output);
  937. }
  938. }
  939. }
  940. /*
  941. * Print out the results of a single counter:
  942. * aggregated counts in system-wide mode
  943. */
  944. static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
  945. {
  946. struct perf_stat *ps = counter->priv;
  947. double avg = avg_stats(&ps->res_stats[0]);
  948. int scaled = counter->counts->scaled;
  949. if (prefix)
  950. fprintf(output, "%s", prefix);
  951. if (scaled == -1) {
  952. fprintf(output, "%*s%s%*s",
  953. csv_output ? 0 : 18,
  954. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  955. csv_sep,
  956. csv_output ? 0 : -24,
  957. perf_evsel__name(counter));
  958. if (counter->cgrp)
  959. fprintf(output, "%s%s", csv_sep, counter->cgrp->name);
  960. fputc('\n', output);
  961. return;
  962. }
  963. if (nsec_counter(counter))
  964. nsec_printout(-1, 0, counter, avg);
  965. else
  966. abs_printout(-1, 0, counter, avg);
  967. print_noise(counter, avg);
  968. if (csv_output) {
  969. fputc('\n', output);
  970. return;
  971. }
  972. if (scaled) {
  973. double avg_enabled, avg_running;
  974. avg_enabled = avg_stats(&ps->res_stats[1]);
  975. avg_running = avg_stats(&ps->res_stats[2]);
  976. fprintf(output, " [%5.2f%%]", 100 * avg_running / avg_enabled);
  977. }
  978. fprintf(output, "\n");
  979. }
  980. /*
  981. * Print out the results of a single counter:
  982. * does not use aggregated count in system-wide
  983. */
  984. static void print_counter(struct perf_evsel *counter, char *prefix)
  985. {
  986. u64 ena, run, val;
  987. int cpu;
  988. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  989. val = counter->counts->cpu[cpu].val;
  990. ena = counter->counts->cpu[cpu].ena;
  991. run = counter->counts->cpu[cpu].run;
  992. if (prefix)
  993. fprintf(output, "%s", prefix);
  994. if (run == 0 || ena == 0) {
  995. fprintf(output, "CPU%*d%s%*s%s%*s",
  996. csv_output ? 0 : -4,
  997. perf_evsel__cpus(counter)->map[cpu], csv_sep,
  998. csv_output ? 0 : 18,
  999. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  1000. csv_sep,
  1001. csv_output ? 0 : -24,
  1002. perf_evsel__name(counter));
  1003. if (counter->cgrp)
  1004. fprintf(output, "%s%s",
  1005. csv_sep, counter->cgrp->name);
  1006. fputc('\n', output);
  1007. continue;
  1008. }
  1009. if (nsec_counter(counter))
  1010. nsec_printout(cpu, 0, counter, val);
  1011. else
  1012. abs_printout(cpu, 0, counter, val);
  1013. if (!csv_output) {
  1014. print_noise(counter, 1.0);
  1015. if (run != ena)
  1016. fprintf(output, " (%.2f%%)",
  1017. 100.0 * run / ena);
  1018. }
  1019. fputc('\n', output);
  1020. }
  1021. }
  1022. static void print_stat(int argc, const char **argv)
  1023. {
  1024. struct perf_evsel *counter;
  1025. int i;
  1026. fflush(stdout);
  1027. if (!csv_output) {
  1028. fprintf(output, "\n");
  1029. fprintf(output, " Performance counter stats for ");
  1030. if (target.system_wide)
  1031. fprintf(output, "\'system wide");
  1032. else if (target.cpu_list)
  1033. fprintf(output, "\'CPU(s) %s", target.cpu_list);
  1034. else if (!perf_target__has_task(&target)) {
  1035. fprintf(output, "\'%s", argv[0]);
  1036. for (i = 1; i < argc; i++)
  1037. fprintf(output, " %s", argv[i]);
  1038. } else if (target.pid)
  1039. fprintf(output, "process id \'%s", target.pid);
  1040. else
  1041. fprintf(output, "thread id \'%s", target.tid);
  1042. fprintf(output, "\'");
  1043. if (run_count > 1)
  1044. fprintf(output, " (%d runs)", run_count);
  1045. fprintf(output, ":\n\n");
  1046. }
  1047. switch (aggr_mode) {
  1048. case AGGR_CORE:
  1049. case AGGR_SOCKET:
  1050. print_aggr(NULL);
  1051. break;
  1052. case AGGR_GLOBAL:
  1053. list_for_each_entry(counter, &evsel_list->entries, node)
  1054. print_counter_aggr(counter, NULL);
  1055. break;
  1056. case AGGR_NONE:
  1057. list_for_each_entry(counter, &evsel_list->entries, node)
  1058. print_counter(counter, NULL);
  1059. break;
  1060. default:
  1061. break;
  1062. }
  1063. if (!csv_output) {
  1064. if (!null_run)
  1065. fprintf(output, "\n");
  1066. fprintf(output, " %17.9f seconds time elapsed",
  1067. avg_stats(&walltime_nsecs_stats)/1e9);
  1068. if (run_count > 1) {
  1069. fprintf(output, " ");
  1070. print_noise_pct(stddev_stats(&walltime_nsecs_stats),
  1071. avg_stats(&walltime_nsecs_stats));
  1072. }
  1073. fprintf(output, "\n\n");
  1074. }
  1075. }
  1076. static volatile int signr = -1;
  1077. static void skip_signal(int signo)
  1078. {
  1079. if ((child_pid == -1) || interval)
  1080. done = 1;
  1081. signr = signo;
  1082. /*
  1083. * render child_pid harmless
  1084. * won't send SIGTERM to a random
  1085. * process in case of race condition
  1086. * and fast PID recycling
  1087. */
  1088. child_pid = -1;
  1089. }
  1090. static void sig_atexit(void)
  1091. {
  1092. sigset_t set, oset;
  1093. /*
  1094. * avoid race condition with SIGCHLD handler
  1095. * in skip_signal() which is modifying child_pid
  1096. * goal is to avoid send SIGTERM to a random
  1097. * process
  1098. */
  1099. sigemptyset(&set);
  1100. sigaddset(&set, SIGCHLD);
  1101. sigprocmask(SIG_BLOCK, &set, &oset);
  1102. if (child_pid != -1)
  1103. kill(child_pid, SIGTERM);
  1104. sigprocmask(SIG_SETMASK, &oset, NULL);
  1105. if (signr == -1)
  1106. return;
  1107. signal(signr, SIG_DFL);
  1108. kill(getpid(), signr);
  1109. }
  1110. static int stat__set_big_num(const struct option *opt __maybe_unused,
  1111. const char *s __maybe_unused, int unset)
  1112. {
  1113. big_num_opt = unset ? 0 : 1;
  1114. return 0;
  1115. }
  1116. static int perf_stat_init_aggr_mode(void)
  1117. {
  1118. switch (aggr_mode) {
  1119. case AGGR_SOCKET:
  1120. if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
  1121. perror("cannot build socket map");
  1122. return -1;
  1123. }
  1124. aggr_get_id = cpu_map__get_socket;
  1125. break;
  1126. case AGGR_CORE:
  1127. if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
  1128. perror("cannot build core map");
  1129. return -1;
  1130. }
  1131. aggr_get_id = cpu_map__get_core;
  1132. break;
  1133. case AGGR_NONE:
  1134. case AGGR_GLOBAL:
  1135. default:
  1136. break;
  1137. }
  1138. return 0;
  1139. }
  1140. static int setup_events(const char * const *attrs, unsigned len)
  1141. {
  1142. unsigned i;
  1143. for (i = 0; i < len; i++) {
  1144. if (parse_events(evsel_list, attrs[i]))
  1145. return -1;
  1146. }
  1147. return 0;
  1148. }
  1149. /*
  1150. * Add default attributes, if there were no attributes specified or
  1151. * if -d/--detailed, -d -d or -d -d -d is used:
  1152. */
  1153. static int add_default_attributes(void)
  1154. {
  1155. struct perf_event_attr default_attrs[] = {
  1156. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  1157. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  1158. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  1159. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  1160. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  1161. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
  1162. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
  1163. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  1164. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  1165. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  1166. };
  1167. /*
  1168. * Detailed stats (-d), covering the L1 and last level data caches:
  1169. */
  1170. struct perf_event_attr detailed_attrs[] = {
  1171. { .type = PERF_TYPE_HW_CACHE,
  1172. .config =
  1173. PERF_COUNT_HW_CACHE_L1D << 0 |
  1174. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1175. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1176. { .type = PERF_TYPE_HW_CACHE,
  1177. .config =
  1178. PERF_COUNT_HW_CACHE_L1D << 0 |
  1179. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1180. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1181. { .type = PERF_TYPE_HW_CACHE,
  1182. .config =
  1183. PERF_COUNT_HW_CACHE_LL << 0 |
  1184. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1185. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1186. { .type = PERF_TYPE_HW_CACHE,
  1187. .config =
  1188. PERF_COUNT_HW_CACHE_LL << 0 |
  1189. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1190. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1191. };
  1192. /*
  1193. * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
  1194. */
  1195. struct perf_event_attr very_detailed_attrs[] = {
  1196. { .type = PERF_TYPE_HW_CACHE,
  1197. .config =
  1198. PERF_COUNT_HW_CACHE_L1I << 0 |
  1199. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1200. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1201. { .type = PERF_TYPE_HW_CACHE,
  1202. .config =
  1203. PERF_COUNT_HW_CACHE_L1I << 0 |
  1204. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1205. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1206. { .type = PERF_TYPE_HW_CACHE,
  1207. .config =
  1208. PERF_COUNT_HW_CACHE_DTLB << 0 |
  1209. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1210. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1211. { .type = PERF_TYPE_HW_CACHE,
  1212. .config =
  1213. PERF_COUNT_HW_CACHE_DTLB << 0 |
  1214. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1215. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1216. { .type = PERF_TYPE_HW_CACHE,
  1217. .config =
  1218. PERF_COUNT_HW_CACHE_ITLB << 0 |
  1219. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1220. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1221. { .type = PERF_TYPE_HW_CACHE,
  1222. .config =
  1223. PERF_COUNT_HW_CACHE_ITLB << 0 |
  1224. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  1225. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1226. };
  1227. /*
  1228. * Very, very detailed stats (-d -d -d), adding prefetch events:
  1229. */
  1230. struct perf_event_attr very_very_detailed_attrs[] = {
  1231. { .type = PERF_TYPE_HW_CACHE,
  1232. .config =
  1233. PERF_COUNT_HW_CACHE_L1D << 0 |
  1234. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  1235. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  1236. { .type = PERF_TYPE_HW_CACHE,
  1237. .config =
  1238. PERF_COUNT_HW_CACHE_L1D << 0 |
  1239. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  1240. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  1241. };
  1242. /* Set attrs if no event is selected and !null_run: */
  1243. if (null_run)
  1244. return 0;
  1245. if (transaction_run) {
  1246. int err;
  1247. if (pmu_have_event("cpu", "cycles-ct") &&
  1248. pmu_have_event("cpu", "el-start"))
  1249. err = setup_events(transaction_attrs,
  1250. ARRAY_SIZE(transaction_attrs));
  1251. else
  1252. err = setup_events(transaction_limited_attrs,
  1253. ARRAY_SIZE(transaction_limited_attrs));
  1254. if (err < 0) {
  1255. fprintf(stderr, "Cannot set up transaction events\n");
  1256. return -1;
  1257. }
  1258. return 0;
  1259. }
  1260. if (!evsel_list->nr_entries) {
  1261. if (perf_evlist__add_default_attrs(evsel_list, default_attrs) < 0)
  1262. return -1;
  1263. }
  1264. /* Detailed events get appended to the event list: */
  1265. if (detailed_run < 1)
  1266. return 0;
  1267. /* Append detailed run extra attributes: */
  1268. if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
  1269. return -1;
  1270. if (detailed_run < 2)
  1271. return 0;
  1272. /* Append very detailed run extra attributes: */
  1273. if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
  1274. return -1;
  1275. if (detailed_run < 3)
  1276. return 0;
  1277. /* Append very, very detailed run extra attributes: */
  1278. return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
  1279. }
  1280. int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
  1281. {
  1282. bool append_file = false;
  1283. int output_fd = 0;
  1284. const char *output_name = NULL;
  1285. const struct option options[] = {
  1286. OPT_BOOLEAN('T', "transaction", &transaction_run,
  1287. "hardware transaction statistics"),
  1288. OPT_CALLBACK('e', "event", &evsel_list, "event",
  1289. "event selector. use 'perf list' to list available events",
  1290. parse_events_option),
  1291. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  1292. "event filter", parse_filter),
  1293. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  1294. "child tasks do not inherit counters"),
  1295. OPT_STRING('p', "pid", &target.pid, "pid",
  1296. "stat events on existing process id"),
  1297. OPT_STRING('t', "tid", &target.tid, "tid",
  1298. "stat events on existing thread id"),
  1299. OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
  1300. "system-wide collection from all CPUs"),
  1301. OPT_BOOLEAN('g', "group", &group,
  1302. "put the counters into a counter group"),
  1303. OPT_BOOLEAN('c', "scale", &scale, "scale/normalize counters"),
  1304. OPT_INCR('v', "verbose", &verbose,
  1305. "be more verbose (show counter open errors, etc)"),
  1306. OPT_INTEGER('r', "repeat", &run_count,
  1307. "repeat command and print average + stddev (max: 100, forever: 0)"),
  1308. OPT_BOOLEAN('n', "null", &null_run,
  1309. "null run - dont start any counters"),
  1310. OPT_INCR('d', "detailed", &detailed_run,
  1311. "detailed run - start a lot of events"),
  1312. OPT_BOOLEAN('S', "sync", &sync_run,
  1313. "call sync() before starting a run"),
  1314. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  1315. "print large numbers with thousands\' separators",
  1316. stat__set_big_num),
  1317. OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
  1318. "list of cpus to monitor in system-wide"),
  1319. OPT_SET_UINT('A', "no-aggr", &aggr_mode,
  1320. "disable CPU count aggregation", AGGR_NONE),
  1321. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  1322. "print counts with custom separator"),
  1323. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  1324. "monitor event in cgroup name only", parse_cgroups),
  1325. OPT_STRING('o', "output", &output_name, "file", "output file name"),
  1326. OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
  1327. OPT_INTEGER(0, "log-fd", &output_fd,
  1328. "log output to fd, instead of stderr"),
  1329. OPT_STRING(0, "pre", &pre_cmd, "command",
  1330. "command to run prior to the measured command"),
  1331. OPT_STRING(0, "post", &post_cmd, "command",
  1332. "command to run after to the measured command"),
  1333. OPT_UINTEGER('I', "interval-print", &interval,
  1334. "print counts at regular interval in ms (>= 100)"),
  1335. OPT_SET_UINT(0, "per-socket", &aggr_mode,
  1336. "aggregate counts per processor socket", AGGR_SOCKET),
  1337. OPT_SET_UINT(0, "per-core", &aggr_mode,
  1338. "aggregate counts per physical processor core", AGGR_CORE),
  1339. OPT_UINTEGER('D', "delay", &initial_delay,
  1340. "ms to wait before starting measurement after program start"),
  1341. OPT_END()
  1342. };
  1343. const char * const stat_usage[] = {
  1344. "perf stat [<options>] [<command>]",
  1345. NULL
  1346. };
  1347. int status = -EINVAL, run_idx;
  1348. const char *mode;
  1349. setlocale(LC_ALL, "");
  1350. evsel_list = perf_evlist__new();
  1351. if (evsel_list == NULL)
  1352. return -ENOMEM;
  1353. argc = parse_options(argc, argv, options, stat_usage,
  1354. PARSE_OPT_STOP_AT_NON_OPTION);
  1355. output = stderr;
  1356. if (output_name && strcmp(output_name, "-"))
  1357. output = NULL;
  1358. if (output_name && output_fd) {
  1359. fprintf(stderr, "cannot use both --output and --log-fd\n");
  1360. parse_options_usage(stat_usage, options, "o", 1);
  1361. parse_options_usage(NULL, options, "log-fd", 0);
  1362. goto out;
  1363. }
  1364. if (output_fd < 0) {
  1365. fprintf(stderr, "argument to --log-fd must be a > 0\n");
  1366. parse_options_usage(stat_usage, options, "log-fd", 0);
  1367. goto out;
  1368. }
  1369. if (!output) {
  1370. struct timespec tm;
  1371. mode = append_file ? "a" : "w";
  1372. output = fopen(output_name, mode);
  1373. if (!output) {
  1374. perror("failed to create output file");
  1375. return -1;
  1376. }
  1377. clock_gettime(CLOCK_REALTIME, &tm);
  1378. fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
  1379. } else if (output_fd > 0) {
  1380. mode = append_file ? "a" : "w";
  1381. output = fdopen(output_fd, mode);
  1382. if (!output) {
  1383. perror("Failed opening logfd");
  1384. return -errno;
  1385. }
  1386. }
  1387. if (csv_sep) {
  1388. csv_output = true;
  1389. if (!strcmp(csv_sep, "\\t"))
  1390. csv_sep = "\t";
  1391. } else
  1392. csv_sep = DEFAULT_SEPARATOR;
  1393. /*
  1394. * let the spreadsheet do the pretty-printing
  1395. */
  1396. if (csv_output) {
  1397. /* User explicitly passed -B? */
  1398. if (big_num_opt == 1) {
  1399. fprintf(stderr, "-B option not supported with -x\n");
  1400. parse_options_usage(stat_usage, options, "B", 1);
  1401. parse_options_usage(NULL, options, "x", 1);
  1402. goto out;
  1403. } else /* Nope, so disable big number formatting */
  1404. big_num = false;
  1405. } else if (big_num_opt == 0) /* User passed --no-big-num */
  1406. big_num = false;
  1407. if (!argc && perf_target__none(&target))
  1408. usage_with_options(stat_usage, options);
  1409. if (run_count < 0) {
  1410. pr_err("Run count must be a positive number\n");
  1411. parse_options_usage(stat_usage, options, "r", 1);
  1412. goto out;
  1413. } else if (run_count == 0) {
  1414. forever = true;
  1415. run_count = 1;
  1416. }
  1417. /* no_aggr, cgroup are for system-wide only */
  1418. if ((aggr_mode != AGGR_GLOBAL || nr_cgroups)
  1419. && !perf_target__has_cpu(&target)) {
  1420. fprintf(stderr, "both cgroup and no-aggregation "
  1421. "modes only available in system-wide mode\n");
  1422. parse_options_usage(stat_usage, options, "G", 1);
  1423. parse_options_usage(NULL, options, "A", 1);
  1424. parse_options_usage(NULL, options, "a", 1);
  1425. goto out;
  1426. }
  1427. if (add_default_attributes())
  1428. goto out;
  1429. perf_target__validate(&target);
  1430. if (perf_evlist__create_maps(evsel_list, &target) < 0) {
  1431. if (perf_target__has_task(&target)) {
  1432. pr_err("Problems finding threads of monitor\n");
  1433. parse_options_usage(stat_usage, options, "p", 1);
  1434. parse_options_usage(NULL, options, "t", 1);
  1435. } else if (perf_target__has_cpu(&target)) {
  1436. perror("failed to parse CPUs map");
  1437. parse_options_usage(stat_usage, options, "C", 1);
  1438. parse_options_usage(NULL, options, "a", 1);
  1439. }
  1440. goto out;
  1441. }
  1442. if (interval && interval < 100) {
  1443. pr_err("print interval must be >= 100ms\n");
  1444. parse_options_usage(stat_usage, options, "I", 1);
  1445. goto out_free_maps;
  1446. }
  1447. if (perf_evlist__alloc_stats(evsel_list, interval))
  1448. goto out_free_maps;
  1449. if (perf_stat_init_aggr_mode())
  1450. goto out_free_maps;
  1451. /*
  1452. * We dont want to block the signals - that would cause
  1453. * child tasks to inherit that and Ctrl-C would not work.
  1454. * What we want is for Ctrl-C to work in the exec()-ed
  1455. * task, but being ignored by perf stat itself:
  1456. */
  1457. atexit(sig_atexit);
  1458. if (!forever)
  1459. signal(SIGINT, skip_signal);
  1460. signal(SIGCHLD, skip_signal);
  1461. signal(SIGALRM, skip_signal);
  1462. signal(SIGABRT, skip_signal);
  1463. status = 0;
  1464. for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
  1465. if (run_count != 1 && verbose)
  1466. fprintf(output, "[ perf stat: executing run #%d ... ]\n",
  1467. run_idx + 1);
  1468. status = run_perf_stat(argc, argv);
  1469. if (forever && status != -1) {
  1470. print_stat(argc, argv);
  1471. perf_stat__reset_stats(evsel_list);
  1472. }
  1473. }
  1474. if (!forever && status != -1 && !interval)
  1475. print_stat(argc, argv);
  1476. perf_evlist__free_stats(evsel_list);
  1477. out_free_maps:
  1478. perf_evlist__delete_maps(evsel_list);
  1479. out:
  1480. perf_evlist__delete(evsel_list);
  1481. return status;
  1482. }