builtin-stat.c 63 KB

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