builtin-stat.c 75 KB

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