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