builtin-stat.c 60 KB

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