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