builtin-stat.c 67 KB

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