xref: /linux/tools/perf/util/stat.c (revision bbcd53c960713507ae764bf81970651b5577b95a)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <inttypes.h>
4 #include <math.h>
5 #include <string.h>
6 #include "counts.h"
7 #include "cpumap.h"
8 #include "debug.h"
9 #include "header.h"
10 #include "stat.h"
11 #include "session.h"
12 #include "target.h"
13 #include "evlist.h"
14 #include "evsel.h"
15 #include "thread_map.h"
16 #include "hashmap.h"
17 #include <linux/zalloc.h>
18 
19 void update_stats(struct stats *stats, u64 val)
20 {
21 	double delta;
22 
23 	stats->n++;
24 	delta = val - stats->mean;
25 	stats->mean += delta / stats->n;
26 	stats->M2 += delta*(val - stats->mean);
27 
28 	if (val > stats->max)
29 		stats->max = val;
30 
31 	if (val < stats->min)
32 		stats->min = val;
33 }
34 
35 double avg_stats(struct stats *stats)
36 {
37 	return stats->mean;
38 }
39 
40 /*
41  * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
42  *
43  *       (\Sum n_i^2) - ((\Sum n_i)^2)/n
44  * s^2 = -------------------------------
45  *                  n - 1
46  *
47  * http://en.wikipedia.org/wiki/Stddev
48  *
49  * The std dev of the mean is related to the std dev by:
50  *
51  *             s
52  * s_mean = -------
53  *          sqrt(n)
54  *
55  */
56 double stddev_stats(struct stats *stats)
57 {
58 	double variance, variance_mean;
59 
60 	if (stats->n < 2)
61 		return 0.0;
62 
63 	variance = stats->M2 / (stats->n - 1);
64 	variance_mean = variance / stats->n;
65 
66 	return sqrt(variance_mean);
67 }
68 
69 double rel_stddev_stats(double stddev, double avg)
70 {
71 	double pct = 0.0;
72 
73 	if (avg)
74 		pct = 100.0 * stddev/avg;
75 
76 	return pct;
77 }
78 
79 bool __perf_evsel_stat__is(struct evsel *evsel,
80 			   enum perf_stat_evsel_id id)
81 {
82 	struct perf_stat_evsel *ps = evsel->stats;
83 
84 	return ps->id == id;
85 }
86 
87 #define ID(id, name) [PERF_STAT_EVSEL_ID__##id] = #name
88 static const char *id_str[PERF_STAT_EVSEL_ID__MAX] = {
89 	ID(NONE,		x),
90 	ID(CYCLES_IN_TX,	cpu/cycles-t/),
91 	ID(TRANSACTION_START,	cpu/tx-start/),
92 	ID(ELISION_START,	cpu/el-start/),
93 	ID(CYCLES_IN_TX_CP,	cpu/cycles-ct/),
94 	ID(TOPDOWN_TOTAL_SLOTS, topdown-total-slots),
95 	ID(TOPDOWN_SLOTS_ISSUED, topdown-slots-issued),
96 	ID(TOPDOWN_SLOTS_RETIRED, topdown-slots-retired),
97 	ID(TOPDOWN_FETCH_BUBBLES, topdown-fetch-bubbles),
98 	ID(TOPDOWN_RECOVERY_BUBBLES, topdown-recovery-bubbles),
99 	ID(TOPDOWN_RETIRING, topdown-retiring),
100 	ID(TOPDOWN_BAD_SPEC, topdown-bad-spec),
101 	ID(TOPDOWN_FE_BOUND, topdown-fe-bound),
102 	ID(TOPDOWN_BE_BOUND, topdown-be-bound),
103 	ID(TOPDOWN_HEAVY_OPS, topdown-heavy-ops),
104 	ID(TOPDOWN_BR_MISPREDICT, topdown-br-mispredict),
105 	ID(TOPDOWN_FETCH_LAT, topdown-fetch-lat),
106 	ID(TOPDOWN_MEM_BOUND, topdown-mem-bound),
107 	ID(SMI_NUM, msr/smi/),
108 	ID(APERF, msr/aperf/),
109 };
110 #undef ID
111 
112 static void perf_stat_evsel_id_init(struct evsel *evsel)
113 {
114 	struct perf_stat_evsel *ps = evsel->stats;
115 	int i;
116 
117 	/* ps->id is 0 hence PERF_STAT_EVSEL_ID__NONE by default */
118 
119 	for (i = 0; i < PERF_STAT_EVSEL_ID__MAX; i++) {
120 		if (!strcmp(evsel__name(evsel), id_str[i])) {
121 			ps->id = i;
122 			break;
123 		}
124 	}
125 }
126 
127 static void evsel__reset_stat_priv(struct evsel *evsel)
128 {
129 	int i;
130 	struct perf_stat_evsel *ps = evsel->stats;
131 
132 	for (i = 0; i < 3; i++)
133 		init_stats(&ps->res_stats[i]);
134 
135 	perf_stat_evsel_id_init(evsel);
136 }
137 
138 static int evsel__alloc_stat_priv(struct evsel *evsel)
139 {
140 	evsel->stats = zalloc(sizeof(struct perf_stat_evsel));
141 	if (evsel->stats == NULL)
142 		return -ENOMEM;
143 	evsel__reset_stat_priv(evsel);
144 	return 0;
145 }
146 
147 static void evsel__free_stat_priv(struct evsel *evsel)
148 {
149 	struct perf_stat_evsel *ps = evsel->stats;
150 
151 	if (ps)
152 		zfree(&ps->group_data);
153 	zfree(&evsel->stats);
154 }
155 
156 static int evsel__alloc_prev_raw_counts(struct evsel *evsel, int ncpus, int nthreads)
157 {
158 	struct perf_counts *counts;
159 
160 	counts = perf_counts__new(ncpus, nthreads);
161 	if (counts)
162 		evsel->prev_raw_counts = counts;
163 
164 	return counts ? 0 : -ENOMEM;
165 }
166 
167 static void evsel__free_prev_raw_counts(struct evsel *evsel)
168 {
169 	perf_counts__delete(evsel->prev_raw_counts);
170 	evsel->prev_raw_counts = NULL;
171 }
172 
173 static void evsel__reset_prev_raw_counts(struct evsel *evsel)
174 {
175 	if (evsel->prev_raw_counts)
176 		perf_counts__reset(evsel->prev_raw_counts);
177 }
178 
179 static int evsel__alloc_stats(struct evsel *evsel, bool alloc_raw)
180 {
181 	int ncpus = evsel__nr_cpus(evsel);
182 	int nthreads = perf_thread_map__nr(evsel->core.threads);
183 
184 	if (evsel__alloc_stat_priv(evsel) < 0 ||
185 	    evsel__alloc_counts(evsel, ncpus, nthreads) < 0 ||
186 	    (alloc_raw && evsel__alloc_prev_raw_counts(evsel, ncpus, nthreads) < 0))
187 		return -ENOMEM;
188 
189 	return 0;
190 }
191 
192 int evlist__alloc_stats(struct evlist *evlist, bool alloc_raw)
193 {
194 	struct evsel *evsel;
195 
196 	evlist__for_each_entry(evlist, evsel) {
197 		if (evsel__alloc_stats(evsel, alloc_raw))
198 			goto out_free;
199 	}
200 
201 	return 0;
202 
203 out_free:
204 	evlist__free_stats(evlist);
205 	return -1;
206 }
207 
208 void evlist__free_stats(struct evlist *evlist)
209 {
210 	struct evsel *evsel;
211 
212 	evlist__for_each_entry(evlist, evsel) {
213 		evsel__free_stat_priv(evsel);
214 		evsel__free_counts(evsel);
215 		evsel__free_prev_raw_counts(evsel);
216 	}
217 }
218 
219 void evlist__reset_stats(struct evlist *evlist)
220 {
221 	struct evsel *evsel;
222 
223 	evlist__for_each_entry(evlist, evsel) {
224 		evsel__reset_stat_priv(evsel);
225 		evsel__reset_counts(evsel);
226 	}
227 }
228 
229 void evlist__reset_prev_raw_counts(struct evlist *evlist)
230 {
231 	struct evsel *evsel;
232 
233 	evlist__for_each_entry(evlist, evsel)
234 		evsel__reset_prev_raw_counts(evsel);
235 }
236 
237 static void evsel__copy_prev_raw_counts(struct evsel *evsel)
238 {
239 	int ncpus = evsel__nr_cpus(evsel);
240 	int nthreads = perf_thread_map__nr(evsel->core.threads);
241 
242 	for (int thread = 0; thread < nthreads; thread++) {
243 		for (int cpu = 0; cpu < ncpus; cpu++) {
244 			*perf_counts(evsel->counts, cpu, thread) =
245 				*perf_counts(evsel->prev_raw_counts, cpu,
246 					     thread);
247 		}
248 	}
249 
250 	evsel->counts->aggr = evsel->prev_raw_counts->aggr;
251 }
252 
253 void evlist__copy_prev_raw_counts(struct evlist *evlist)
254 {
255 	struct evsel *evsel;
256 
257 	evlist__for_each_entry(evlist, evsel)
258 		evsel__copy_prev_raw_counts(evsel);
259 }
260 
261 void evlist__save_aggr_prev_raw_counts(struct evlist *evlist)
262 {
263 	struct evsel *evsel;
264 
265 	/*
266 	 * To collect the overall statistics for interval mode,
267 	 * we copy the counts from evsel->prev_raw_counts to
268 	 * evsel->counts. The perf_stat_process_counter creates
269 	 * aggr values from per cpu values, but the per cpu values
270 	 * are 0 for AGGR_GLOBAL. So we use a trick that saves the
271 	 * previous aggr value to the first member of perf_counts,
272 	 * then aggr calculation in process_counter_values can work
273 	 * correctly.
274 	 */
275 	evlist__for_each_entry(evlist, evsel) {
276 		*perf_counts(evsel->prev_raw_counts, 0, 0) =
277 			evsel->prev_raw_counts->aggr;
278 	}
279 }
280 
281 static size_t pkg_id_hash(const void *__key, void *ctx __maybe_unused)
282 {
283 	uint64_t *key = (uint64_t *) __key;
284 
285 	return *key & 0xffffffff;
286 }
287 
288 static bool pkg_id_equal(const void *__key1, const void *__key2,
289 			 void *ctx __maybe_unused)
290 {
291 	uint64_t *key1 = (uint64_t *) __key1;
292 	uint64_t *key2 = (uint64_t *) __key2;
293 
294 	return *key1 == *key2;
295 }
296 
297 static int check_per_pkg(struct evsel *counter,
298 			 struct perf_counts_values *vals, int cpu, bool *skip)
299 {
300 	struct hashmap *mask = counter->per_pkg_mask;
301 	struct perf_cpu_map *cpus = evsel__cpus(counter);
302 	int s, d, ret = 0;
303 	uint64_t *key;
304 
305 	*skip = false;
306 
307 	if (!counter->per_pkg)
308 		return 0;
309 
310 	if (perf_cpu_map__empty(cpus))
311 		return 0;
312 
313 	if (!mask) {
314 		mask = hashmap__new(pkg_id_hash, pkg_id_equal, NULL);
315 		if (!mask)
316 			return -ENOMEM;
317 
318 		counter->per_pkg_mask = mask;
319 	}
320 
321 	/*
322 	 * we do not consider an event that has not run as a good
323 	 * instance to mark a package as used (skip=1). Otherwise
324 	 * we may run into a situation where the first CPU in a package
325 	 * is not running anything, yet the second is, and this function
326 	 * would mark the package as used after the first CPU and would
327 	 * not read the values from the second CPU.
328 	 */
329 	if (!(vals->run && vals->ena))
330 		return 0;
331 
332 	s = cpu_map__get_socket(cpus, cpu, NULL).socket;
333 	if (s < 0)
334 		return -1;
335 
336 	/*
337 	 * On multi-die system, die_id > 0. On no-die system, die_id = 0.
338 	 * We use hashmap(socket, die) to check the used socket+die pair.
339 	 */
340 	d = cpu_map__get_die(cpus, cpu, NULL).die;
341 	if (d < 0)
342 		return -1;
343 
344 	key = malloc(sizeof(*key));
345 	if (!key)
346 		return -ENOMEM;
347 
348 	*key = (uint64_t)d << 32 | s;
349 	if (hashmap__find(mask, (void *)key, NULL))
350 		*skip = true;
351 	else
352 		ret = hashmap__add(mask, (void *)key, (void *)1);
353 
354 	return ret;
355 }
356 
357 static int
358 process_counter_values(struct perf_stat_config *config, struct evsel *evsel,
359 		       int cpu, int thread,
360 		       struct perf_counts_values *count)
361 {
362 	struct perf_counts_values *aggr = &evsel->counts->aggr;
363 	static struct perf_counts_values zero;
364 	bool skip = false;
365 
366 	if (check_per_pkg(evsel, count, cpu, &skip)) {
367 		pr_err("failed to read per-pkg counter\n");
368 		return -1;
369 	}
370 
371 	if (skip)
372 		count = &zero;
373 
374 	switch (config->aggr_mode) {
375 	case AGGR_THREAD:
376 	case AGGR_CORE:
377 	case AGGR_DIE:
378 	case AGGR_SOCKET:
379 	case AGGR_NODE:
380 	case AGGR_NONE:
381 		if (!evsel->snapshot)
382 			evsel__compute_deltas(evsel, cpu, thread, count);
383 		perf_counts_values__scale(count, config->scale, NULL);
384 		if ((config->aggr_mode == AGGR_NONE) && (!evsel->percore)) {
385 			perf_stat__update_shadow_stats(evsel, count->val,
386 						       cpu, &rt_stat);
387 		}
388 
389 		if (config->aggr_mode == AGGR_THREAD) {
390 			if (config->stats)
391 				perf_stat__update_shadow_stats(evsel,
392 					count->val, 0, &config->stats[thread]);
393 			else
394 				perf_stat__update_shadow_stats(evsel,
395 					count->val, 0, &rt_stat);
396 		}
397 		break;
398 	case AGGR_GLOBAL:
399 		aggr->val += count->val;
400 		aggr->ena += count->ena;
401 		aggr->run += count->run;
402 	case AGGR_UNSET:
403 	default:
404 		break;
405 	}
406 
407 	return 0;
408 }
409 
410 static int process_counter_maps(struct perf_stat_config *config,
411 				struct evsel *counter)
412 {
413 	int nthreads = perf_thread_map__nr(counter->core.threads);
414 	int ncpus = evsel__nr_cpus(counter);
415 	int cpu, thread;
416 
417 	if (counter->core.system_wide)
418 		nthreads = 1;
419 
420 	for (thread = 0; thread < nthreads; thread++) {
421 		for (cpu = 0; cpu < ncpus; cpu++) {
422 			if (process_counter_values(config, counter, cpu, thread,
423 						   perf_counts(counter->counts, cpu, thread)))
424 				return -1;
425 		}
426 	}
427 
428 	return 0;
429 }
430 
431 int perf_stat_process_counter(struct perf_stat_config *config,
432 			      struct evsel *counter)
433 {
434 	struct perf_counts_values *aggr = &counter->counts->aggr;
435 	struct perf_stat_evsel *ps = counter->stats;
436 	u64 *count = counter->counts->aggr.values;
437 	int i, ret;
438 
439 	aggr->val = aggr->ena = aggr->run = 0;
440 
441 	/*
442 	 * We calculate counter's data every interval,
443 	 * and the display code shows ps->res_stats
444 	 * avg value. We need to zero the stats for
445 	 * interval mode, otherwise overall avg running
446 	 * averages will be shown for each interval.
447 	 */
448 	if (config->interval || config->summary) {
449 		for (i = 0; i < 3; i++)
450 			init_stats(&ps->res_stats[i]);
451 	}
452 
453 	if (counter->per_pkg)
454 		evsel__zero_per_pkg(counter);
455 
456 	ret = process_counter_maps(config, counter);
457 	if (ret)
458 		return ret;
459 
460 	if (config->aggr_mode != AGGR_GLOBAL)
461 		return 0;
462 
463 	if (!counter->snapshot)
464 		evsel__compute_deltas(counter, -1, -1, aggr);
465 	perf_counts_values__scale(aggr, config->scale, &counter->counts->scaled);
466 
467 	for (i = 0; i < 3; i++)
468 		update_stats(&ps->res_stats[i], count[i]);
469 
470 	if (verbose > 0) {
471 		fprintf(config->output, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
472 			evsel__name(counter), count[0], count[1], count[2]);
473 	}
474 
475 	/*
476 	 * Save the full runtime - to allow normalization during printout:
477 	 */
478 	perf_stat__update_shadow_stats(counter, *count, 0, &rt_stat);
479 
480 	return 0;
481 }
482 
483 int perf_event__process_stat_event(struct perf_session *session,
484 				   union perf_event *event)
485 {
486 	struct perf_counts_values count;
487 	struct perf_record_stat *st = &event->stat;
488 	struct evsel *counter;
489 
490 	count.val = st->val;
491 	count.ena = st->ena;
492 	count.run = st->run;
493 
494 	counter = evlist__id2evsel(session->evlist, st->id);
495 	if (!counter) {
496 		pr_err("Failed to resolve counter for stat event.\n");
497 		return -EINVAL;
498 	}
499 
500 	*perf_counts(counter->counts, st->cpu, st->thread) = count;
501 	counter->supported = true;
502 	return 0;
503 }
504 
505 size_t perf_event__fprintf_stat(union perf_event *event, FILE *fp)
506 {
507 	struct perf_record_stat *st = (struct perf_record_stat *)event;
508 	size_t ret;
509 
510 	ret  = fprintf(fp, "\n... id %" PRI_lu64 ", cpu %d, thread %d\n",
511 		       st->id, st->cpu, st->thread);
512 	ret += fprintf(fp, "... value %" PRI_lu64 ", enabled %" PRI_lu64 ", running %" PRI_lu64 "\n",
513 		       st->val, st->ena, st->run);
514 
515 	return ret;
516 }
517 
518 size_t perf_event__fprintf_stat_round(union perf_event *event, FILE *fp)
519 {
520 	struct perf_record_stat_round *rd = (struct perf_record_stat_round *)event;
521 	size_t ret;
522 
523 	ret = fprintf(fp, "\n... time %" PRI_lu64 ", type %s\n", rd->time,
524 		      rd->type == PERF_STAT_ROUND_TYPE__FINAL ? "FINAL" : "INTERVAL");
525 
526 	return ret;
527 }
528 
529 size_t perf_event__fprintf_stat_config(union perf_event *event, FILE *fp)
530 {
531 	struct perf_stat_config sc;
532 	size_t ret;
533 
534 	perf_event__read_stat_config(&sc, &event->stat_config);
535 
536 	ret  = fprintf(fp, "\n");
537 	ret += fprintf(fp, "... aggr_mode %d\n", sc.aggr_mode);
538 	ret += fprintf(fp, "... scale     %d\n", sc.scale);
539 	ret += fprintf(fp, "... interval  %u\n", sc.interval);
540 
541 	return ret;
542 }
543 
544 int create_perf_stat_counter(struct evsel *evsel,
545 			     struct perf_stat_config *config,
546 			     struct target *target,
547 			     int cpu)
548 {
549 	struct perf_event_attr *attr = &evsel->core.attr;
550 	struct evsel *leader = evsel->leader;
551 
552 	attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
553 			    PERF_FORMAT_TOTAL_TIME_RUNNING;
554 
555 	/*
556 	 * The event is part of non trivial group, let's enable
557 	 * the group read (for leader) and ID retrieval for all
558 	 * members.
559 	 */
560 	if (leader->core.nr_members > 1)
561 		attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
562 
563 	attr->inherit = !config->no_inherit && list_empty(&evsel->bpf_counter_list);
564 
565 	/*
566 	 * Some events get initialized with sample_(period/type) set,
567 	 * like tracepoints. Clear it up for counting.
568 	 */
569 	attr->sample_period = 0;
570 
571 	if (config->identifier)
572 		attr->sample_type = PERF_SAMPLE_IDENTIFIER;
573 
574 	if (config->all_user) {
575 		attr->exclude_kernel = 1;
576 		attr->exclude_user   = 0;
577 	}
578 
579 	if (config->all_kernel) {
580 		attr->exclude_kernel = 0;
581 		attr->exclude_user   = 1;
582 	}
583 
584 	/*
585 	 * Disabling all counters initially, they will be enabled
586 	 * either manually by us or by kernel via enable_on_exec
587 	 * set later.
588 	 */
589 	if (evsel__is_group_leader(evsel)) {
590 		attr->disabled = 1;
591 
592 		/*
593 		 * In case of initial_delay we enable tracee
594 		 * events manually.
595 		 */
596 		if (target__none(target) && !config->initial_delay)
597 			attr->enable_on_exec = 1;
598 	}
599 
600 	if (target__has_cpu(target) && !target__has_per_thread(target))
601 		return evsel__open_per_cpu(evsel, evsel__cpus(evsel), cpu);
602 
603 	return evsel__open_per_thread(evsel, evsel->core.threads);
604 }
605