builtin-stat.c 59 KB

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