builtin-stat.c 77 KB

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