xref: /openbmc/linux/tools/perf/builtin-mem.c (revision 12109610)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <inttypes.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <unistd.h>
6 #include "builtin.h"
7 
8 #include <subcmd/parse-options.h>
9 #include "util/auxtrace.h"
10 #include "util/trace-event.h"
11 #include "util/tool.h"
12 #include "util/session.h"
13 #include "util/data.h"
14 #include "util/map_symbol.h"
15 #include "util/mem-events.h"
16 #include "util/debug.h"
17 #include "util/dso.h"
18 #include "util/map.h"
19 #include "util/symbol.h"
20 #include "util/pmu.h"
21 #include "util/pmu-hybrid.h"
22 #include "util/sample.h"
23 #include "util/string2.h"
24 #include "util/util.h"
25 #include <linux/err.h>
26 
27 #define MEM_OPERATION_LOAD	0x1
28 #define MEM_OPERATION_STORE	0x2
29 
30 struct perf_mem {
31 	struct perf_tool	tool;
32 	char const		*input_name;
33 	bool			hide_unresolved;
34 	bool			dump_raw;
35 	bool			force;
36 	bool			phys_addr;
37 	bool			data_page_size;
38 	int			operation;
39 	const char		*cpu_list;
40 	DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
41 };
42 
43 static int parse_record_events(const struct option *opt,
44 			       const char *str, int unset __maybe_unused)
45 {
46 	struct perf_mem *mem = *(struct perf_mem **)opt->value;
47 
48 	if (!strcmp(str, "list")) {
49 		perf_mem_events__list();
50 		exit(0);
51 	}
52 	if (perf_mem_events__parse(str))
53 		exit(-1);
54 
55 	mem->operation = 0;
56 	return 0;
57 }
58 
59 static const char * const __usage[] = {
60 	"perf mem record [<options>] [<command>]",
61 	"perf mem record [<options>] -- <command> [<options>]",
62 	NULL
63 };
64 
65 static const char * const *record_mem_usage = __usage;
66 
67 static int __cmd_record(int argc, const char **argv, struct perf_mem *mem)
68 {
69 	int rec_argc, i = 0, j, tmp_nr = 0;
70 	int start, end;
71 	const char **rec_argv;
72 	char **rec_tmp;
73 	int ret;
74 	bool all_user = false, all_kernel = false;
75 	struct perf_mem_event *e;
76 	struct option options[] = {
77 	OPT_CALLBACK('e', "event", &mem, "event",
78 		     "event selector. use 'perf mem record -e list' to list available events",
79 		     parse_record_events),
80 	OPT_UINTEGER(0, "ldlat", &perf_mem_events__loads_ldlat, "mem-loads latency"),
81 	OPT_INCR('v', "verbose", &verbose,
82 		 "be more verbose (show counter open errors, etc)"),
83 	OPT_BOOLEAN('U', "all-user", &all_user, "collect only user level data"),
84 	OPT_BOOLEAN('K', "all-kernel", &all_kernel, "collect only kernel level data"),
85 	OPT_END()
86 	};
87 
88 	if (perf_mem_events__init()) {
89 		pr_err("failed: memory events not supported\n");
90 		return -1;
91 	}
92 
93 	argc = parse_options(argc, argv, options, record_mem_usage,
94 			     PARSE_OPT_KEEP_UNKNOWN);
95 
96 	if (!perf_pmu__has_hybrid())
97 		rec_argc = argc + 9; /* max number of arguments */
98 	else
99 		rec_argc = argc + 9 * perf_pmu__hybrid_pmu_num();
100 
101 	if (mem->cpu_list)
102 		rec_argc += 2;
103 
104 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
105 	if (!rec_argv)
106 		return -1;
107 
108 	/*
109 	 * Save the allocated event name strings.
110 	 */
111 	rec_tmp = calloc(rec_argc + 1, sizeof(char *));
112 	if (!rec_tmp) {
113 		free(rec_argv);
114 		return -1;
115 	}
116 
117 	rec_argv[i++] = "record";
118 
119 	e = perf_mem_events__ptr(PERF_MEM_EVENTS__LOAD_STORE);
120 
121 	/*
122 	 * The load and store operations are required, use the event
123 	 * PERF_MEM_EVENTS__LOAD_STORE if it is supported.
124 	 */
125 	if (e->tag &&
126 	    (mem->operation & MEM_OPERATION_LOAD) &&
127 	    (mem->operation & MEM_OPERATION_STORE)) {
128 		e->record = true;
129 		rec_argv[i++] = "-W";
130 	} else {
131 		if (mem->operation & MEM_OPERATION_LOAD) {
132 			e = perf_mem_events__ptr(PERF_MEM_EVENTS__LOAD);
133 			e->record = true;
134 		}
135 
136 		if (mem->operation & MEM_OPERATION_STORE) {
137 			e = perf_mem_events__ptr(PERF_MEM_EVENTS__STORE);
138 			e->record = true;
139 		}
140 	}
141 
142 	e = perf_mem_events__ptr(PERF_MEM_EVENTS__LOAD);
143 	if (e->record)
144 		rec_argv[i++] = "-W";
145 
146 	rec_argv[i++] = "-d";
147 
148 	if (mem->phys_addr)
149 		rec_argv[i++] = "--phys-data";
150 
151 	if (mem->data_page_size)
152 		rec_argv[i++] = "--data-page-size";
153 
154 	start = i;
155 	ret = perf_mem_events__record_args(rec_argv, &i, rec_tmp, &tmp_nr);
156 	if (ret)
157 		goto out;
158 	end = i;
159 
160 	if (all_user)
161 		rec_argv[i++] = "--all-user";
162 
163 	if (all_kernel)
164 		rec_argv[i++] = "--all-kernel";
165 
166 	if (mem->cpu_list) {
167 		rec_argv[i++] = "-C";
168 		rec_argv[i++] = mem->cpu_list;
169 	}
170 
171 	for (j = 0; j < argc; j++, i++)
172 		rec_argv[i] = argv[j];
173 
174 	if (verbose > 0) {
175 		pr_debug("calling: record ");
176 
177 		for (j = start; j < end; j++)
178 			pr_debug("%s ", rec_argv[j]);
179 
180 		pr_debug("\n");
181 	}
182 
183 	ret = cmd_record(i, rec_argv);
184 out:
185 	for (i = 0; i < tmp_nr; i++)
186 		free(rec_tmp[i]);
187 
188 	free(rec_tmp);
189 	free(rec_argv);
190 	return ret;
191 }
192 
193 static int
194 dump_raw_samples(struct perf_tool *tool,
195 		 union perf_event *event,
196 		 struct perf_sample *sample,
197 		 struct machine *machine)
198 {
199 	struct perf_mem *mem = container_of(tool, struct perf_mem, tool);
200 	struct addr_location al;
201 	const char *fmt, *field_sep;
202 	char str[PAGE_SIZE_NAME_LEN];
203 	struct dso *dso = NULL;
204 
205 	if (machine__resolve(machine, &al, sample) < 0) {
206 		fprintf(stderr, "problem processing %d event, skipping it.\n",
207 				event->header.type);
208 		return -1;
209 	}
210 
211 	if (al.filtered || (mem->hide_unresolved && al.sym == NULL))
212 		goto out_put;
213 
214 	if (al.map != NULL) {
215 		dso = map__dso(al.map);
216 		if (dso)
217 			dso->hit = 1;
218 	}
219 
220 	field_sep = symbol_conf.field_sep;
221 	if (field_sep) {
222 		fmt = "%d%s%d%s0x%"PRIx64"%s0x%"PRIx64"%s";
223 	} else {
224 		fmt = "%5d%s%5d%s0x%016"PRIx64"%s0x016%"PRIx64"%s";
225 		symbol_conf.field_sep = " ";
226 	}
227 	printf(fmt,
228 		sample->pid,
229 		symbol_conf.field_sep,
230 		sample->tid,
231 		symbol_conf.field_sep,
232 		sample->ip,
233 		symbol_conf.field_sep,
234 		sample->addr,
235 		symbol_conf.field_sep);
236 
237 	if (mem->phys_addr) {
238 		printf("0x%016"PRIx64"%s",
239 			sample->phys_addr,
240 			symbol_conf.field_sep);
241 	}
242 
243 	if (mem->data_page_size) {
244 		printf("%s%s",
245 			get_page_size_name(sample->data_page_size, str),
246 			symbol_conf.field_sep);
247 	}
248 
249 	if (field_sep)
250 		fmt = "%"PRIu64"%s0x%"PRIx64"%s%s:%s\n";
251 	else
252 		fmt = "%5"PRIu64"%s0x%06"PRIx64"%s%s:%s\n";
253 
254 	printf(fmt,
255 		sample->weight,
256 		symbol_conf.field_sep,
257 		sample->data_src,
258 		symbol_conf.field_sep,
259 		dso ? dso->long_name : "???",
260 		al.sym ? al.sym->name : "???");
261 out_put:
262 	addr_location__put(&al);
263 	return 0;
264 }
265 
266 static int process_sample_event(struct perf_tool *tool,
267 				union perf_event *event,
268 				struct perf_sample *sample,
269 				struct evsel *evsel __maybe_unused,
270 				struct machine *machine)
271 {
272 	return dump_raw_samples(tool, event, sample, machine);
273 }
274 
275 static int report_raw_events(struct perf_mem *mem)
276 {
277 	struct itrace_synth_opts itrace_synth_opts = {
278 		.set = true,
279 		.mem = true,	/* Only enable memory event */
280 		.default_no_sample = true,
281 	};
282 
283 	struct perf_data data = {
284 		.path  = input_name,
285 		.mode  = PERF_DATA_MODE_READ,
286 		.force = mem->force,
287 	};
288 	int ret;
289 	struct perf_session *session = perf_session__new(&data, &mem->tool);
290 
291 	if (IS_ERR(session))
292 		return PTR_ERR(session);
293 
294 	session->itrace_synth_opts = &itrace_synth_opts;
295 
296 	if (mem->cpu_list) {
297 		ret = perf_session__cpu_bitmap(session, mem->cpu_list,
298 					       mem->cpu_bitmap);
299 		if (ret < 0)
300 			goto out_delete;
301 	}
302 
303 	ret = symbol__init(&session->header.env);
304 	if (ret < 0)
305 		goto out_delete;
306 
307 	printf("# PID, TID, IP, ADDR, ");
308 
309 	if (mem->phys_addr)
310 		printf("PHYS ADDR, ");
311 
312 	if (mem->data_page_size)
313 		printf("DATA PAGE SIZE, ");
314 
315 	printf("LOCAL WEIGHT, DSRC, SYMBOL\n");
316 
317 	ret = perf_session__process_events(session);
318 
319 out_delete:
320 	perf_session__delete(session);
321 	return ret;
322 }
323 static char *get_sort_order(struct perf_mem *mem)
324 {
325 	bool has_extra_options = (mem->phys_addr | mem->data_page_size) ? true : false;
326 	char sort[128];
327 
328 	/*
329 	 * there is no weight (cost) associated with stores, so don't print
330 	 * the column
331 	 */
332 	if (!(mem->operation & MEM_OPERATION_LOAD)) {
333 		strcpy(sort, "--sort=mem,sym,dso,symbol_daddr,"
334 			     "dso_daddr,tlb,locked");
335 	} else if (has_extra_options) {
336 		strcpy(sort, "--sort=local_weight,mem,sym,dso,symbol_daddr,"
337 			     "dso_daddr,snoop,tlb,locked,blocked");
338 	} else
339 		return NULL;
340 
341 	if (mem->phys_addr)
342 		strcat(sort, ",phys_daddr");
343 
344 	if (mem->data_page_size)
345 		strcat(sort, ",data_page_size");
346 
347 	return strdup(sort);
348 }
349 
350 static int report_events(int argc, const char **argv, struct perf_mem *mem)
351 {
352 	const char **rep_argv;
353 	int ret, i = 0, j, rep_argc;
354 	char *new_sort_order;
355 
356 	if (mem->dump_raw)
357 		return report_raw_events(mem);
358 
359 	rep_argc = argc + 3;
360 	rep_argv = calloc(rep_argc + 1, sizeof(char *));
361 	if (!rep_argv)
362 		return -1;
363 
364 	rep_argv[i++] = "report";
365 	rep_argv[i++] = "--mem-mode";
366 	rep_argv[i++] = "-n"; /* display number of samples */
367 
368 	new_sort_order = get_sort_order(mem);
369 	if (new_sort_order)
370 		rep_argv[i++] = new_sort_order;
371 
372 	for (j = 1; j < argc; j++, i++)
373 		rep_argv[i] = argv[j];
374 
375 	ret = cmd_report(i, rep_argv);
376 	free(rep_argv);
377 	return ret;
378 }
379 
380 struct mem_mode {
381 	const char *name;
382 	int mode;
383 };
384 
385 #define MEM_OPT(n, m) \
386 	{ .name = n, .mode = (m) }
387 
388 #define MEM_END { .name = NULL }
389 
390 static const struct mem_mode mem_modes[]={
391 	MEM_OPT("load", MEM_OPERATION_LOAD),
392 	MEM_OPT("store", MEM_OPERATION_STORE),
393 	MEM_END
394 };
395 
396 static int
397 parse_mem_ops(const struct option *opt, const char *str, int unset)
398 {
399 	int *mode = (int *)opt->value;
400 	const struct mem_mode *m;
401 	char *s, *os = NULL, *p;
402 	int ret = -1;
403 
404 	if (unset)
405 		return 0;
406 
407 	/* str may be NULL in case no arg is passed to -t */
408 	if (str) {
409 		/* because str is read-only */
410 		s = os = strdup(str);
411 		if (!s)
412 			return -1;
413 
414 		/* reset mode */
415 		*mode = 0;
416 
417 		for (;;) {
418 			p = strchr(s, ',');
419 			if (p)
420 				*p = '\0';
421 
422 			for (m = mem_modes; m->name; m++) {
423 				if (!strcasecmp(s, m->name))
424 					break;
425 			}
426 			if (!m->name) {
427 				fprintf(stderr, "unknown sampling op %s,"
428 					    " check man page\n", s);
429 				goto error;
430 			}
431 
432 			*mode |= m->mode;
433 
434 			if (!p)
435 				break;
436 
437 			s = p + 1;
438 		}
439 	}
440 	ret = 0;
441 
442 	if (*mode == 0)
443 		*mode = MEM_OPERATION_LOAD;
444 error:
445 	free(os);
446 	return ret;
447 }
448 
449 int cmd_mem(int argc, const char **argv)
450 {
451 	struct stat st;
452 	struct perf_mem mem = {
453 		.tool = {
454 			.sample		= process_sample_event,
455 			.mmap		= perf_event__process_mmap,
456 			.mmap2		= perf_event__process_mmap2,
457 			.comm		= perf_event__process_comm,
458 			.lost		= perf_event__process_lost,
459 			.fork		= perf_event__process_fork,
460 			.attr		= perf_event__process_attr,
461 			.build_id	= perf_event__process_build_id,
462 			.namespaces	= perf_event__process_namespaces,
463 			.auxtrace_info  = perf_event__process_auxtrace_info,
464 			.auxtrace       = perf_event__process_auxtrace,
465 			.auxtrace_error = perf_event__process_auxtrace_error,
466 			.ordered_events	= true,
467 		},
468 		.input_name		 = "perf.data",
469 		/*
470 		 * default to both load an store sampling
471 		 */
472 		.operation		 = MEM_OPERATION_LOAD | MEM_OPERATION_STORE,
473 	};
474 	const struct option mem_options[] = {
475 	OPT_CALLBACK('t', "type", &mem.operation,
476 		   "type", "memory operations(load,store) Default load,store",
477 		    parse_mem_ops),
478 	OPT_BOOLEAN('D', "dump-raw-samples", &mem.dump_raw,
479 		    "dump raw samples in ASCII"),
480 	OPT_BOOLEAN('U', "hide-unresolved", &mem.hide_unresolved,
481 		    "Only display entries resolved to a symbol"),
482 	OPT_STRING('i', "input", &input_name, "file",
483 		   "input file name"),
484 	OPT_STRING('C', "cpu", &mem.cpu_list, "cpu",
485 		   "list of cpus to profile"),
486 	OPT_STRING_NOEMPTY('x', "field-separator", &symbol_conf.field_sep,
487 		   "separator",
488 		   "separator for columns, no spaces will be added"
489 		   " between columns '.' is reserved."),
490 	OPT_BOOLEAN('f', "force", &mem.force, "don't complain, do it"),
491 	OPT_BOOLEAN('p', "phys-data", &mem.phys_addr, "Record/Report sample physical addresses"),
492 	OPT_BOOLEAN(0, "data-page-size", &mem.data_page_size, "Record/Report sample data address page size"),
493 	OPT_END()
494 	};
495 	const char *const mem_subcommands[] = { "record", "report", NULL };
496 	const char *mem_usage[] = {
497 		NULL,
498 		NULL
499 	};
500 
501 	argc = parse_options_subcommand(argc, argv, mem_options, mem_subcommands,
502 					mem_usage, PARSE_OPT_KEEP_UNKNOWN);
503 
504 	if (!argc || !(strncmp(argv[0], "rec", 3) || mem.operation))
505 		usage_with_options(mem_usage, mem_options);
506 
507 	if (!mem.input_name || !strlen(mem.input_name)) {
508 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
509 			mem.input_name = "-";
510 		else
511 			mem.input_name = "perf.data";
512 	}
513 
514 	if (strlen(argv[0]) > 2 && strstarts("record", argv[0]))
515 		return __cmd_record(argc, argv, &mem);
516 	else if (strlen(argv[0]) > 2 && strstarts("report", argv[0]))
517 		return report_events(argc, argv, &mem);
518 	else
519 		usage_with_options(mem_usage, mem_options);
520 
521 	return 0;
522 }
523