builtin-stat.c 63 KB

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