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