builtin-stat.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  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 "util/parse-options.h"
  42. #include "util/parse-events.h"
  43. #include "util/pmu.h"
  44. #include "util/event.h"
  45. #include "util/evlist.h"
  46. #include "util/evsel.h"
  47. #include "util/debug.h"
  48. #include "util/color.h"
  49. #include "util/stat.h"
  50. #include "util/header.h"
  51. #include "util/cpumap.h"
  52. #include "util/thread.h"
  53. #include "util/thread_map.h"
  54. #include <stdlib.h>
  55. #include <sys/prctl.h>
  56. #include <locale.h>
  57. #define DEFAULT_SEPARATOR " "
  58. #define CNTR_NOT_SUPPORTED "<not supported>"
  59. #define CNTR_NOT_COUNTED "<not counted>"
  60. static void print_counters(struct timespec *ts, int argc, const char **argv);
  61. /* Default events used for perf stat -T */
  62. static const char *transaction_attrs = {
  63. "task-clock,"
  64. "{"
  65. "instructions,"
  66. "cycles,"
  67. "cpu/cycles-t/,"
  68. "cpu/tx-start/,"
  69. "cpu/el-start/,"
  70. "cpu/cycles-ct/"
  71. "}"
  72. };
  73. /* More limited version when the CPU does not have all events. */
  74. static const char * transaction_limited_attrs = {
  75. "task-clock,"
  76. "{"
  77. "instructions,"
  78. "cycles,"
  79. "cpu/cycles-t/,"
  80. "cpu/tx-start/"
  81. "}"
  82. };
  83. static struct perf_evlist *evsel_list;
  84. static struct target target = {
  85. .uid = UINT_MAX,
  86. };
  87. static int run_count = 1;
  88. static bool no_inherit = false;
  89. static bool scale = true;
  90. static enum aggr_mode aggr_mode = AGGR_GLOBAL;
  91. static volatile pid_t child_pid = -1;
  92. static bool null_run = false;
  93. static int detailed_run = 0;
  94. static bool transaction_run;
  95. static bool big_num = true;
  96. static int big_num_opt = -1;
  97. static const char *csv_sep = NULL;
  98. static bool csv_output = false;
  99. static bool group = false;
  100. static FILE *output = NULL;
  101. static const char *pre_cmd = NULL;
  102. static const char *post_cmd = NULL;
  103. static bool sync_run = false;
  104. static unsigned int interval = 0;
  105. static unsigned int initial_delay = 0;
  106. static unsigned int unit_width = 4; /* strlen("unit") */
  107. static bool forever = false;
  108. static struct timespec ref_time;
  109. static struct cpu_map *aggr_map;
  110. static int (*aggr_get_id)(struct cpu_map *m, int cpu);
  111. static volatile int done = 0;
  112. static inline void diff_timespec(struct timespec *r, struct timespec *a,
  113. struct timespec *b)
  114. {
  115. r->tv_sec = a->tv_sec - b->tv_sec;
  116. if (a->tv_nsec < b->tv_nsec) {
  117. r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
  118. r->tv_sec--;
  119. } else {
  120. r->tv_nsec = a->tv_nsec - b->tv_nsec ;
  121. }
  122. }
  123. static void perf_stat__reset_stats(void)
  124. {
  125. perf_evlist__reset_stats(evsel_list);
  126. perf_stat__reset_shadow_stats();
  127. }
  128. static int create_perf_stat_counter(struct perf_evsel *evsel)
  129. {
  130. struct perf_event_attr *attr = &evsel->attr;
  131. if (scale)
  132. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  133. PERF_FORMAT_TOTAL_TIME_RUNNING;
  134. attr->inherit = !no_inherit;
  135. if (target__has_cpu(&target))
  136. return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
  137. if (!target__has_task(&target) && perf_evsel__is_group_leader(evsel)) {
  138. attr->disabled = 1;
  139. if (!initial_delay)
  140. attr->enable_on_exec = 1;
  141. }
  142. return perf_evsel__open_per_thread(evsel, evsel_list->threads);
  143. }
  144. /*
  145. * Does the counter have nsecs as a unit?
  146. */
  147. static inline int nsec_counter(struct perf_evsel *evsel)
  148. {
  149. if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
  150. perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  151. return 1;
  152. return 0;
  153. }
  154. static void zero_per_pkg(struct perf_evsel *counter)
  155. {
  156. if (counter->per_pkg_mask)
  157. memset(counter->per_pkg_mask, 0, MAX_NR_CPUS);
  158. }
  159. static int check_per_pkg(struct perf_evsel *counter, int cpu, bool *skip)
  160. {
  161. unsigned long *mask = counter->per_pkg_mask;
  162. struct cpu_map *cpus = perf_evsel__cpus(counter);
  163. int s;
  164. *skip = false;
  165. if (!counter->per_pkg)
  166. return 0;
  167. if (cpu_map__empty(cpus))
  168. return 0;
  169. if (!mask) {
  170. mask = zalloc(MAX_NR_CPUS);
  171. if (!mask)
  172. return -ENOMEM;
  173. counter->per_pkg_mask = mask;
  174. }
  175. s = cpu_map__get_socket(cpus, cpu);
  176. if (s < 0)
  177. return -1;
  178. *skip = test_and_set_bit(s, mask) == 1;
  179. return 0;
  180. }
  181. static int
  182. process_counter_values(struct perf_evsel *evsel, int cpu, int thread,
  183. struct perf_counts_values *count)
  184. {
  185. struct perf_counts_values *aggr = &evsel->counts->aggr;
  186. static struct perf_counts_values zero;
  187. bool skip = false;
  188. if (check_per_pkg(evsel, cpu, &skip)) {
  189. pr_err("failed to read per-pkg counter\n");
  190. return -1;
  191. }
  192. if (skip)
  193. count = &zero;
  194. switch (aggr_mode) {
  195. case AGGR_THREAD:
  196. case AGGR_CORE:
  197. case AGGR_SOCKET:
  198. case AGGR_NONE:
  199. if (!evsel->snapshot)
  200. perf_evsel__compute_deltas(evsel, cpu, thread, count);
  201. perf_counts_values__scale(count, scale, NULL);
  202. if (aggr_mode == AGGR_NONE)
  203. perf_stat__update_shadow_stats(evsel, count->values, cpu);
  204. break;
  205. case AGGR_GLOBAL:
  206. aggr->val += count->val;
  207. if (scale) {
  208. aggr->ena += count->ena;
  209. aggr->run += count->run;
  210. }
  211. default:
  212. break;
  213. }
  214. return 0;
  215. }
  216. static int process_counter_maps(struct perf_evsel *counter)
  217. {
  218. int nthreads = thread_map__nr(counter->threads);
  219. int ncpus = perf_evsel__nr_cpus(counter);
  220. int cpu, thread;
  221. if (counter->system_wide)
  222. nthreads = 1;
  223. for (thread = 0; thread < nthreads; thread++) {
  224. for (cpu = 0; cpu < ncpus; cpu++) {
  225. if (process_counter_values(counter, cpu, thread,
  226. perf_counts(counter->counts, cpu, thread)))
  227. return -1;
  228. }
  229. }
  230. return 0;
  231. }
  232. static int process_counter(struct perf_evsel *counter)
  233. {
  234. struct perf_counts_values *aggr = &counter->counts->aggr;
  235. struct perf_stat *ps = counter->priv;
  236. u64 *count = counter->counts->aggr.values;
  237. int i, ret;
  238. aggr->val = aggr->ena = aggr->run = 0;
  239. init_stats(ps->res_stats);
  240. if (counter->per_pkg)
  241. zero_per_pkg(counter);
  242. ret = process_counter_maps(counter);
  243. if (ret)
  244. return ret;
  245. if (aggr_mode != AGGR_GLOBAL)
  246. return 0;
  247. if (!counter->snapshot)
  248. perf_evsel__compute_deltas(counter, -1, -1, aggr);
  249. perf_counts_values__scale(aggr, scale, &counter->counts->scaled);
  250. for (i = 0; i < 3; i++)
  251. update_stats(&ps->res_stats[i], count[i]);
  252. if (verbose) {
  253. fprintf(output, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  254. perf_evsel__name(counter), count[0], count[1], count[2]);
  255. }
  256. /*
  257. * Save the full runtime - to allow normalization during printout:
  258. */
  259. perf_stat__update_shadow_stats(counter, count, 0);
  260. return 0;
  261. }
  262. /*
  263. * Read out the results of a single counter:
  264. * do not aggregate counts across CPUs in system-wide mode
  265. */
  266. static int read_counter(struct perf_evsel *counter)
  267. {
  268. int nthreads = thread_map__nr(evsel_list->threads);
  269. int ncpus = perf_evsel__nr_cpus(counter);
  270. int cpu, thread;
  271. if (!counter->supported)
  272. return -ENOENT;
  273. if (counter->system_wide)
  274. nthreads = 1;
  275. for (thread = 0; thread < nthreads; thread++) {
  276. for (cpu = 0; cpu < ncpus; cpu++) {
  277. struct perf_counts_values *count;
  278. count = perf_counts(counter->counts, cpu, thread);
  279. if (perf_evsel__read(counter, cpu, thread, count))
  280. return -1;
  281. }
  282. }
  283. return 0;
  284. }
  285. static void read_counters(bool close)
  286. {
  287. struct perf_evsel *counter;
  288. evlist__for_each(evsel_list, counter) {
  289. if (read_counter(counter))
  290. pr_warning("failed to read counter %s\n", counter->name);
  291. if (process_counter(counter))
  292. pr_warning("failed to process counter %s\n", counter->name);
  293. if (close) {
  294. perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
  295. thread_map__nr(evsel_list->threads));
  296. }
  297. }
  298. }
  299. static void process_interval(void)
  300. {
  301. struct timespec ts, rs;
  302. read_counters(false);
  303. clock_gettime(CLOCK_MONOTONIC, &ts);
  304. diff_timespec(&rs, &ts, &ref_time);
  305. print_counters(&rs, 0, NULL);
  306. }
  307. static void handle_initial_delay(void)
  308. {
  309. struct perf_evsel *counter;
  310. if (initial_delay) {
  311. const int ncpus = cpu_map__nr(evsel_list->cpus),
  312. nthreads = thread_map__nr(evsel_list->threads);
  313. usleep(initial_delay * 1000);
  314. evlist__for_each(evsel_list, counter)
  315. perf_evsel__enable(counter, ncpus, nthreads);
  316. }
  317. }
  318. static volatile int workload_exec_errno;
  319. /*
  320. * perf_evlist__prepare_workload will send a SIGUSR1
  321. * if the fork fails, since we asked by setting its
  322. * want_signal to true.
  323. */
  324. static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
  325. void *ucontext __maybe_unused)
  326. {
  327. workload_exec_errno = info->si_value.sival_int;
  328. }
  329. static int __run_perf_stat(int argc, const char **argv)
  330. {
  331. char msg[512];
  332. unsigned long long t0, t1;
  333. struct perf_evsel *counter;
  334. struct timespec ts;
  335. size_t l;
  336. int status = 0;
  337. const bool forks = (argc > 0);
  338. if (interval) {
  339. ts.tv_sec = interval / 1000;
  340. ts.tv_nsec = (interval % 1000) * 1000000;
  341. } else {
  342. ts.tv_sec = 1;
  343. ts.tv_nsec = 0;
  344. }
  345. if (forks) {
  346. if (perf_evlist__prepare_workload(evsel_list, &target, argv, false,
  347. workload_exec_failed_signal) < 0) {
  348. perror("failed to prepare workload");
  349. return -1;
  350. }
  351. child_pid = evsel_list->workload.pid;
  352. }
  353. if (group)
  354. perf_evlist__set_leader(evsel_list);
  355. evlist__for_each(evsel_list, counter) {
  356. if (create_perf_stat_counter(counter) < 0) {
  357. /*
  358. * PPC returns ENXIO for HW counters until 2.6.37
  359. * (behavior changed with commit b0a873e).
  360. */
  361. if (errno == EINVAL || errno == ENOSYS ||
  362. errno == ENOENT || errno == EOPNOTSUPP ||
  363. errno == ENXIO) {
  364. if (verbose)
  365. ui__warning("%s event is not supported by the kernel.\n",
  366. perf_evsel__name(counter));
  367. counter->supported = false;
  368. if ((counter->leader != counter) ||
  369. !(counter->leader->nr_members > 1))
  370. continue;
  371. }
  372. perf_evsel__open_strerror(counter, &target,
  373. errno, msg, sizeof(msg));
  374. ui__error("%s\n", msg);
  375. if (child_pid != -1)
  376. kill(child_pid, SIGTERM);
  377. return -1;
  378. }
  379. counter->supported = true;
  380. l = strlen(counter->unit);
  381. if (l > unit_width)
  382. unit_width = l;
  383. }
  384. if (perf_evlist__apply_filters(evsel_list, &counter)) {
  385. error("failed to set filter \"%s\" on event %s with %d (%s)\n",
  386. counter->filter, perf_evsel__name(counter), errno,
  387. strerror_r(errno, msg, sizeof(msg)));
  388. return -1;
  389. }
  390. /*
  391. * Enable counters and exec the command:
  392. */
  393. t0 = rdclock();
  394. clock_gettime(CLOCK_MONOTONIC, &ref_time);
  395. if (forks) {
  396. perf_evlist__start_workload(evsel_list);
  397. handle_initial_delay();
  398. if (interval) {
  399. while (!waitpid(child_pid, &status, WNOHANG)) {
  400. nanosleep(&ts, NULL);
  401. process_interval();
  402. }
  403. }
  404. wait(&status);
  405. if (workload_exec_errno) {
  406. const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
  407. pr_err("Workload failed: %s\n", emsg);
  408. return -1;
  409. }
  410. if (WIFSIGNALED(status))
  411. psignal(WTERMSIG(status), argv[0]);
  412. } else {
  413. handle_initial_delay();
  414. while (!done) {
  415. nanosleep(&ts, NULL);
  416. if (interval)
  417. process_interval();
  418. }
  419. }
  420. t1 = rdclock();
  421. update_stats(&walltime_nsecs_stats, t1 - t0);
  422. read_counters(true);
  423. return WEXITSTATUS(status);
  424. }
  425. static int run_perf_stat(int argc, const char **argv)
  426. {
  427. int ret;
  428. if (pre_cmd) {
  429. ret = system(pre_cmd);
  430. if (ret)
  431. return ret;
  432. }
  433. if (sync_run)
  434. sync();
  435. ret = __run_perf_stat(argc, argv);
  436. if (ret)
  437. return ret;
  438. if (post_cmd) {
  439. ret = system(post_cmd);
  440. if (ret)
  441. return ret;
  442. }
  443. return ret;
  444. }
  445. static void print_running(u64 run, u64 ena)
  446. {
  447. if (csv_output) {
  448. fprintf(output, "%s%" PRIu64 "%s%.2f",
  449. csv_sep,
  450. run,
  451. csv_sep,
  452. ena ? 100.0 * run / ena : 100.0);
  453. } else if (run != ena) {
  454. fprintf(output, " (%.2f%%)", 100.0 * run / ena);
  455. }
  456. }
  457. static void print_noise_pct(double total, double avg)
  458. {
  459. double pct = rel_stddev_stats(total, avg);
  460. if (csv_output)
  461. fprintf(output, "%s%.2f%%", csv_sep, pct);
  462. else if (pct)
  463. fprintf(output, " ( +-%6.2f%% )", pct);
  464. }
  465. static void print_noise(struct perf_evsel *evsel, double avg)
  466. {
  467. struct perf_stat *ps;
  468. if (run_count == 1)
  469. return;
  470. ps = evsel->priv;
  471. print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
  472. }
  473. static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
  474. {
  475. switch (aggr_mode) {
  476. case AGGR_CORE:
  477. fprintf(output, "S%d-C%*d%s%*d%s",
  478. cpu_map__id_to_socket(id),
  479. csv_output ? 0 : -8,
  480. cpu_map__id_to_cpu(id),
  481. csv_sep,
  482. csv_output ? 0 : 4,
  483. nr,
  484. csv_sep);
  485. break;
  486. case AGGR_SOCKET:
  487. fprintf(output, "S%*d%s%*d%s",
  488. csv_output ? 0 : -5,
  489. id,
  490. csv_sep,
  491. csv_output ? 0 : 4,
  492. nr,
  493. csv_sep);
  494. break;
  495. case AGGR_NONE:
  496. fprintf(output, "CPU%*d%s",
  497. csv_output ? 0 : -4,
  498. perf_evsel__cpus(evsel)->map[id], csv_sep);
  499. break;
  500. case AGGR_THREAD:
  501. fprintf(output, "%*s-%*d%s",
  502. csv_output ? 0 : 16,
  503. thread_map__comm(evsel->threads, id),
  504. csv_output ? 0 : -8,
  505. thread_map__pid(evsel->threads, id),
  506. csv_sep);
  507. break;
  508. case AGGR_GLOBAL:
  509. default:
  510. break;
  511. }
  512. }
  513. static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
  514. {
  515. double msecs = avg / 1e6;
  516. const char *fmt_v, *fmt_n;
  517. char name[25];
  518. fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
  519. fmt_n = csv_output ? "%s" : "%-25s";
  520. aggr_printout(evsel, id, nr);
  521. scnprintf(name, sizeof(name), "%s%s",
  522. perf_evsel__name(evsel), csv_output ? "" : " (msec)");
  523. fprintf(output, fmt_v, msecs, csv_sep);
  524. if (csv_output)
  525. fprintf(output, "%s%s", evsel->unit, csv_sep);
  526. else
  527. fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
  528. fprintf(output, fmt_n, name);
  529. if (evsel->cgrp)
  530. fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
  531. if (csv_output || interval)
  532. return;
  533. if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  534. fprintf(output, " # %8.3f CPUs utilized ",
  535. avg / avg_stats(&walltime_nsecs_stats));
  536. else
  537. fprintf(output, " ");
  538. }
  539. static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
  540. {
  541. double sc = evsel->scale;
  542. const char *fmt;
  543. int cpu = cpu_map__id_to_cpu(id);
  544. if (csv_output) {
  545. fmt = sc != 1.0 ? "%.2f%s" : "%.0f%s";
  546. } else {
  547. if (big_num)
  548. fmt = sc != 1.0 ? "%'18.2f%s" : "%'18.0f%s";
  549. else
  550. fmt = sc != 1.0 ? "%18.2f%s" : "%18.0f%s";
  551. }
  552. aggr_printout(evsel, id, nr);
  553. if (aggr_mode == AGGR_GLOBAL)
  554. cpu = 0;
  555. fprintf(output, fmt, avg, csv_sep);
  556. if (evsel->unit)
  557. fprintf(output, "%-*s%s",
  558. csv_output ? 0 : unit_width,
  559. evsel->unit, csv_sep);
  560. fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
  561. if (evsel->cgrp)
  562. fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
  563. if (csv_output || interval)
  564. return;
  565. perf_stat__print_shadow_stats(output, evsel, avg, cpu, aggr_mode);
  566. }
  567. static void print_aggr(char *prefix)
  568. {
  569. struct perf_evsel *counter;
  570. int cpu, cpu2, s, s2, id, nr;
  571. double uval;
  572. u64 ena, run, val;
  573. if (!(aggr_map || aggr_get_id))
  574. return;
  575. for (s = 0; s < aggr_map->nr; s++) {
  576. id = aggr_map->map[s];
  577. evlist__for_each(evsel_list, counter) {
  578. val = ena = run = 0;
  579. nr = 0;
  580. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  581. cpu2 = perf_evsel__cpus(counter)->map[cpu];
  582. s2 = aggr_get_id(evsel_list->cpus, cpu2);
  583. if (s2 != id)
  584. continue;
  585. val += perf_counts(counter->counts, cpu, 0)->val;
  586. ena += perf_counts(counter->counts, cpu, 0)->ena;
  587. run += perf_counts(counter->counts, cpu, 0)->run;
  588. nr++;
  589. }
  590. if (prefix)
  591. fprintf(output, "%s", prefix);
  592. if (run == 0 || ena == 0) {
  593. aggr_printout(counter, id, nr);
  594. fprintf(output, "%*s%s",
  595. csv_output ? 0 : 18,
  596. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  597. csv_sep);
  598. fprintf(output, "%-*s%s",
  599. csv_output ? 0 : unit_width,
  600. counter->unit, csv_sep);
  601. fprintf(output, "%*s",
  602. csv_output ? 0 : -25,
  603. perf_evsel__name(counter));
  604. if (counter->cgrp)
  605. fprintf(output, "%s%s",
  606. csv_sep, counter->cgrp->name);
  607. print_running(run, ena);
  608. fputc('\n', output);
  609. continue;
  610. }
  611. uval = val * counter->scale;
  612. if (nsec_counter(counter))
  613. nsec_printout(id, nr, counter, uval);
  614. else
  615. abs_printout(id, nr, counter, uval);
  616. if (!csv_output)
  617. print_noise(counter, 1.0);
  618. print_running(run, ena);
  619. fputc('\n', output);
  620. }
  621. }
  622. }
  623. static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
  624. {
  625. int nthreads = thread_map__nr(counter->threads);
  626. int ncpus = cpu_map__nr(counter->cpus);
  627. int cpu, thread;
  628. double uval;
  629. for (thread = 0; thread < nthreads; thread++) {
  630. u64 ena = 0, run = 0, val = 0;
  631. for (cpu = 0; cpu < ncpus; cpu++) {
  632. val += perf_counts(counter->counts, cpu, thread)->val;
  633. ena += perf_counts(counter->counts, cpu, thread)->ena;
  634. run += perf_counts(counter->counts, cpu, thread)->run;
  635. }
  636. if (prefix)
  637. fprintf(output, "%s", prefix);
  638. uval = val * counter->scale;
  639. if (nsec_counter(counter))
  640. nsec_printout(thread, 0, counter, uval);
  641. else
  642. abs_printout(thread, 0, counter, uval);
  643. if (!csv_output)
  644. print_noise(counter, 1.0);
  645. print_running(run, ena);
  646. fputc('\n', output);
  647. }
  648. }
  649. /*
  650. * Print out the results of a single counter:
  651. * aggregated counts in system-wide mode
  652. */
  653. static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
  654. {
  655. struct perf_stat *ps = counter->priv;
  656. double avg = avg_stats(&ps->res_stats[0]);
  657. int scaled = counter->counts->scaled;
  658. double uval;
  659. double avg_enabled, avg_running;
  660. avg_enabled = avg_stats(&ps->res_stats[1]);
  661. avg_running = avg_stats(&ps->res_stats[2]);
  662. if (prefix)
  663. fprintf(output, "%s", prefix);
  664. if (scaled == -1 || !counter->supported) {
  665. fprintf(output, "%*s%s",
  666. csv_output ? 0 : 18,
  667. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  668. csv_sep);
  669. fprintf(output, "%-*s%s",
  670. csv_output ? 0 : unit_width,
  671. counter->unit, csv_sep);
  672. fprintf(output, "%*s",
  673. csv_output ? 0 : -25,
  674. perf_evsel__name(counter));
  675. if (counter->cgrp)
  676. fprintf(output, "%s%s", csv_sep, counter->cgrp->name);
  677. print_running(avg_running, avg_enabled);
  678. fputc('\n', output);
  679. return;
  680. }
  681. uval = avg * counter->scale;
  682. if (nsec_counter(counter))
  683. nsec_printout(-1, 0, counter, uval);
  684. else
  685. abs_printout(-1, 0, counter, uval);
  686. print_noise(counter, avg);
  687. print_running(avg_running, avg_enabled);
  688. fprintf(output, "\n");
  689. }
  690. /*
  691. * Print out the results of a single counter:
  692. * does not use aggregated count in system-wide
  693. */
  694. static void print_counter(struct perf_evsel *counter, char *prefix)
  695. {
  696. u64 ena, run, val;
  697. double uval;
  698. int cpu;
  699. for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
  700. val = perf_counts(counter->counts, cpu, 0)->val;
  701. ena = perf_counts(counter->counts, cpu, 0)->ena;
  702. run = perf_counts(counter->counts, cpu, 0)->run;
  703. if (prefix)
  704. fprintf(output, "%s", prefix);
  705. if (run == 0 || ena == 0) {
  706. fprintf(output, "CPU%*d%s%*s%s",
  707. csv_output ? 0 : -4,
  708. perf_evsel__cpus(counter)->map[cpu], csv_sep,
  709. csv_output ? 0 : 18,
  710. counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
  711. csv_sep);
  712. fprintf(output, "%-*s%s",
  713. csv_output ? 0 : unit_width,
  714. counter->unit, csv_sep);
  715. fprintf(output, "%*s",
  716. csv_output ? 0 : -25,
  717. perf_evsel__name(counter));
  718. if (counter->cgrp)
  719. fprintf(output, "%s%s",
  720. csv_sep, counter->cgrp->name);
  721. print_running(run, ena);
  722. fputc('\n', output);
  723. continue;
  724. }
  725. uval = val * counter->scale;
  726. if (nsec_counter(counter))
  727. nsec_printout(cpu, 0, counter, uval);
  728. else
  729. abs_printout(cpu, 0, counter, uval);
  730. if (!csv_output)
  731. print_noise(counter, 1.0);
  732. print_running(run, ena);
  733. fputc('\n', output);
  734. }
  735. }
  736. static void print_interval(char *prefix, struct timespec *ts)
  737. {
  738. static int num_print_interval;
  739. sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
  740. if (num_print_interval == 0 && !csv_output) {
  741. switch (aggr_mode) {
  742. case AGGR_SOCKET:
  743. fprintf(output, "# time socket cpus counts %*s events\n", unit_width, "unit");
  744. break;
  745. case AGGR_CORE:
  746. fprintf(output, "# time core cpus counts %*s events\n", unit_width, "unit");
  747. break;
  748. case AGGR_NONE:
  749. fprintf(output, "# time CPU counts %*s events\n", unit_width, "unit");
  750. break;
  751. case AGGR_THREAD:
  752. fprintf(output, "# time comm-pid counts %*s events\n", unit_width, "unit");
  753. break;
  754. case AGGR_GLOBAL:
  755. default:
  756. fprintf(output, "# time counts %*s events\n", unit_width, "unit");
  757. }
  758. }
  759. if (++num_print_interval == 25)
  760. num_print_interval = 0;
  761. }
  762. static void print_header(int argc, const char **argv)
  763. {
  764. int i;
  765. fflush(stdout);
  766. if (!csv_output) {
  767. fprintf(output, "\n");
  768. fprintf(output, " Performance counter stats for ");
  769. if (target.system_wide)
  770. fprintf(output, "\'system wide");
  771. else if (target.cpu_list)
  772. fprintf(output, "\'CPU(s) %s", target.cpu_list);
  773. else if (!target__has_task(&target)) {
  774. fprintf(output, "\'%s", argv[0]);
  775. for (i = 1; i < argc; i++)
  776. fprintf(output, " %s", argv[i]);
  777. } else if (target.pid)
  778. fprintf(output, "process id \'%s", target.pid);
  779. else
  780. fprintf(output, "thread id \'%s", target.tid);
  781. fprintf(output, "\'");
  782. if (run_count > 1)
  783. fprintf(output, " (%d runs)", run_count);
  784. fprintf(output, ":\n\n");
  785. }
  786. }
  787. static void print_footer(void)
  788. {
  789. if (!null_run)
  790. fprintf(output, "\n");
  791. fprintf(output, " %17.9f seconds time elapsed",
  792. avg_stats(&walltime_nsecs_stats)/1e9);
  793. if (run_count > 1) {
  794. fprintf(output, " ");
  795. print_noise_pct(stddev_stats(&walltime_nsecs_stats),
  796. avg_stats(&walltime_nsecs_stats));
  797. }
  798. fprintf(output, "\n\n");
  799. }
  800. static void print_counters(struct timespec *ts, int argc, const char **argv)
  801. {
  802. struct perf_evsel *counter;
  803. char buf[64], *prefix = NULL;
  804. if (interval)
  805. print_interval(prefix = buf, ts);
  806. else
  807. print_header(argc, argv);
  808. switch (aggr_mode) {
  809. case AGGR_CORE:
  810. case AGGR_SOCKET:
  811. print_aggr(prefix);
  812. break;
  813. case AGGR_THREAD:
  814. evlist__for_each(evsel_list, counter)
  815. print_aggr_thread(counter, prefix);
  816. break;
  817. case AGGR_GLOBAL:
  818. evlist__for_each(evsel_list, counter)
  819. print_counter_aggr(counter, prefix);
  820. break;
  821. case AGGR_NONE:
  822. evlist__for_each(evsel_list, counter)
  823. print_counter(counter, prefix);
  824. break;
  825. default:
  826. break;
  827. }
  828. if (!interval && !csv_output)
  829. print_footer();
  830. fflush(output);
  831. }
  832. static volatile int signr = -1;
  833. static void skip_signal(int signo)
  834. {
  835. if ((child_pid == -1) || interval)
  836. done = 1;
  837. signr = signo;
  838. /*
  839. * render child_pid harmless
  840. * won't send SIGTERM to a random
  841. * process in case of race condition
  842. * and fast PID recycling
  843. */
  844. child_pid = -1;
  845. }
  846. static void sig_atexit(void)
  847. {
  848. sigset_t set, oset;
  849. /*
  850. * avoid race condition with SIGCHLD handler
  851. * in skip_signal() which is modifying child_pid
  852. * goal is to avoid send SIGTERM to a random
  853. * process
  854. */
  855. sigemptyset(&set);
  856. sigaddset(&set, SIGCHLD);
  857. sigprocmask(SIG_BLOCK, &set, &oset);
  858. if (child_pid != -1)
  859. kill(child_pid, SIGTERM);
  860. sigprocmask(SIG_SETMASK, &oset, NULL);
  861. if (signr == -1)
  862. return;
  863. signal(signr, SIG_DFL);
  864. kill(getpid(), signr);
  865. }
  866. static int stat__set_big_num(const struct option *opt __maybe_unused,
  867. const char *s __maybe_unused, int unset)
  868. {
  869. big_num_opt = unset ? 0 : 1;
  870. return 0;
  871. }
  872. static int perf_stat_init_aggr_mode(void)
  873. {
  874. switch (aggr_mode) {
  875. case AGGR_SOCKET:
  876. if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
  877. perror("cannot build socket map");
  878. return -1;
  879. }
  880. aggr_get_id = cpu_map__get_socket;
  881. break;
  882. case AGGR_CORE:
  883. if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
  884. perror("cannot build core map");
  885. return -1;
  886. }
  887. aggr_get_id = cpu_map__get_core;
  888. break;
  889. case AGGR_NONE:
  890. case AGGR_GLOBAL:
  891. case AGGR_THREAD:
  892. default:
  893. break;
  894. }
  895. return 0;
  896. }
  897. /*
  898. * Add default attributes, if there were no attributes specified or
  899. * if -d/--detailed, -d -d or -d -d -d is used:
  900. */
  901. static int add_default_attributes(void)
  902. {
  903. struct perf_event_attr default_attrs[] = {
  904. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  905. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  906. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  907. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  908. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  909. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
  910. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
  911. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  912. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  913. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  914. };
  915. /*
  916. * Detailed stats (-d), covering the L1 and last level data caches:
  917. */
  918. struct perf_event_attr detailed_attrs[] = {
  919. { .type = PERF_TYPE_HW_CACHE,
  920. .config =
  921. PERF_COUNT_HW_CACHE_L1D << 0 |
  922. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  923. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  924. { .type = PERF_TYPE_HW_CACHE,
  925. .config =
  926. PERF_COUNT_HW_CACHE_L1D << 0 |
  927. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  928. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  929. { .type = PERF_TYPE_HW_CACHE,
  930. .config =
  931. PERF_COUNT_HW_CACHE_LL << 0 |
  932. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  933. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  934. { .type = PERF_TYPE_HW_CACHE,
  935. .config =
  936. PERF_COUNT_HW_CACHE_LL << 0 |
  937. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  938. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  939. };
  940. /*
  941. * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
  942. */
  943. struct perf_event_attr very_detailed_attrs[] = {
  944. { .type = PERF_TYPE_HW_CACHE,
  945. .config =
  946. PERF_COUNT_HW_CACHE_L1I << 0 |
  947. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  948. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  949. { .type = PERF_TYPE_HW_CACHE,
  950. .config =
  951. PERF_COUNT_HW_CACHE_L1I << 0 |
  952. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  953. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  954. { .type = PERF_TYPE_HW_CACHE,
  955. .config =
  956. PERF_COUNT_HW_CACHE_DTLB << 0 |
  957. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  958. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  959. { .type = PERF_TYPE_HW_CACHE,
  960. .config =
  961. PERF_COUNT_HW_CACHE_DTLB << 0 |
  962. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  963. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  964. { .type = PERF_TYPE_HW_CACHE,
  965. .config =
  966. PERF_COUNT_HW_CACHE_ITLB << 0 |
  967. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  968. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  969. { .type = PERF_TYPE_HW_CACHE,
  970. .config =
  971. PERF_COUNT_HW_CACHE_ITLB << 0 |
  972. (PERF_COUNT_HW_CACHE_OP_READ << 8) |
  973. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  974. };
  975. /*
  976. * Very, very detailed stats (-d -d -d), adding prefetch events:
  977. */
  978. struct perf_event_attr very_very_detailed_attrs[] = {
  979. { .type = PERF_TYPE_HW_CACHE,
  980. .config =
  981. PERF_COUNT_HW_CACHE_L1D << 0 |
  982. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  983. (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
  984. { .type = PERF_TYPE_HW_CACHE,
  985. .config =
  986. PERF_COUNT_HW_CACHE_L1D << 0 |
  987. (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
  988. (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
  989. };
  990. /* Set attrs if no event is selected and !null_run: */
  991. if (null_run)
  992. return 0;
  993. if (transaction_run) {
  994. int err;
  995. if (pmu_have_event("cpu", "cycles-ct") &&
  996. pmu_have_event("cpu", "el-start"))
  997. err = parse_events(evsel_list, transaction_attrs, NULL);
  998. else
  999. err = parse_events(evsel_list, transaction_limited_attrs, NULL);
  1000. if (err) {
  1001. fprintf(stderr, "Cannot set up transaction events\n");
  1002. return -1;
  1003. }
  1004. return 0;
  1005. }
  1006. if (!evsel_list->nr_entries) {
  1007. if (perf_evlist__add_default_attrs(evsel_list, default_attrs) < 0)
  1008. return -1;
  1009. }
  1010. /* Detailed events get appended to the event list: */
  1011. if (detailed_run < 1)
  1012. return 0;
  1013. /* Append detailed run extra attributes: */
  1014. if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
  1015. return -1;
  1016. if (detailed_run < 2)
  1017. return 0;
  1018. /* Append very detailed run extra attributes: */
  1019. if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
  1020. return -1;
  1021. if (detailed_run < 3)
  1022. return 0;
  1023. /* Append very, very detailed run extra attributes: */
  1024. return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
  1025. }
  1026. int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
  1027. {
  1028. bool append_file = false;
  1029. int output_fd = 0;
  1030. const char *output_name = NULL;
  1031. const struct option options[] = {
  1032. OPT_BOOLEAN('T', "transaction", &transaction_run,
  1033. "hardware transaction statistics"),
  1034. OPT_CALLBACK('e', "event", &evsel_list, "event",
  1035. "event selector. use 'perf list' to list available events",
  1036. parse_events_option),
  1037. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  1038. "event filter", parse_filter),
  1039. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  1040. "child tasks do not inherit counters"),
  1041. OPT_STRING('p', "pid", &target.pid, "pid",
  1042. "stat events on existing process id"),
  1043. OPT_STRING('t', "tid", &target.tid, "tid",
  1044. "stat events on existing thread id"),
  1045. OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
  1046. "system-wide collection from all CPUs"),
  1047. OPT_BOOLEAN('g', "group", &group,
  1048. "put the counters into a counter group"),
  1049. OPT_BOOLEAN('c', "scale", &scale, "scale/normalize counters"),
  1050. OPT_INCR('v', "verbose", &verbose,
  1051. "be more verbose (show counter open errors, etc)"),
  1052. OPT_INTEGER('r', "repeat", &run_count,
  1053. "repeat command and print average + stddev (max: 100, forever: 0)"),
  1054. OPT_BOOLEAN('n', "null", &null_run,
  1055. "null run - dont start any counters"),
  1056. OPT_INCR('d', "detailed", &detailed_run,
  1057. "detailed run - start a lot of events"),
  1058. OPT_BOOLEAN('S', "sync", &sync_run,
  1059. "call sync() before starting a run"),
  1060. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  1061. "print large numbers with thousands\' separators",
  1062. stat__set_big_num),
  1063. OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
  1064. "list of cpus to monitor in system-wide"),
  1065. OPT_SET_UINT('A', "no-aggr", &aggr_mode,
  1066. "disable CPU count aggregation", AGGR_NONE),
  1067. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  1068. "print counts with custom separator"),
  1069. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  1070. "monitor event in cgroup name only", parse_cgroups),
  1071. OPT_STRING('o', "output", &output_name, "file", "output file name"),
  1072. OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
  1073. OPT_INTEGER(0, "log-fd", &output_fd,
  1074. "log output to fd, instead of stderr"),
  1075. OPT_STRING(0, "pre", &pre_cmd, "command",
  1076. "command to run prior to the measured command"),
  1077. OPT_STRING(0, "post", &post_cmd, "command",
  1078. "command to run after to the measured command"),
  1079. OPT_UINTEGER('I', "interval-print", &interval,
  1080. "print counts at regular interval in ms (>= 100)"),
  1081. OPT_SET_UINT(0, "per-socket", &aggr_mode,
  1082. "aggregate counts per processor socket", AGGR_SOCKET),
  1083. OPT_SET_UINT(0, "per-core", &aggr_mode,
  1084. "aggregate counts per physical processor core", AGGR_CORE),
  1085. OPT_SET_UINT(0, "per-thread", &aggr_mode,
  1086. "aggregate counts per thread", AGGR_THREAD),
  1087. OPT_UINTEGER('D', "delay", &initial_delay,
  1088. "ms to wait before starting measurement after program start"),
  1089. OPT_END()
  1090. };
  1091. const char * const stat_usage[] = {
  1092. "perf stat [<options>] [<command>]",
  1093. NULL
  1094. };
  1095. int status = -EINVAL, run_idx;
  1096. const char *mode;
  1097. setlocale(LC_ALL, "");
  1098. evsel_list = perf_evlist__new();
  1099. if (evsel_list == NULL)
  1100. return -ENOMEM;
  1101. argc = parse_options(argc, argv, options, stat_usage,
  1102. PARSE_OPT_STOP_AT_NON_OPTION);
  1103. output = stderr;
  1104. if (output_name && strcmp(output_name, "-"))
  1105. output = NULL;
  1106. if (output_name && output_fd) {
  1107. fprintf(stderr, "cannot use both --output and --log-fd\n");
  1108. parse_options_usage(stat_usage, options, "o", 1);
  1109. parse_options_usage(NULL, options, "log-fd", 0);
  1110. goto out;
  1111. }
  1112. if (output_fd < 0) {
  1113. fprintf(stderr, "argument to --log-fd must be a > 0\n");
  1114. parse_options_usage(stat_usage, options, "log-fd", 0);
  1115. goto out;
  1116. }
  1117. if (!output) {
  1118. struct timespec tm;
  1119. mode = append_file ? "a" : "w";
  1120. output = fopen(output_name, mode);
  1121. if (!output) {
  1122. perror("failed to create output file");
  1123. return -1;
  1124. }
  1125. clock_gettime(CLOCK_REALTIME, &tm);
  1126. fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
  1127. } else if (output_fd > 0) {
  1128. mode = append_file ? "a" : "w";
  1129. output = fdopen(output_fd, mode);
  1130. if (!output) {
  1131. perror("Failed opening logfd");
  1132. return -errno;
  1133. }
  1134. }
  1135. if (csv_sep) {
  1136. csv_output = true;
  1137. if (!strcmp(csv_sep, "\\t"))
  1138. csv_sep = "\t";
  1139. } else
  1140. csv_sep = DEFAULT_SEPARATOR;
  1141. /*
  1142. * let the spreadsheet do the pretty-printing
  1143. */
  1144. if (csv_output) {
  1145. /* User explicitly passed -B? */
  1146. if (big_num_opt == 1) {
  1147. fprintf(stderr, "-B option not supported with -x\n");
  1148. parse_options_usage(stat_usage, options, "B", 1);
  1149. parse_options_usage(NULL, options, "x", 1);
  1150. goto out;
  1151. } else /* Nope, so disable big number formatting */
  1152. big_num = false;
  1153. } else if (big_num_opt == 0) /* User passed --no-big-num */
  1154. big_num = false;
  1155. if (!argc && target__none(&target))
  1156. usage_with_options(stat_usage, options);
  1157. if (run_count < 0) {
  1158. pr_err("Run count must be a positive number\n");
  1159. parse_options_usage(stat_usage, options, "r", 1);
  1160. goto out;
  1161. } else if (run_count == 0) {
  1162. forever = true;
  1163. run_count = 1;
  1164. }
  1165. if ((aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
  1166. fprintf(stderr, "The --per-thread option is only available "
  1167. "when monitoring via -p -t options.\n");
  1168. parse_options_usage(NULL, options, "p", 1);
  1169. parse_options_usage(NULL, options, "t", 1);
  1170. goto out;
  1171. }
  1172. /*
  1173. * no_aggr, cgroup are for system-wide only
  1174. * --per-thread is aggregated per thread, we dont mix it with cpu mode
  1175. */
  1176. if (((aggr_mode != AGGR_GLOBAL && aggr_mode != AGGR_THREAD) || nr_cgroups) &&
  1177. !target__has_cpu(&target)) {
  1178. fprintf(stderr, "both cgroup and no-aggregation "
  1179. "modes only available in system-wide mode\n");
  1180. parse_options_usage(stat_usage, options, "G", 1);
  1181. parse_options_usage(NULL, options, "A", 1);
  1182. parse_options_usage(NULL, options, "a", 1);
  1183. goto out;
  1184. }
  1185. if (add_default_attributes())
  1186. goto out;
  1187. target__validate(&target);
  1188. if (perf_evlist__create_maps(evsel_list, &target) < 0) {
  1189. if (target__has_task(&target)) {
  1190. pr_err("Problems finding threads of monitor\n");
  1191. parse_options_usage(stat_usage, options, "p", 1);
  1192. parse_options_usage(NULL, options, "t", 1);
  1193. } else if (target__has_cpu(&target)) {
  1194. perror("failed to parse CPUs map");
  1195. parse_options_usage(stat_usage, options, "C", 1);
  1196. parse_options_usage(NULL, options, "a", 1);
  1197. }
  1198. goto out;
  1199. }
  1200. /*
  1201. * Initialize thread_map with comm names,
  1202. * so we could print it out on output.
  1203. */
  1204. if (aggr_mode == AGGR_THREAD)
  1205. thread_map__read_comms(evsel_list->threads);
  1206. if (interval && interval < 100) {
  1207. pr_err("print interval must be >= 100ms\n");
  1208. parse_options_usage(stat_usage, options, "I", 1);
  1209. goto out;
  1210. }
  1211. if (perf_evlist__alloc_stats(evsel_list, interval))
  1212. goto out;
  1213. if (perf_stat_init_aggr_mode())
  1214. goto out;
  1215. /*
  1216. * We dont want to block the signals - that would cause
  1217. * child tasks to inherit that and Ctrl-C would not work.
  1218. * What we want is for Ctrl-C to work in the exec()-ed
  1219. * task, but being ignored by perf stat itself:
  1220. */
  1221. atexit(sig_atexit);
  1222. if (!forever)
  1223. signal(SIGINT, skip_signal);
  1224. signal(SIGCHLD, skip_signal);
  1225. signal(SIGALRM, skip_signal);
  1226. signal(SIGABRT, skip_signal);
  1227. status = 0;
  1228. for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
  1229. if (run_count != 1 && verbose)
  1230. fprintf(output, "[ perf stat: executing run #%d ... ]\n",
  1231. run_idx + 1);
  1232. status = run_perf_stat(argc, argv);
  1233. if (forever && status != -1) {
  1234. print_counters(NULL, argc, argv);
  1235. perf_stat__reset_stats();
  1236. }
  1237. }
  1238. if (!forever && status != -1 && !interval)
  1239. print_counters(NULL, argc, argv);
  1240. perf_evlist__free_stats(evsel_list);
  1241. out:
  1242. perf_evlist__delete(evsel_list);
  1243. return status;
  1244. }