builtin-stat.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  1. /*
  2. * builtin-stat.c
  3. *
  4. * Builtin stat command: Give a precise performance counters summary
  5. * overview about any workload, CPU or specific PID.
  6. *
  7. * Sample output:
  8. $ perf stat ./hackbench 10
  9. Time: 0.118
  10. Performance counter stats for './hackbench 10':
  11. 1708.761321 task-clock # 11.037 CPUs utilized
  12. 41,190 context-switches # 0.024 M/sec
  13. 6,735 CPU-migrations # 0.004 M/sec
  14. 17,318 page-faults # 0.010 M/sec
  15. 5,205,202,243 cycles # 3.046 GHz
  16. 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
  17. 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
  18. 2,603,501,247 instructions # 0.50 insns per cycle
  19. # 1.48 stalled cycles per insn
  20. 484,357,498 branches # 283.455 M/sec
  21. 6,388,934 branch-misses # 1.32% of all branches
  22. 0.154822978 seconds time elapsed
  23. *
  24. * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
  25. *
  26. * Improvements and fixes by:
  27. *
  28. * Arjan van de Ven <arjan@linux.intel.com>
  29. * Yanmin Zhang <yanmin.zhang@intel.com>
  30. * Wu Fengguang <fengguang.wu@intel.com>
  31. * Mike Galbraith <efault@gmx.de>
  32. * Paul Mackerras <paulus@samba.org>
  33. * Jaswinder Singh Rajput <jaswinder@kernel.org>
  34. *
  35. * Released under the GPL v2. (and only v2, not any later version)
  36. */
  37. #include "perf.h"
  38. #include "builtin.h"
  39. #include "util/cgroup.h"
  40. #include "util/util.h"
  41. #include <subcmd/parse-options.h>
  42. #include "util/parse-events.h"
  43. #include "util/pmu.h"
  44. #include "util/event.h"
  45. #include "util/evlist.h"
  46. #include "util/evsel.h"
  47. #include "util/debug.h"
  48. #include "util/drv_configs.h"
  49. #include "util/color.h"
  50. #include "util/stat.h"
  51. #include "util/header.h"
  52. #include "util/cpumap.h"
  53. #include "util/thread.h"
  54. #include "util/thread_map.h"
  55. #include "util/counts.h"
  56. #include "util/group.h"
  57. #include "util/session.h"
  58. #include "util/tool.h"
  59. #include "util/string2.h"
  60. #include "util/metricgroup.h"
  61. #include "util/top.h"
  62. #include "asm/bug.h"
  63. #include <linux/time64.h>
  64. #include <api/fs/fs.h>
  65. #include <errno.h>
  66. #include <signal.h>
  67. #include <stdlib.h>
  68. #include <sys/prctl.h>
  69. #include <inttypes.h>
  70. #include <locale.h>
  71. #include <math.h>
  72. #include <sys/types.h>
  73. #include <sys/stat.h>
  74. #include <sys/wait.h>
  75. #include <unistd.h>
  76. #include <sys/time.h>
  77. #include <sys/resource.h>
  78. #include <sys/wait.h>
  79. #include "sane_ctype.h"
  80. #define DEFAULT_SEPARATOR " "
  81. #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
  82. static void print_counters(struct timespec *ts, int argc, const char **argv);
  83. /* Default events used for perf stat -T */
  84. static const char *transaction_attrs = {
  85. "task-clock,"
  86. "{"
  87. "instructions,"
  88. "cycles,"
  89. "cpu/cycles-t/,"
  90. "cpu/tx-start/,"
  91. "cpu/el-start/,"
  92. "cpu/cycles-ct/"
  93. "}"
  94. };
  95. /* More limited version when the CPU does not have all events. */
  96. static const char * transaction_limited_attrs = {
  97. "task-clock,"
  98. "{"
  99. "instructions,"
  100. "cycles,"
  101. "cpu/cycles-t/,"
  102. "cpu/tx-start/"
  103. "}"
  104. };
  105. static const char * topdown_attrs[] = {
  106. "topdown-total-slots",
  107. "topdown-slots-retired",
  108. "topdown-recovery-bubbles",
  109. "topdown-fetch-bubbles",
  110. "topdown-slots-issued",
  111. NULL,
  112. };
  113. static const char *smi_cost_attrs = {
  114. "{"
  115. "msr/aperf/,"
  116. "msr/smi/,"
  117. "cycles"
  118. "}"
  119. };
  120. static struct perf_evlist *evsel_list;
  121. static struct target target = {
  122. .uid = UINT_MAX,
  123. };
  124. #define METRIC_ONLY_LEN 20
  125. static volatile pid_t child_pid = -1;
  126. static int detailed_run = 0;
  127. static bool transaction_run;
  128. static bool topdown_run = false;
  129. static bool smi_cost = false;
  130. static bool smi_reset = false;
  131. static int big_num_opt = -1;
  132. static bool group = false;
  133. static const char *pre_cmd = NULL;
  134. static const char *post_cmd = NULL;
  135. static bool sync_run = false;
  136. static bool forever = false;
  137. static bool force_metric_only = false;
  138. static struct timespec ref_time;
  139. static bool append_file;
  140. static bool interval_count;
  141. static const char *output_name;
  142. static int output_fd;
  143. struct perf_stat {
  144. bool record;
  145. struct perf_data data;
  146. struct perf_session *session;
  147. u64 bytes_written;
  148. struct perf_tool tool;
  149. bool maps_allocated;
  150. struct cpu_map *cpus;
  151. struct thread_map *threads;
  152. enum aggr_mode aggr_mode;
  153. };
  154. static struct perf_stat perf_stat;
  155. #define STAT_RECORD perf_stat.record
  156. static volatile int done = 0;
  157. static struct perf_stat_config stat_config = {
  158. .aggr_mode = AGGR_GLOBAL,
  159. .scale = true,
  160. .unit_width = 4, /* strlen("unit") */
  161. .run_count = 1,
  162. .metric_only_len = METRIC_ONLY_LEN,
  163. .walltime_nsecs_stats = &walltime_nsecs_stats,
  164. .big_num = true,
  165. };
  166. static inline void diff_timespec(struct timespec *r, struct timespec *a,
  167. struct timespec *b)
  168. {
  169. r->tv_sec = a->tv_sec - b->tv_sec;
  170. if (a->tv_nsec < b->tv_nsec) {
  171. r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
  172. r->tv_sec--;
  173. } else {
  174. r->tv_nsec = a->tv_nsec - b->tv_nsec ;
  175. }
  176. }
  177. static void perf_stat__reset_stats(void)
  178. {
  179. int i;
  180. perf_evlist__reset_stats(evsel_list);
  181. perf_stat__reset_shadow_stats();
  182. for (i = 0; i < stat_config.stats_num; i++)
  183. perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
  184. }
  185. static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
  186. union perf_event *event,
  187. struct perf_sample *sample __maybe_unused,
  188. struct machine *machine __maybe_unused)
  189. {
  190. if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
  191. pr_err("failed to write perf data, error: %m\n");
  192. return -1;
  193. }
  194. perf_stat.bytes_written += event->header.size;
  195. return 0;
  196. }
  197. static int write_stat_round_event(u64 tm, u64 type)
  198. {
  199. return perf_event__synthesize_stat_round(NULL, tm, type,
  200. process_synthesized_event,
  201. NULL);
  202. }
  203. #define WRITE_STAT_ROUND_EVENT(time, interval) \
  204. write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
  205. #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
  206. static int
  207. perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
  208. struct perf_counts_values *count)
  209. {
  210. struct perf_sample_id *sid = SID(counter, cpu, thread);
  211. return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
  212. process_synthesized_event, NULL);
  213. }
  214. /*
  215. * Read out the results of a single counter:
  216. * do not aggregate counts across CPUs in system-wide mode
  217. */
  218. static int read_counter(struct perf_evsel *counter)
  219. {
  220. int nthreads = thread_map__nr(evsel_list->threads);
  221. int ncpus, cpu, thread;
  222. if (target__has_cpu(&target) && !target__has_per_thread(&target))
  223. ncpus = perf_evsel__nr_cpus(counter);
  224. else
  225. ncpus = 1;
  226. if (!counter->supported)
  227. return -ENOENT;
  228. if (counter->system_wide)
  229. nthreads = 1;
  230. for (thread = 0; thread < nthreads; thread++) {
  231. for (cpu = 0; cpu < ncpus; cpu++) {
  232. struct perf_counts_values *count;
  233. count = perf_counts(counter->counts, cpu, thread);
  234. /*
  235. * The leader's group read loads data into its group members
  236. * (via perf_evsel__read_counter) and sets threir count->loaded.
  237. */
  238. if (!count->loaded &&
  239. perf_evsel__read_counter(counter, cpu, thread)) {
  240. counter->counts->scaled = -1;
  241. perf_counts(counter->counts, cpu, thread)->ena = 0;
  242. perf_counts(counter->counts, cpu, thread)->run = 0;
  243. return -1;
  244. }
  245. count->loaded = false;
  246. if (STAT_RECORD) {
  247. if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
  248. pr_err("failed to write stat event\n");
  249. return -1;
  250. }
  251. }
  252. if (verbose > 1) {
  253. fprintf(stat_config.output,
  254. "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  255. perf_evsel__name(counter),
  256. cpu,
  257. count->val, count->ena, count->run);
  258. }
  259. }
  260. }
  261. return 0;
  262. }
  263. static void read_counters(void)
  264. {
  265. struct perf_evsel *counter;
  266. int ret;
  267. evlist__for_each_entry(evsel_list, counter) {
  268. ret = read_counter(counter);
  269. if (ret)
  270. pr_debug("failed to read counter %s\n", counter->name);
  271. if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
  272. pr_warning("failed to process counter %s\n", counter->name);
  273. }
  274. }
  275. static void process_interval(void)
  276. {
  277. struct timespec ts, rs;
  278. read_counters();
  279. clock_gettime(CLOCK_MONOTONIC, &ts);
  280. diff_timespec(&rs, &ts, &ref_time);
  281. if (STAT_RECORD) {
  282. if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
  283. pr_err("failed to write stat round event\n");
  284. }
  285. init_stats(&walltime_nsecs_stats);
  286. update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
  287. print_counters(&rs, 0, NULL);
  288. }
  289. static void enable_counters(void)
  290. {
  291. if (stat_config.initial_delay)
  292. usleep(stat_config.initial_delay * USEC_PER_MSEC);
  293. /*
  294. * We need to enable counters only if:
  295. * - we don't have tracee (attaching to task or cpu)
  296. * - we have initial delay configured
  297. */
  298. if (!target__none(&target) || stat_config.initial_delay)
  299. perf_evlist__enable(evsel_list);
  300. }
  301. static void disable_counters(void)
  302. {
  303. /*
  304. * If we don't have tracee (attaching to task or cpu), counters may
  305. * still be running. To get accurate group ratios, we must stop groups
  306. * from counting before reading their constituent counters.
  307. */
  308. if (!target__none(&target))
  309. perf_evlist__disable(evsel_list);
  310. }
  311. static volatile int workload_exec_errno;
  312. /*
  313. * perf_evlist__prepare_workload will send a SIGUSR1
  314. * if the fork fails, since we asked by setting its
  315. * want_signal to true.
  316. */
  317. static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
  318. void *ucontext __maybe_unused)
  319. {
  320. workload_exec_errno = info->si_value.sival_int;
  321. }
  322. static bool perf_evsel__should_store_id(struct perf_evsel *counter)
  323. {
  324. return STAT_RECORD || counter->attr.read_format & PERF_FORMAT_ID;
  325. }
  326. static struct perf_evsel *perf_evsel__reset_weak_group(struct perf_evsel *evsel)
  327. {
  328. struct perf_evsel *c2, *leader;
  329. bool is_open = true;
  330. leader = evsel->leader;
  331. pr_debug("Weak group for %s/%d failed\n",
  332. leader->name, leader->nr_members);
  333. /*
  334. * for_each_group_member doesn't work here because it doesn't
  335. * include the first entry.
  336. */
  337. evlist__for_each_entry(evsel_list, c2) {
  338. if (c2 == evsel)
  339. is_open = false;
  340. if (c2->leader == leader) {
  341. if (is_open)
  342. perf_evsel__close(c2);
  343. c2->leader = c2;
  344. c2->nr_members = 0;
  345. }
  346. }
  347. return leader;
  348. }
  349. static int __run_perf_stat(int argc, const char **argv, int run_idx)
  350. {
  351. int interval = stat_config.interval;
  352. int times = stat_config.times;
  353. int timeout = stat_config.timeout;
  354. char msg[BUFSIZ];
  355. unsigned long long t0, t1;
  356. struct perf_evsel *counter;
  357. struct timespec ts;
  358. size_t l;
  359. int status = 0;
  360. const bool forks = (argc > 0);
  361. bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
  362. struct perf_evsel_config_term *err_term;
  363. if (interval) {
  364. ts.tv_sec = interval / USEC_PER_MSEC;
  365. ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
  366. } else if (timeout) {
  367. ts.tv_sec = timeout / USEC_PER_MSEC;
  368. ts.tv_nsec = (timeout % USEC_PER_MSEC) * NSEC_PER_MSEC;
  369. } else {
  370. ts.tv_sec = 1;
  371. ts.tv_nsec = 0;
  372. }
  373. if (forks) {
  374. if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
  375. workload_exec_failed_signal) < 0) {
  376. perror("failed to prepare workload");
  377. return -1;
  378. }
  379. child_pid = evsel_list->workload.pid;
  380. }
  381. if (group)
  382. perf_evlist__set_leader(evsel_list);
  383. evlist__for_each_entry(evsel_list, counter) {
  384. try_again:
  385. if (create_perf_stat_counter(counter, &stat_config, &target) < 0) {
  386. /* Weak group failed. Reset the group. */
  387. if ((errno == EINVAL || errno == EBADF) &&
  388. counter->leader != counter &&
  389. counter->weak_group) {
  390. counter = perf_evsel__reset_weak_group(counter);
  391. goto try_again;
  392. }
  393. /*
  394. * PPC returns ENXIO for HW counters until 2.6.37
  395. * (behavior changed with commit b0a873e).
  396. */
  397. if (errno == EINVAL || errno == ENOSYS ||
  398. errno == ENOENT || errno == EOPNOTSUPP ||
  399. errno == ENXIO) {
  400. if (verbose > 0)
  401. ui__warning("%s event is not supported by the kernel.\n",
  402. perf_evsel__name(counter));
  403. counter->supported = false;
  404. if ((counter->leader != counter) ||
  405. !(counter->leader->nr_members > 1))
  406. continue;
  407. } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  408. if (verbose > 0)
  409. ui__warning("%s\n", msg);
  410. goto try_again;
  411. } else if (target__has_per_thread(&target) &&
  412. evsel_list->threads &&
  413. evsel_list->threads->err_thread != -1) {
  414. /*
  415. * For global --per-thread case, skip current
  416. * error thread.
  417. */
  418. if (!thread_map__remove(evsel_list->threads,
  419. evsel_list->threads->err_thread)) {
  420. evsel_list->threads->err_thread = -1;
  421. goto try_again;
  422. }
  423. }
  424. perf_evsel__open_strerror(counter, &target,
  425. errno, msg, sizeof(msg));
  426. ui__error("%s\n", msg);
  427. if (child_pid != -1)
  428. kill(child_pid, SIGTERM);
  429. return -1;
  430. }
  431. counter->supported = true;
  432. l = strlen(counter->unit);
  433. if (l > stat_config.unit_width)
  434. stat_config.unit_width = l;
  435. if (perf_evsel__should_store_id(counter) &&
  436. perf_evsel__store_ids(counter, evsel_list))
  437. return -1;
  438. }
  439. if (perf_evlist__apply_filters(evsel_list, &counter)) {
  440. pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
  441. counter->filter, perf_evsel__name(counter), errno,
  442. str_error_r(errno, msg, sizeof(msg)));
  443. return -1;
  444. }
  445. if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
  446. pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
  447. err_term->val.drv_cfg, perf_evsel__name(counter), errno,
  448. str_error_r(errno, msg, sizeof(msg)));
  449. return -1;
  450. }
  451. if (STAT_RECORD) {
  452. int err, fd = perf_data__fd(&perf_stat.data);
  453. if (is_pipe) {
  454. err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
  455. } else {
  456. err = perf_session__write_header(perf_stat.session, evsel_list,
  457. fd, false);
  458. }
  459. if (err < 0)
  460. return err;
  461. err = perf_stat_synthesize_config(&stat_config, NULL, evsel_list,
  462. process_synthesized_event, is_pipe);
  463. if (err < 0)
  464. return err;
  465. }
  466. /*
  467. * Enable counters and exec the command:
  468. */
  469. t0 = rdclock();
  470. clock_gettime(CLOCK_MONOTONIC, &ref_time);
  471. if (forks) {
  472. perf_evlist__start_workload(evsel_list);
  473. enable_counters();
  474. if (interval || timeout) {
  475. while (!waitpid(child_pid, &status, WNOHANG)) {
  476. nanosleep(&ts, NULL);
  477. if (timeout)
  478. break;
  479. process_interval();
  480. if (interval_count && !(--times))
  481. break;
  482. }
  483. }
  484. wait4(child_pid, &status, 0, &stat_config.ru_data);
  485. if (workload_exec_errno) {
  486. const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
  487. pr_err("Workload failed: %s\n", emsg);
  488. return -1;
  489. }
  490. if (WIFSIGNALED(status))
  491. psignal(WTERMSIG(status), argv[0]);
  492. } else {
  493. enable_counters();
  494. while (!done) {
  495. nanosleep(&ts, NULL);
  496. if (timeout)
  497. break;
  498. if (interval) {
  499. process_interval();
  500. if (interval_count && !(--times))
  501. break;
  502. }
  503. }
  504. }
  505. disable_counters();
  506. t1 = rdclock();
  507. if (stat_config.walltime_run_table)
  508. stat_config.walltime_run[run_idx] = t1 - t0;
  509. update_stats(&walltime_nsecs_stats, t1 - t0);
  510. /*
  511. * Closing a group leader splits the group, and as we only disable
  512. * group leaders, results in remaining events becoming enabled. To
  513. * avoid arbitrary skew, we must read all counters before closing any
  514. * group leaders.
  515. */
  516. read_counters();
  517. perf_evlist__close(evsel_list);
  518. return WEXITSTATUS(status);
  519. }
  520. static int run_perf_stat(int argc, const char **argv, int run_idx)
  521. {
  522. int ret;
  523. if (pre_cmd) {
  524. ret = system(pre_cmd);
  525. if (ret)
  526. return ret;
  527. }
  528. if (sync_run)
  529. sync();
  530. ret = __run_perf_stat(argc, argv, run_idx);
  531. if (ret)
  532. return ret;
  533. if (post_cmd) {
  534. ret = system(post_cmd);
  535. if (ret)
  536. return ret;
  537. }
  538. return ret;
  539. }
  540. static void print_counters(struct timespec *ts, int argc, const char **argv)
  541. {
  542. /* Do not print anything if we record to the pipe. */
  543. if (STAT_RECORD && perf_stat.data.is_pipe)
  544. return;
  545. perf_evlist__print_counters(evsel_list, &stat_config, &target,
  546. ts, argc, argv);
  547. }
  548. static volatile int signr = -1;
  549. static void skip_signal(int signo)
  550. {
  551. if ((child_pid == -1) || stat_config.interval)
  552. done = 1;
  553. signr = signo;
  554. /*
  555. * render child_pid harmless
  556. * won't send SIGTERM to a random
  557. * process in case of race condition
  558. * and fast PID recycling
  559. */
  560. child_pid = -1;
  561. }
  562. static void sig_atexit(void)
  563. {
  564. sigset_t set, oset;
  565. /*
  566. * avoid race condition with SIGCHLD handler
  567. * in skip_signal() which is modifying child_pid
  568. * goal is to avoid send SIGTERM to a random
  569. * process
  570. */
  571. sigemptyset(&set);
  572. sigaddset(&set, SIGCHLD);
  573. sigprocmask(SIG_BLOCK, &set, &oset);
  574. if (child_pid != -1)
  575. kill(child_pid, SIGTERM);
  576. sigprocmask(SIG_SETMASK, &oset, NULL);
  577. if (signr == -1)
  578. return;
  579. signal(signr, SIG_DFL);
  580. kill(getpid(), signr);
  581. }
  582. static int stat__set_big_num(const struct option *opt __maybe_unused,
  583. const char *s __maybe_unused, int unset)
  584. {
  585. big_num_opt = unset ? 0 : 1;
  586. return 0;
  587. }
  588. static int enable_metric_only(const struct option *opt __maybe_unused,
  589. const char *s __maybe_unused, int unset)
  590. {
  591. force_metric_only = true;
  592. stat_config.metric_only = !unset;
  593. return 0;
  594. }
  595. static int parse_metric_groups(const struct option *opt,
  596. const char *str,
  597. int unset __maybe_unused)
  598. {
  599. return metricgroup__parse_groups(opt, str, &stat_config.metric_events);
  600. }
  601. static const struct option stat_options[] = {
  602. OPT_BOOLEAN('T', "transaction", &transaction_run,
  603. "hardware transaction statistics"),
  604. OPT_CALLBACK('e', "event", &evsel_list, "event",
  605. "event selector. use 'perf list' to list available events",
  606. parse_events_option),
  607. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  608. "event filter", parse_filter),
  609. OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
  610. "child tasks do not inherit counters"),
  611. OPT_STRING('p', "pid", &target.pid, "pid",
  612. "stat events on existing process id"),
  613. OPT_STRING('t', "tid", &target.tid, "tid",
  614. "stat events on existing thread id"),
  615. OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
  616. "system-wide collection from all CPUs"),
  617. OPT_BOOLEAN('g', "group", &group,
  618. "put the counters into a counter group"),
  619. OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
  620. OPT_INCR('v', "verbose", &verbose,
  621. "be more verbose (show counter open errors, etc)"),
  622. OPT_INTEGER('r', "repeat", &stat_config.run_count,
  623. "repeat command and print average + stddev (max: 100, forever: 0)"),
  624. OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
  625. "display details about each run (only with -r option)"),
  626. OPT_BOOLEAN('n', "null", &stat_config.null_run,
  627. "null run - dont start any counters"),
  628. OPT_INCR('d', "detailed", &detailed_run,
  629. "detailed run - start a lot of events"),
  630. OPT_BOOLEAN('S', "sync", &sync_run,
  631. "call sync() before starting a run"),
  632. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  633. "print large numbers with thousands\' separators",
  634. stat__set_big_num),
  635. OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
  636. "list of cpus to monitor in system-wide"),
  637. OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
  638. "disable CPU count aggregation", AGGR_NONE),
  639. OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
  640. OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
  641. "print counts with custom separator"),
  642. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  643. "monitor event in cgroup name only", parse_cgroups),
  644. OPT_STRING('o', "output", &output_name, "file", "output file name"),
  645. OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
  646. OPT_INTEGER(0, "log-fd", &output_fd,
  647. "log output to fd, instead of stderr"),
  648. OPT_STRING(0, "pre", &pre_cmd, "command",
  649. "command to run prior to the measured command"),
  650. OPT_STRING(0, "post", &post_cmd, "command",
  651. "command to run after to the measured command"),
  652. OPT_UINTEGER('I', "interval-print", &stat_config.interval,
  653. "print counts at regular interval in ms "
  654. "(overhead is possible for values <= 100ms)"),
  655. OPT_INTEGER(0, "interval-count", &stat_config.times,
  656. "print counts for fixed number of times"),
  657. OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
  658. "clear screen in between new interval"),
  659. OPT_UINTEGER(0, "timeout", &stat_config.timeout,
  660. "stop workload and print counts after a timeout period in ms (>= 10ms)"),
  661. OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
  662. "aggregate counts per processor socket", AGGR_SOCKET),
  663. OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
  664. "aggregate counts per physical processor core", AGGR_CORE),
  665. OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
  666. "aggregate counts per thread", AGGR_THREAD),
  667. OPT_UINTEGER('D', "delay", &stat_config.initial_delay,
  668. "ms to wait before starting measurement after program start"),
  669. OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
  670. "Only print computed metrics. No raw values", enable_metric_only),
  671. OPT_BOOLEAN(0, "topdown", &topdown_run,
  672. "measure topdown level 1 statistics"),
  673. OPT_BOOLEAN(0, "smi-cost", &smi_cost,
  674. "measure SMI cost"),
  675. OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
  676. "monitor specified metrics or metric groups (separated by ,)",
  677. parse_metric_groups),
  678. OPT_END()
  679. };
  680. static int perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
  681. struct cpu_map *map, int cpu)
  682. {
  683. return cpu_map__get_socket(map, cpu, NULL);
  684. }
  685. static int perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
  686. struct cpu_map *map, int cpu)
  687. {
  688. return cpu_map__get_core(map, cpu, NULL);
  689. }
  690. static int cpu_map__get_max(struct cpu_map *map)
  691. {
  692. int i, max = -1;
  693. for (i = 0; i < map->nr; i++) {
  694. if (map->map[i] > max)
  695. max = map->map[i];
  696. }
  697. return max;
  698. }
  699. static int perf_stat__get_aggr(struct perf_stat_config *config,
  700. aggr_get_id_t get_id, struct cpu_map *map, int idx)
  701. {
  702. int cpu;
  703. if (idx >= map->nr)
  704. return -1;
  705. cpu = map->map[idx];
  706. if (config->cpus_aggr_map->map[cpu] == -1)
  707. config->cpus_aggr_map->map[cpu] = get_id(config, map, idx);
  708. return config->cpus_aggr_map->map[cpu];
  709. }
  710. static int perf_stat__get_socket_cached(struct perf_stat_config *config,
  711. struct cpu_map *map, int idx)
  712. {
  713. return perf_stat__get_aggr(config, perf_stat__get_socket, map, idx);
  714. }
  715. static int perf_stat__get_core_cached(struct perf_stat_config *config,
  716. struct cpu_map *map, int idx)
  717. {
  718. return perf_stat__get_aggr(config, perf_stat__get_core, map, idx);
  719. }
  720. static int perf_stat_init_aggr_mode(void)
  721. {
  722. int nr;
  723. switch (stat_config.aggr_mode) {
  724. case AGGR_SOCKET:
  725. if (cpu_map__build_socket_map(evsel_list->cpus, &stat_config.aggr_map)) {
  726. perror("cannot build socket map");
  727. return -1;
  728. }
  729. stat_config.aggr_get_id = perf_stat__get_socket_cached;
  730. break;
  731. case AGGR_CORE:
  732. if (cpu_map__build_core_map(evsel_list->cpus, &stat_config.aggr_map)) {
  733. perror("cannot build core map");
  734. return -1;
  735. }
  736. stat_config.aggr_get_id = perf_stat__get_core_cached;
  737. break;
  738. case AGGR_NONE:
  739. case AGGR_GLOBAL:
  740. case AGGR_THREAD:
  741. case AGGR_UNSET:
  742. default:
  743. break;
  744. }
  745. /*
  746. * The evsel_list->cpus is the base we operate on,
  747. * taking the highest cpu number to be the size of
  748. * the aggregation translate cpumap.
  749. */
  750. nr = cpu_map__get_max(evsel_list->cpus);
  751. stat_config.cpus_aggr_map = cpu_map__empty_new(nr + 1);
  752. return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
  753. }
  754. static void perf_stat__exit_aggr_mode(void)
  755. {
  756. cpu_map__put(stat_config.aggr_map);
  757. cpu_map__put(stat_config.cpus_aggr_map);
  758. stat_config.aggr_map = NULL;
  759. stat_config.cpus_aggr_map = NULL;
  760. }
  761. static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
  762. {
  763. int cpu;
  764. if (idx > map->nr)
  765. return -1;
  766. cpu = map->map[idx];
  767. if (cpu >= env->nr_cpus_avail)
  768. return -1;
  769. return cpu;
  770. }
  771. static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
  772. {
  773. struct perf_env *env = data;
  774. int cpu = perf_env__get_cpu(env, map, idx);
  775. return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
  776. }
  777. static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
  778. {
  779. struct perf_env *env = data;
  780. int core = -1, cpu = perf_env__get_cpu(env, map, idx);
  781. if (cpu != -1) {
  782. int socket_id = env->cpu[cpu].socket_id;
  783. /*
  784. * Encode socket in upper 16 bits
  785. * core_id is relative to socket, and
  786. * we need a global id. So we combine
  787. * socket + core id.
  788. */
  789. core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
  790. }
  791. return core;
  792. }
  793. static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
  794. struct cpu_map **sockp)
  795. {
  796. return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
  797. }
  798. static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
  799. struct cpu_map **corep)
  800. {
  801. return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
  802. }
  803. static int perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
  804. struct cpu_map *map, int idx)
  805. {
  806. return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
  807. }
  808. static int perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
  809. struct cpu_map *map, int idx)
  810. {
  811. return perf_env__get_core(map, idx, &perf_stat.session->header.env);
  812. }
  813. static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
  814. {
  815. struct perf_env *env = &st->session->header.env;
  816. switch (stat_config.aggr_mode) {
  817. case AGGR_SOCKET:
  818. if (perf_env__build_socket_map(env, evsel_list->cpus, &stat_config.aggr_map)) {
  819. perror("cannot build socket map");
  820. return -1;
  821. }
  822. stat_config.aggr_get_id = perf_stat__get_socket_file;
  823. break;
  824. case AGGR_CORE:
  825. if (perf_env__build_core_map(env, evsel_list->cpus, &stat_config.aggr_map)) {
  826. perror("cannot build core map");
  827. return -1;
  828. }
  829. stat_config.aggr_get_id = perf_stat__get_core_file;
  830. break;
  831. case AGGR_NONE:
  832. case AGGR_GLOBAL:
  833. case AGGR_THREAD:
  834. case AGGR_UNSET:
  835. default:
  836. break;
  837. }
  838. return 0;
  839. }
  840. static int topdown_filter_events(const char **attr, char **str, bool use_group)
  841. {
  842. int off = 0;
  843. int i;
  844. int len = 0;
  845. char *s;
  846. for (i = 0; attr[i]; i++) {
  847. if (pmu_have_event("cpu", attr[i])) {
  848. len += strlen(attr[i]) + 1;
  849. attr[i - off] = attr[i];
  850. } else
  851. off++;
  852. }
  853. attr[i - off] = NULL;
  854. *str = malloc(len + 1 + 2);
  855. if (!*str)
  856. return -1;
  857. s = *str;
  858. if (i - off == 0) {
  859. *s = 0;
  860. return 0;
  861. }
  862. if (use_group)
  863. *s++ = '{';
  864. for (i = 0; attr[i]; i++) {
  865. strcpy(s, attr[i]);
  866. s += strlen(s);
  867. *s++ = ',';
  868. }
  869. if (use_group) {
  870. s[-1] = '}';
  871. *s = 0;
  872. } else
  873. s[-1] = 0;
  874. return 0;
  875. }
  876. __weak bool arch_topdown_check_group(bool *warn)
  877. {
  878. *warn = false;
  879. return false;
  880. }
  881. __weak void arch_topdown_group_warn(void)
  882. {
  883. }
  884. /*
  885. * Add default attributes, if there were no attributes specified or
  886. * if -d/--detailed, -d -d or -d -d -d is used:
  887. */
  888. static int add_default_attributes(void)
  889. {
  890. int err;
  891. struct perf_event_attr default_attrs0[] = {
  892. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  893. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  894. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  895. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  896. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  897. };
  898. struct perf_event_attr frontend_attrs[] = {
  899. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
  900. };
  901. struct perf_event_attr backend_attrs[] = {
  902. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
  903. };
  904. struct perf_event_attr default_attrs1[] = {
  905. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  906. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  907. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  908. };
  909. /*
  910. * Detailed stats (-d), covering the L1 and last level data caches:
  911. */
  912. struct perf_event_attr detailed_attrs[] = {
  913. { .type = PERF_TYPE_HW_CACHE,
  914. .config =
  915. PERF_COUNT_HW_CACHE_L1D << 0 |
  916. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  917. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  918. { .type = PERF_TYPE_HW_CACHE,
  919. .config =
  920. PERF_COUNT_HW_CACHE_L1D << 0 |
  921. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  922. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  923. { .type = PERF_TYPE_HW_CACHE,
  924. .config =
  925. PERF_COUNT_HW_CACHE_LL << 0 |
  926. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  927. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  928. { .type = PERF_TYPE_HW_CACHE,
  929. .config =
  930. PERF_COUNT_HW_CACHE_LL << 0 |
  931. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  932. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  933. };
  934. /*
  935. * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
  936. */
  937. struct perf_event_attr very_detailed_attrs[] = {
  938. { .type = PERF_TYPE_HW_CACHE,
  939. .config =
  940. PERF_COUNT_HW_CACHE_L1I << 0 |
  941. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  942. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  943. { .type = PERF_TYPE_HW_CACHE,
  944. .config =
  945. PERF_COUNT_HW_CACHE_L1I << 0 |
  946. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  947. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  948. { .type = PERF_TYPE_HW_CACHE,
  949. .config =
  950. PERF_COUNT_HW_CACHE_DTLB << 0 |
  951. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  952. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  953. { .type = PERF_TYPE_HW_CACHE,
  954. .config =
  955. PERF_COUNT_HW_CACHE_DTLB << 0 |
  956. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  957. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  958. { .type = PERF_TYPE_HW_CACHE,
  959. .config =
  960. PERF_COUNT_HW_CACHE_ITLB << 0 |
  961. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  962. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  963. { .type = PERF_TYPE_HW_CACHE,
  964. .config =
  965. PERF_COUNT_HW_CACHE_ITLB << 0 |
  966. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  967. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  968. };
  969. /*
  970. * Very, very detailed stats (-d -d -d), adding prefetch events:
  971. */
  972. struct perf_event_attr very_very_detailed_attrs[] = {
  973. { .type = PERF_TYPE_HW_CACHE,
  974. .config =
  975. PERF_COUNT_HW_CACHE_L1D << 0 |
  976. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  977. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  978. { .type = PERF_TYPE_HW_CACHE,
  979. .config =
  980. PERF_COUNT_HW_CACHE_L1D << 0 |
  981. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  982. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  983. };
  984. struct parse_events_error errinfo;
  985. /* Set attrs if no event is selected and !null_run: */
  986. if (stat_config.null_run)
  987. return 0;
  988. if (transaction_run) {
  989. /* Handle -T as -M transaction. Once platform specific metrics
  990. * support has been added to the json files, all archictures
  991. * will use this approach. To determine transaction support
  992. * on an architecture test for such a metric name.
  993. */
  994. if (metricgroup__has_metric("transaction")) {
  995. struct option opt = { .value = &evsel_list };
  996. return metricgroup__parse_groups(&opt, "transaction",
  997. &stat_config.metric_events);
  998. }
  999. if (pmu_have_event("cpu", "cycles-ct") &&
  1000. pmu_have_event("cpu", "el-start"))
  1001. err = parse_events(evsel_list, transaction_attrs,
  1002. &errinfo);
  1003. else
  1004. err = parse_events(evsel_list,
  1005. transaction_limited_attrs,
  1006. &errinfo);
  1007. if (err) {
  1008. fprintf(stderr, "Cannot set up transaction events\n");
  1009. parse_events_print_error(&errinfo, transaction_attrs);
  1010. return -1;
  1011. }
  1012. return 0;
  1013. }
  1014. if (smi_cost) {
  1015. int smi;
  1016. if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
  1017. fprintf(stderr, "freeze_on_smi is not supported.\n");
  1018. return -1;
  1019. }
  1020. if (!smi) {
  1021. if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
  1022. fprintf(stderr, "Failed to set freeze_on_smi.\n");
  1023. return -1;
  1024. }
  1025. smi_reset = true;
  1026. }
  1027. if (pmu_have_event("msr", "aperf") &&
  1028. pmu_have_event("msr", "smi")) {
  1029. if (!force_metric_only)
  1030. stat_config.metric_only = true;
  1031. err = parse_events(evsel_list, smi_cost_attrs, &errinfo);
  1032. } else {
  1033. fprintf(stderr, "To measure SMI cost, it needs "
  1034. "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
  1035. parse_events_print_error(&errinfo, smi_cost_attrs);
  1036. return -1;
  1037. }
  1038. if (err) {
  1039. fprintf(stderr, "Cannot set up SMI cost events\n");
  1040. return -1;
  1041. }
  1042. return 0;
  1043. }
  1044. if (topdown_run) {
  1045. char *str = NULL;
  1046. bool warn = false;
  1047. if (stat_config.aggr_mode != AGGR_GLOBAL &&
  1048. stat_config.aggr_mode != AGGR_CORE) {
  1049. pr_err("top down event configuration requires --per-core mode\n");
  1050. return -1;
  1051. }
  1052. stat_config.aggr_mode = AGGR_CORE;
  1053. if (nr_cgroups || !target__has_cpu(&target)) {
  1054. pr_err("top down event configuration requires system-wide mode (-a)\n");
  1055. return -1;
  1056. }
  1057. if (!force_metric_only)
  1058. stat_config.metric_only = true;
  1059. if (topdown_filter_events(topdown_attrs, &str,
  1060. arch_topdown_check_group(&warn)) < 0) {
  1061. pr_err("Out of memory\n");
  1062. return -1;
  1063. }
  1064. if (topdown_attrs[0] && str) {
  1065. if (warn)
  1066. arch_topdown_group_warn();
  1067. err = parse_events(evsel_list, str, &errinfo);
  1068. if (err) {
  1069. fprintf(stderr,
  1070. "Cannot set up top down events %s: %d\n",
  1071. str, err);
  1072. free(str);
  1073. parse_events_print_error(&errinfo, str);
  1074. return -1;
  1075. }
  1076. } else {
  1077. fprintf(stderr, "System does not support topdown\n");
  1078. return -1;
  1079. }
  1080. free(str);
  1081. }
  1082. if (!evsel_list->nr_entries) {
  1083. if (target__has_cpu(&target))
  1084. default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
  1085. if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
  1086. return -1;
  1087. if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
  1088. if (perf_evlist__add_default_attrs(evsel_list,
  1089. frontend_attrs) < 0)
  1090. return -1;
  1091. }
  1092. if (pmu_have_event("cpu", "stalled-cycles-backend")) {
  1093. if (perf_evlist__add_default_attrs(evsel_list,
  1094. backend_attrs) < 0)
  1095. return -1;
  1096. }
  1097. if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
  1098. return -1;
  1099. }
  1100. /* Detailed events get appended to the event list: */
  1101. if (detailed_run < 1)
  1102. return 0;
  1103. /* Append detailed run extra attributes: */
  1104. if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
  1105. return -1;
  1106. if (detailed_run < 2)
  1107. return 0;
  1108. /* Append very detailed run extra attributes: */
  1109. if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
  1110. return -1;
  1111. if (detailed_run < 3)
  1112. return 0;
  1113. /* Append very, very detailed run extra attributes: */
  1114. return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
  1115. }
  1116. static const char * const stat_record_usage[] = {
  1117. "perf stat record [<options>]",
  1118. NULL,
  1119. };
  1120. static void init_features(struct perf_session *session)
  1121. {
  1122. int feat;
  1123. for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
  1124. perf_header__set_feat(&session->header, feat);
  1125. perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
  1126. perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
  1127. perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
  1128. perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
  1129. }
  1130. static int __cmd_record(int argc, const char **argv)
  1131. {
  1132. struct perf_session *session;
  1133. struct perf_data *data = &perf_stat.data;
  1134. argc = parse_options(argc, argv, stat_options, stat_record_usage,
  1135. PARSE_OPT_STOP_AT_NON_OPTION);
  1136. if (output_name)
  1137. data->file.path = output_name;
  1138. if (stat_config.run_count != 1 || forever) {
  1139. pr_err("Cannot use -r option with perf stat record.\n");
  1140. return -1;
  1141. }
  1142. session = perf_session__new(data, false, NULL);
  1143. if (session == NULL) {
  1144. pr_err("Perf session creation failed.\n");
  1145. return -1;
  1146. }
  1147. init_features(session);
  1148. session->evlist = evsel_list;
  1149. perf_stat.session = session;
  1150. perf_stat.record = true;
  1151. return argc;
  1152. }
  1153. static int process_stat_round_event(struct perf_session *session,
  1154. union perf_event *event)
  1155. {
  1156. struct stat_round_event *stat_round = &event->stat_round;
  1157. struct perf_evsel *counter;
  1158. struct timespec tsh, *ts = NULL;
  1159. const char **argv = session->header.env.cmdline_argv;
  1160. int argc = session->header.env.nr_cmdline;
  1161. evlist__for_each_entry(evsel_list, counter)
  1162. perf_stat_process_counter(&stat_config, counter);
  1163. if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
  1164. update_stats(&walltime_nsecs_stats, stat_round->time);
  1165. if (stat_config.interval && stat_round->time) {
  1166. tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
  1167. tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
  1168. ts = &tsh;
  1169. }
  1170. print_counters(ts, argc, argv);
  1171. return 0;
  1172. }
  1173. static
  1174. int process_stat_config_event(struct perf_session *session,
  1175. union perf_event *event)
  1176. {
  1177. struct perf_tool *tool = session->tool;
  1178. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  1179. perf_event__read_stat_config(&stat_config, &event->stat_config);
  1180. if (cpu_map__empty(st->cpus)) {
  1181. if (st->aggr_mode != AGGR_UNSET)
  1182. pr_warning("warning: processing task data, aggregation mode not set\n");
  1183. return 0;
  1184. }
  1185. if (st->aggr_mode != AGGR_UNSET)
  1186. stat_config.aggr_mode = st->aggr_mode;
  1187. if (perf_stat.data.is_pipe)
  1188. perf_stat_init_aggr_mode();
  1189. else
  1190. perf_stat_init_aggr_mode_file(st);
  1191. return 0;
  1192. }
  1193. static int set_maps(struct perf_stat *st)
  1194. {
  1195. if (!st->cpus || !st->threads)
  1196. return 0;
  1197. if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
  1198. return -EINVAL;
  1199. perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
  1200. if (perf_evlist__alloc_stats(evsel_list, true))
  1201. return -ENOMEM;
  1202. st->maps_allocated = true;
  1203. return 0;
  1204. }
  1205. static
  1206. int process_thread_map_event(struct perf_session *session,
  1207. union perf_event *event)
  1208. {
  1209. struct perf_tool *tool = session->tool;
  1210. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  1211. if (st->threads) {
  1212. pr_warning("Extra thread map event, ignoring.\n");
  1213. return 0;
  1214. }
  1215. st->threads = thread_map__new_event(&event->thread_map);
  1216. if (!st->threads)
  1217. return -ENOMEM;
  1218. return set_maps(st);
  1219. }
  1220. static
  1221. int process_cpu_map_event(struct perf_session *session,
  1222. union perf_event *event)
  1223. {
  1224. struct perf_tool *tool = session->tool;
  1225. struct perf_stat *st = container_of(tool, struct perf_stat, tool);
  1226. struct cpu_map *cpus;
  1227. if (st->cpus) {
  1228. pr_warning("Extra cpu map event, ignoring.\n");
  1229. return 0;
  1230. }
  1231. cpus = cpu_map__new_data(&event->cpu_map.data);
  1232. if (!cpus)
  1233. return -ENOMEM;
  1234. st->cpus = cpus;
  1235. return set_maps(st);
  1236. }
  1237. static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
  1238. {
  1239. int i;
  1240. config->stats = calloc(nthreads, sizeof(struct runtime_stat));
  1241. if (!config->stats)
  1242. return -1;
  1243. config->stats_num = nthreads;
  1244. for (i = 0; i < nthreads; i++)
  1245. runtime_stat__init(&config->stats[i]);
  1246. return 0;
  1247. }
  1248. static void runtime_stat_delete(struct perf_stat_config *config)
  1249. {
  1250. int i;
  1251. if (!config->stats)
  1252. return;
  1253. for (i = 0; i < config->stats_num; i++)
  1254. runtime_stat__exit(&config->stats[i]);
  1255. free(config->stats);
  1256. }
  1257. static const char * const stat_report_usage[] = {
  1258. "perf stat report [<options>]",
  1259. NULL,
  1260. };
  1261. static struct perf_stat perf_stat = {
  1262. .tool = {
  1263. .attr = perf_event__process_attr,
  1264. .event_update = perf_event__process_event_update,
  1265. .thread_map = process_thread_map_event,
  1266. .cpu_map = process_cpu_map_event,
  1267. .stat_config = process_stat_config_event,
  1268. .stat = perf_event__process_stat_event,
  1269. .stat_round = process_stat_round_event,
  1270. },
  1271. .aggr_mode = AGGR_UNSET,
  1272. };
  1273. static int __cmd_report(int argc, const char **argv)
  1274. {
  1275. struct perf_session *session;
  1276. const struct option options[] = {
  1277. OPT_STRING('i', "input", &input_name, "file", "input file name"),
  1278. OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
  1279. "aggregate counts per processor socket", AGGR_SOCKET),
  1280. OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
  1281. "aggregate counts per physical processor core", AGGR_CORE),
  1282. OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
  1283. "disable CPU count aggregation", AGGR_NONE),
  1284. OPT_END()
  1285. };
  1286. struct stat st;
  1287. int ret;
  1288. argc = parse_options(argc, argv, options, stat_report_usage, 0);
  1289. if (!input_name || !strlen(input_name)) {
  1290. if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
  1291. input_name = "-";
  1292. else
  1293. input_name = "perf.data";
  1294. }
  1295. perf_stat.data.file.path = input_name;
  1296. perf_stat.data.mode = PERF_DATA_MODE_READ;
  1297. session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
  1298. if (session == NULL)
  1299. return -1;
  1300. perf_stat.session = session;
  1301. stat_config.output = stderr;
  1302. evsel_list = session->evlist;
  1303. ret = perf_session__process_events(session);
  1304. if (ret)
  1305. return ret;
  1306. perf_session__delete(session);
  1307. return 0;
  1308. }
  1309. static void setup_system_wide(int forks)
  1310. {
  1311. /*
  1312. * Make system wide (-a) the default target if
  1313. * no target was specified and one of following
  1314. * conditions is met:
  1315. *
  1316. * - there's no workload specified
  1317. * - there is workload specified but all requested
  1318. * events are system wide events
  1319. */
  1320. if (!target__none(&target))
  1321. return;
  1322. if (!forks)
  1323. target.system_wide = true;
  1324. else {
  1325. struct perf_evsel *counter;
  1326. evlist__for_each_entry(evsel_list, counter) {
  1327. if (!counter->system_wide)
  1328. return;
  1329. }
  1330. if (evsel_list->nr_entries)
  1331. target.system_wide = true;
  1332. }
  1333. }
  1334. int cmd_stat(int argc, const char **argv)
  1335. {
  1336. const char * const stat_usage[] = {
  1337. "perf stat [<options>] [<command>]",
  1338. NULL
  1339. };
  1340. int status = -EINVAL, run_idx;
  1341. const char *mode;
  1342. FILE *output = stderr;
  1343. unsigned int interval, timeout;
  1344. const char * const stat_subcommands[] = { "record", "report" };
  1345. setlocale(LC_ALL, "");
  1346. evsel_list = perf_evlist__new();
  1347. if (evsel_list == NULL)
  1348. return -ENOMEM;
  1349. parse_events__shrink_config_terms();
  1350. argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
  1351. (const char **) stat_usage,
  1352. PARSE_OPT_STOP_AT_NON_OPTION);
  1353. perf_stat__collect_metric_expr(evsel_list);
  1354. perf_stat__init_shadow_stats();
  1355. if (stat_config.csv_sep) {
  1356. stat_config.csv_output = true;
  1357. if (!strcmp(stat_config.csv_sep, "\\t"))
  1358. stat_config.csv_sep = "\t";
  1359. } else
  1360. stat_config.csv_sep = DEFAULT_SEPARATOR;
  1361. if (argc && !strncmp(argv[0], "rec", 3)) {
  1362. argc = __cmd_record(argc, argv);
  1363. if (argc < 0)
  1364. return -1;
  1365. } else if (argc && !strncmp(argv[0], "rep", 3))
  1366. return __cmd_report(argc, argv);
  1367. interval = stat_config.interval;
  1368. timeout = stat_config.timeout;
  1369. /*
  1370. * For record command the -o is already taken care of.
  1371. */
  1372. if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
  1373. output = NULL;
  1374. if (output_name && output_fd) {
  1375. fprintf(stderr, "cannot use both --output and --log-fd\n");
  1376. parse_options_usage(stat_usage, stat_options, "o", 1);
  1377. parse_options_usage(NULL, stat_options, "log-fd", 0);
  1378. goto out;
  1379. }
  1380. if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
  1381. fprintf(stderr, "--metric-only is not supported with --per-thread\n");
  1382. goto out;
  1383. }
  1384. if (stat_config.metric_only && stat_config.run_count > 1) {
  1385. fprintf(stderr, "--metric-only is not supported with -r\n");
  1386. goto out;
  1387. }
  1388. if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
  1389. fprintf(stderr, "--table is only supported with -r\n");
  1390. parse_options_usage(stat_usage, stat_options, "r", 1);
  1391. parse_options_usage(NULL, stat_options, "table", 0);
  1392. goto out;
  1393. }
  1394. if (output_fd < 0) {
  1395. fprintf(stderr, "argument to --log-fd must be a > 0\n");
  1396. parse_options_usage(stat_usage, stat_options, "log-fd", 0);
  1397. goto out;
  1398. }
  1399. if (!output) {
  1400. struct timespec tm;
  1401. mode = append_file ? "a" : "w";
  1402. output = fopen(output_name, mode);
  1403. if (!output) {
  1404. perror("failed to create output file");
  1405. return -1;
  1406. }
  1407. clock_gettime(CLOCK_REALTIME, &tm);
  1408. fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
  1409. } else if (output_fd > 0) {
  1410. mode = append_file ? "a" : "w";
  1411. output = fdopen(output_fd, mode);
  1412. if (!output) {
  1413. perror("Failed opening logfd");
  1414. return -errno;
  1415. }
  1416. }
  1417. stat_config.output = output;
  1418. /*
  1419. * let the spreadsheet do the pretty-printing
  1420. */
  1421. if (stat_config.csv_output) {
  1422. /* User explicitly passed -B? */
  1423. if (big_num_opt == 1) {
  1424. fprintf(stderr, "-B option not supported with -x\n");
  1425. parse_options_usage(stat_usage, stat_options, "B", 1);
  1426. parse_options_usage(NULL, stat_options, "x", 1);
  1427. goto out;
  1428. } else /* Nope, so disable big number formatting */
  1429. stat_config.big_num = false;
  1430. } else if (big_num_opt == 0) /* User passed --no-big-num */
  1431. stat_config.big_num = false;
  1432. setup_system_wide(argc);
  1433. /*
  1434. * Display user/system times only for single
  1435. * run and when there's specified tracee.
  1436. */
  1437. if ((stat_config.run_count == 1) && target__none(&target))
  1438. stat_config.ru_display = true;
  1439. if (stat_config.run_count < 0) {
  1440. pr_err("Run count must be a positive number\n");
  1441. parse_options_usage(stat_usage, stat_options, "r", 1);
  1442. goto out;
  1443. } else if (stat_config.run_count == 0) {
  1444. forever = true;
  1445. stat_config.run_count = 1;
  1446. }
  1447. if (stat_config.walltime_run_table) {
  1448. stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
  1449. if (!stat_config.walltime_run) {
  1450. pr_err("failed to setup -r option");
  1451. goto out;
  1452. }
  1453. }
  1454. if ((stat_config.aggr_mode == AGGR_THREAD) &&
  1455. !target__has_task(&target)) {
  1456. if (!target.system_wide || target.cpu_list) {
  1457. fprintf(stderr, "The --per-thread option is only "
  1458. "available when monitoring via -p -t -a "
  1459. "options or only --per-thread.\n");
  1460. parse_options_usage(NULL, stat_options, "p", 1);
  1461. parse_options_usage(NULL, stat_options, "t", 1);
  1462. goto out;
  1463. }
  1464. }
  1465. /*
  1466. * no_aggr, cgroup are for system-wide only
  1467. * --per-thread is aggregated per thread, we dont mix it with cpu mode
  1468. */
  1469. if (((stat_config.aggr_mode != AGGR_GLOBAL &&
  1470. stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
  1471. !target__has_cpu(&target)) {
  1472. fprintf(stderr, "both cgroup and no-aggregation "
  1473. "modes only available in system-wide mode\n");
  1474. parse_options_usage(stat_usage, stat_options, "G", 1);
  1475. parse_options_usage(NULL, stat_options, "A", 1);
  1476. parse_options_usage(NULL, stat_options, "a", 1);
  1477. goto out;
  1478. }
  1479. if (add_default_attributes())
  1480. goto out;
  1481. target__validate(&target);
  1482. if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
  1483. target.per_thread = true;
  1484. if (perf_evlist__create_maps(evsel_list, &target) < 0) {
  1485. if (target__has_task(&target)) {
  1486. pr_err("Problems finding threads of monitor\n");
  1487. parse_options_usage(stat_usage, stat_options, "p", 1);
  1488. parse_options_usage(NULL, stat_options, "t", 1);
  1489. } else if (target__has_cpu(&target)) {
  1490. perror("failed to parse CPUs map");
  1491. parse_options_usage(stat_usage, stat_options, "C", 1);
  1492. parse_options_usage(NULL, stat_options, "a", 1);
  1493. }
  1494. goto out;
  1495. }
  1496. /*
  1497. * Initialize thread_map with comm names,
  1498. * so we could print it out on output.
  1499. */
  1500. if (stat_config.aggr_mode == AGGR_THREAD) {
  1501. thread_map__read_comms(evsel_list->threads);
  1502. if (target.system_wide) {
  1503. if (runtime_stat_new(&stat_config,
  1504. thread_map__nr(evsel_list->threads))) {
  1505. goto out;
  1506. }
  1507. }
  1508. }
  1509. if (stat_config.times && interval)
  1510. interval_count = true;
  1511. else if (stat_config.times && !interval) {
  1512. pr_err("interval-count option should be used together with "
  1513. "interval-print.\n");
  1514. parse_options_usage(stat_usage, stat_options, "interval-count", 0);
  1515. parse_options_usage(stat_usage, stat_options, "I", 1);
  1516. goto out;
  1517. }
  1518. if (timeout && timeout < 100) {
  1519. if (timeout < 10) {
  1520. pr_err("timeout must be >= 10ms.\n");
  1521. parse_options_usage(stat_usage, stat_options, "timeout", 0);
  1522. goto out;
  1523. } else
  1524. pr_warning("timeout < 100ms. "
  1525. "The overhead percentage could be high in some cases. "
  1526. "Please proceed with caution.\n");
  1527. }
  1528. if (timeout && interval) {
  1529. pr_err("timeout option is not supported with interval-print.\n");
  1530. parse_options_usage(stat_usage, stat_options, "timeout", 0);
  1531. parse_options_usage(stat_usage, stat_options, "I", 1);
  1532. goto out;
  1533. }
  1534. if (perf_evlist__alloc_stats(evsel_list, interval))
  1535. goto out;
  1536. if (perf_stat_init_aggr_mode())
  1537. goto out;
  1538. /*
  1539. * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
  1540. * while avoiding that older tools show confusing messages.
  1541. *
  1542. * However for pipe sessions we need to keep it zero,
  1543. * because script's perf_evsel__check_attr is triggered
  1544. * by attr->sample_type != 0, and we can't run it on
  1545. * stat sessions.
  1546. */
  1547. stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
  1548. /*
  1549. * We dont want to block the signals - that would cause
  1550. * child tasks to inherit that and Ctrl-C would not work.
  1551. * What we want is for Ctrl-C to work in the exec()-ed
  1552. * task, but being ignored by perf stat itself:
  1553. */
  1554. atexit(sig_atexit);
  1555. if (!forever)
  1556. signal(SIGINT, skip_signal);
  1557. signal(SIGCHLD, skip_signal);
  1558. signal(SIGALRM, skip_signal);
  1559. signal(SIGABRT, skip_signal);
  1560. status = 0;
  1561. for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
  1562. if (stat_config.run_count != 1 && verbose > 0)
  1563. fprintf(output, "[ perf stat: executing run #%d ... ]\n",
  1564. run_idx + 1);
  1565. status = run_perf_stat(argc, argv, run_idx);
  1566. if (forever && status != -1) {
  1567. print_counters(NULL, argc, argv);
  1568. perf_stat__reset_stats();
  1569. }
  1570. }
  1571. if (!forever && status != -1 && !interval)
  1572. print_counters(NULL, argc, argv);
  1573. if (STAT_RECORD) {
  1574. /*
  1575. * We synthesize the kernel mmap record just so that older tools
  1576. * don't emit warnings about not being able to resolve symbols
  1577. * due to /proc/sys/kernel/kptr_restrict settings and instear provide
  1578. * a saner message about no samples being in the perf.data file.
  1579. *
  1580. * This also serves to suppress a warning about f_header.data.size == 0
  1581. * in header.c at the moment 'perf stat record' gets introduced, which
  1582. * is not really needed once we start adding the stat specific PERF_RECORD_
  1583. * records, but the need to suppress the kptr_restrict messages in older
  1584. * tools remain -acme
  1585. */
  1586. int fd = perf_data__fd(&perf_stat.data);
  1587. int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
  1588. process_synthesized_event,
  1589. &perf_stat.session->machines.host);
  1590. if (err) {
  1591. pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
  1592. "older tools may produce warnings about this file\n.");
  1593. }
  1594. if (!interval) {
  1595. if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
  1596. pr_err("failed to write stat round event\n");
  1597. }
  1598. if (!perf_stat.data.is_pipe) {
  1599. perf_stat.session->header.data_size += perf_stat.bytes_written;
  1600. perf_session__write_header(perf_stat.session, evsel_list, fd, true);
  1601. }
  1602. perf_session__delete(perf_stat.session);
  1603. }
  1604. perf_stat__exit_aggr_mode();
  1605. perf_evlist__free_stats(evsel_list);
  1606. out:
  1607. free(stat_config.walltime_run);
  1608. if (smi_cost && smi_reset)
  1609. sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
  1610. perf_evlist__delete(evsel_list);
  1611. runtime_stat_delete(&stat_config);
  1612. return status;
  1613. }