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