xref: /freebsd/usr.sbin/pmcstat/pmcstat_log.c (revision ee12645ec737eb940554769af2c275524ea20d37)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2005-2007, Joseph Koshy
5  * Copyright (c) 2007 The FreeBSD Foundation
6  * All rights reserved.
7  *
8  * Portions of this software were developed by A. Joseph Koshy under
9  * sponsorship from the FreeBSD Foundation and Google, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Transform a hwpmc(4) log into human readable form, and into
35  * gprof(1) compatible profiles.
36  */
37 
38 #include <sys/param.h>
39 #include <sys/endian.h>
40 #include <sys/cpuset.h>
41 #include <sys/gmon.h>
42 #include <sys/imgact_aout.h>
43 #include <sys/imgact_elf.h>
44 #include <sys/mman.h>
45 #include <sys/pmc.h>
46 #include <sys/queue.h>
47 #include <sys/socket.h>
48 #include <sys/stat.h>
49 #include <sys/wait.h>
50 
51 #include <netinet/in.h>
52 
53 #include <assert.h>
54 #include <curses.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <gelf.h>
59 #include <inttypes.h>
60 #include <libgen.h>
61 #include <limits.h>
62 #include <netdb.h>
63 #include <pmc.h>
64 #include <pmclog.h>
65 #include <sysexits.h>
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <unistd.h>
71 
72 #include "pmcstat.h"
73 #include "pmcstat_log.h"
74 #include "pmcstat_top.h"
75 
76 /*
77  * PUBLIC INTERFACES
78  *
79  * pmcstat_initialize_logging()	initialize this module, called first
80  * pmcstat_shutdown_logging()		orderly shutdown, called last
81  * pmcstat_open_log()			open an eventlog for processing
82  * pmcstat_process_log()		print/convert an event log
83  * pmcstat_display_log()		top mode display for the log
84  * pmcstat_close_log()			finish processing an event log
85  *
86  * IMPLEMENTATION NOTES
87  *
88  * We correlate each 'callchain' or 'sample' entry seen in the event
89  * log back to an executable object in the system. Executable objects
90  * include:
91  * 	- program executables,
92  *	- shared libraries loaded by the runtime loader,
93  *	- dlopen()'ed objects loaded by the program,
94  *	- the runtime loader itself,
95  *	- the kernel and kernel modules.
96  *
97  * Each process that we know about is treated as a set of regions that
98  * map to executable objects.  Processes are described by
99  * 'pmcstat_process' structures.  Executable objects are tracked by
100  * 'pmcstat_image' structures.  The kernel and kernel modules are
101  * common to all processes (they reside at the same virtual addresses
102  * for all processes).  Individual processes can have their text
103  * segments and shared libraries loaded at process-specific locations.
104  *
105  * A given executable object can be in use by multiple processes
106  * (e.g., libc.so) and loaded at a different address in each.
107  * pmcstat_pcmap structures track per-image mappings.
108  *
109  * The sample log could have samples from multiple PMCs; we
110  * generate one 'gmon.out' profile per PMC.
111  *
112  * IMPLEMENTATION OF GMON OUTPUT
113  *
114  * Each executable object gets one 'gmon.out' profile, per PMC in
115  * use.  Creation of 'gmon.out' profiles is done lazily.  The
116  * 'gmon.out' profiles generated for a given sampling PMC are
117  * aggregates of all the samples for that particular executable
118  * object.
119  *
120  * IMPLEMENTATION OF SYSTEM-WIDE CALLGRAPH OUTPUT
121  *
122  * Each active pmcid has its own callgraph structure, described by a
123  * 'struct pmcstat_callgraph'.  Given a process id and a list of pc
124  * values, we map each pc value to a tuple (image, symbol), where
125  * 'image' denotes an executable object and 'symbol' is the closest
126  * symbol that precedes the pc value.  Each pc value in the list is
127  * also given a 'rank' that reflects its depth in the call stack.
128  */
129 
130 struct pmcstat_pmcs pmcstat_pmcs = LIST_HEAD_INITIALIZER(pmcstat_pmcs);
131 
132 /*
133  * All image descriptors are kept in a hash table.
134  */
135 struct pmcstat_image_hash_list pmcstat_image_hash[PMCSTAT_NHASH];
136 
137 /*
138  * All process descriptors are kept in a hash table.
139  */
140 struct pmcstat_process_hash_list pmcstat_process_hash[PMCSTAT_NHASH];
141 
142 struct pmcstat_stats pmcstat_stats; /* statistics */
143 static int ps_samples_period; /* samples count between top refresh. */
144 
145 struct pmcstat_process *pmcstat_kernproc; /* kernel 'process' */
146 
147 #include "pmcpl_gprof.h"
148 #include "pmcpl_callgraph.h"
149 #include "pmcpl_annotate.h"
150 #include "pmcpl_annotate_cg.h"
151 #include "pmcpl_calltree.h"
152 
153 static struct pmc_plugins plugins[] = {
154 	{
155 		.pl_name		= "none",
156 	},
157 	{
158 		.pl_name		= "callgraph",
159 		.pl_init		= pmcpl_cg_init,
160 		.pl_shutdown		= pmcpl_cg_shutdown,
161 		.pl_process		= pmcpl_cg_process,
162 		.pl_topkeypress		= pmcpl_cg_topkeypress,
163 		.pl_topdisplay		= pmcpl_cg_topdisplay
164 	},
165 	{
166 		.pl_name		= "gprof",
167 		.pl_shutdown		= pmcpl_gmon_shutdown,
168 		.pl_process		= pmcpl_gmon_process,
169 		.pl_initimage		= pmcpl_gmon_initimage,
170 		.pl_shutdownimage	= pmcpl_gmon_shutdownimage,
171 		.pl_newpmc		= pmcpl_gmon_newpmc
172 	},
173 	{
174 		.pl_name		= "annotate",
175 		.pl_process		= pmcpl_annotate_process
176 	},
177 	{
178 		.pl_name		= "calltree",
179 		.pl_configure		= pmcpl_ct_configure,
180 		.pl_init		= pmcpl_ct_init,
181 		.pl_shutdown		= pmcpl_ct_shutdown,
182 		.pl_process		= pmcpl_ct_process,
183 		.pl_topkeypress		= pmcpl_ct_topkeypress,
184 		.pl_topdisplay		= pmcpl_ct_topdisplay
185 	},
186 	{
187 		.pl_name		= "annotate_cg",
188 		.pl_process		= pmcpl_annotate_cg_process
189 	},
190 
191 	{
192 		.pl_name		= NULL
193 	}
194 };
195 
196 static int pmcstat_mergepmc;
197 static uint64_t _pmcstat_current_tsc; /* TSC for PMCSTAT_PRINT_ENTRY */
198 
199 int pmcstat_pmcinfilter = 0; /* PMC filter for top mode. */
200 float pmcstat_threshold = 0.5; /* Cost filter for top mode. */
201 
202 /*
203  * Prototypes
204  */
205 
206 static void pmcstat_stats_reset(int _reset_global);
207 
208 /*
209  * PMC count.
210  */
211 int pmcstat_npmcs;
212 
213 /*
214  * PMC Top mode pause state.
215  */
216 static int pmcstat_pause;
217 
218 static void
pmcstat_stats_reset(int reset_global)219 pmcstat_stats_reset(int reset_global)
220 {
221 	struct pmcstat_pmcrecord *pr;
222 
223 	/* Flush PMCs stats. */
224 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next) {
225 		pr->pr_samples = 0;
226 		pr->pr_dubious_frames = 0;
227 	}
228 	ps_samples_period = 0;
229 
230 	/* Flush global stats. */
231 	if (reset_global)
232 		bzero(&pmcstat_stats, sizeof(struct pmcstat_stats));
233 }
234 
235 /*
236  * Resolve file name and line number for the given address.
237  */
238 int
pmcstat_image_addr2line(struct pmcstat_image * image,uintfptr_t addr,char * sourcefile,size_t sourcefile_len,unsigned * sourceline,char * funcname,size_t funcname_len)239 pmcstat_image_addr2line(struct pmcstat_image *image, uintfptr_t addr,
240     char *sourcefile, size_t sourcefile_len, unsigned *sourceline,
241     char *funcname, size_t funcname_len)
242 {
243 	static int addr2line_warn = 0;
244 
245 	char *sep, cmdline[PATH_MAX], imagepath[PATH_MAX];
246 	unsigned l;
247 	int fd;
248 
249 	if (image->pi_addr2line == NULL) {
250 		/* Try default debug file location. */
251 		snprintf(imagepath, sizeof(imagepath),
252 		    "/usr/lib/debug/%s%s.debug",
253 		    args.pa_fsroot,
254 		    pmcstat_string_unintern(image->pi_fullpath));
255 		fd = open(imagepath, O_RDONLY);
256 		if (fd < 0) {
257 			/* Old kernel symbol path. */
258 			snprintf(imagepath, sizeof(imagepath), "%s%s.symbols",
259 			    args.pa_fsroot,
260 			    pmcstat_string_unintern(image->pi_fullpath));
261 			fd = open(imagepath, O_RDONLY);
262 			if (fd < 0) {
263 				snprintf(imagepath, sizeof(imagepath), "%s%s",
264 				    args.pa_fsroot,
265 				    pmcstat_string_unintern(
266 				        image->pi_fullpath));
267 			}
268 		}
269 		if (fd >= 0)
270 			close(fd);
271 		/*
272 		 * New addr2line support recursive inline function with -i
273 		 * but the format does not add a marker when no more entries
274 		 * are available.
275 		 */
276 		snprintf(cmdline, sizeof(cmdline), "addr2line -Cfe \"%s\"",
277 		    imagepath);
278 		image->pi_addr2line = popen(cmdline, "r+");
279 		if (image->pi_addr2line == NULL) {
280 			if (!addr2line_warn) {
281 				addr2line_warn = 1;
282 				warnx(
283 "WARNING: addr2line is needed for source code information."
284 				    );
285 			}
286 			return (0);
287 		}
288 	}
289 
290 	if (feof(image->pi_addr2line) || ferror(image->pi_addr2line)) {
291 		warnx("WARNING: addr2line pipe error");
292 		pclose(image->pi_addr2line);
293 		image->pi_addr2line = NULL;
294 		return (0);
295 	}
296 
297 	fprintf(image->pi_addr2line, "%p\n", (void *)addr);
298 
299 	if (fgets(funcname, funcname_len, image->pi_addr2line) == NULL) {
300 		warnx("WARNING: addr2line function name read error");
301 		return (0);
302 	}
303 	sep = strchr(funcname, '\n');
304 	if (sep != NULL)
305 		*sep = '\0';
306 
307 	if (fgets(sourcefile, sourcefile_len, image->pi_addr2line) == NULL) {
308 		warnx("WARNING: addr2line source file read error");
309 		return (0);
310 	}
311 	sep = strchr(sourcefile, ':');
312 	if (sep == NULL) {
313 		warnx("WARNING: addr2line source line separator missing");
314 		return (0);
315 	}
316 	*sep = '\0';
317 	l = atoi(sep+1);
318 	if (l == 0)
319 		return (0);
320 	*sourceline = l;
321 	return (1);
322 }
323 
324 /*
325  * Given a pmcid in use, find its human-readable name.
326  */
327 
328 const char *
pmcstat_pmcid_to_name(pmc_id_t pmcid)329 pmcstat_pmcid_to_name(pmc_id_t pmcid)
330 {
331 	struct pmcstat_pmcrecord *pr;
332 
333 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
334 	    if (pr->pr_pmcid == pmcid)
335 		    return (pmcstat_string_unintern(pr->pr_pmcname));
336 
337 	return NULL;
338 }
339 
340 /*
341  * Convert PMC index to name.
342  */
343 
344 const char *
pmcstat_pmcindex_to_name(int pmcin)345 pmcstat_pmcindex_to_name(int pmcin)
346 {
347 	struct pmcstat_pmcrecord *pr;
348 
349 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
350 		if (pr->pr_pmcin == pmcin)
351 			return pmcstat_string_unintern(pr->pr_pmcname);
352 
353 	return NULL;
354 }
355 
356 /*
357  * Return PMC record with given index.
358  */
359 
360 struct pmcstat_pmcrecord *
pmcstat_pmcindex_to_pmcr(int pmcin)361 pmcstat_pmcindex_to_pmcr(int pmcin)
362 {
363 	struct pmcstat_pmcrecord *pr;
364 
365 	LIST_FOREACH(pr, &pmcstat_pmcs, pr_next)
366 		if (pr->pr_pmcin == pmcin)
367 			return pr;
368 
369 	return NULL;
370 }
371 
372 #if defined(__amd64__) || defined(__i386__)
373 static void
pmcstat_print_ibs_fetch(struct pmclog_ev_callchain * cc,int offset)374 pmcstat_print_ibs_fetch(struct pmclog_ev_callchain *cc, int offset)
375 {
376 	uint64_t *ibsbuf = (uint64_t *)&cc->pl_pc[offset];
377 	uint64_t ctl;
378 
379 	ctl = ibsbuf[PMC_MPIDX_FETCH_CTL];
380 	PMCSTAT_PRINT_ENTRY("ibs-fetch", "%s%s%s%s",
381 	    (ctl & IBS_FETCH_CTL_ICMISS) ? "icmiss " : "",
382 	    (ctl & IBS_FETCH_CTL_L1TLBMISS) ? "l1tlbmiss " : "",
383 	    (ctl & IBS_FETCH_CTL_OPCACHEMISS) ? "opcachemiss " : "",
384 	    (ctl & IBS_FETCH_CTL_L3MISS) ? "l3miss" : "");
385 	PMCSTAT_PRINT_ENTRY("ibs-fetch", "Latency %" PRIu64,
386 	    IBS_FETCH_CTL_TO_LAT(ctl));
387 	PMCSTAT_PRINT_ENTRY("IBS", "Address %" PRIx64,
388 	    ibsbuf[PMC_MPIDX_FETCH_LINADDR]);
389 	if ((ctl & IBS_FETCH_CTL_PHYSADDRVALID) != 0) {
390 		PMCSTAT_PRINT_ENTRY("IBS", "Physical Address %" PRIx64,
391 		    ibsbuf[PMC_MPIDX_FETCH_PHYSADDR]);
392 	}
393 }
394 
395 static void
pmcstat_print_ibs_op(struct pmclog_ev_callchain * cc,int offset)396 pmcstat_print_ibs_op(struct pmclog_ev_callchain *cc, int offset)
397 {
398 	uint64_t *ibsbuf = (uint64_t *)&cc->pl_pc[offset];
399 	uint64_t data, data3;
400 
401 	data = ibsbuf[PMC_MPIDX_OP_DATA];
402 	data3 = ibsbuf[PMC_MPIDX_OP_DATA3];
403 
404 	if ((data & IBS_OP_DATA_RIPINVALID) == 0) {
405 		PMCSTAT_PRINT_ENTRY("ibs-op", "RIP %" PRIx64,
406 		    ibsbuf[PMC_MPIDX_OP_RIP]);
407 	}
408 	PMCSTAT_PRINT_ENTRY("ibs-op", "%s%s%s%s",
409 	    (data & IBS_OP_DATA_BRANCHRETIRED) ? "branchretired " : "",
410 	    (data & IBS_OP_DATA_BRANCHMISPREDICTED) ? "branchmispredicted " : "",
411 	    (data & IBS_OP_DATA_BRANCHTAKEN) ? "branchtaken " : "",
412 	    (data & IBS_OP_DATA_RETURN) ? "return" : "");
413 	PMCSTAT_PRINT_ENTRY("ibs-op", "%s%s%s%s%s",
414 	    (data3 & IBS_OP_DATA3_LOAD) ? "load " : "",
415 	    (data3 & IBS_OP_DATA3_STORE) ? "store " : "",
416 	    (data3 & IBS_OP_DATA3_LOCKEDOP) ? "lock " : "",
417 	    (data3 & IBS_OP_DATA3_DCL1TLBMISS) ? "l1tlbmiss " : "",
418 	    (data3 & IBS_OP_DATA3_DCMISS) ? "dcmiss " : "");
419 	PMCSTAT_PRINT_ENTRY("ibs-op", "Latency %" PRIu64,
420 	    IBS_OP_DATA3_TO_DCLAT(data3));
421 	if ((data3 & IBS_OP_DATA3_DCLINADDRVALID) != 0) {
422 		PMCSTAT_PRINT_ENTRY("ibs-op", "Address %" PRIx64,
423 		    ibsbuf[PMC_MPIDX_OP_DC_LINADDR]);
424 	}
425 	if ((data3 & IBS_OP_DATA3_DCPHYADDRVALID) != 0) {
426 		PMCSTAT_PRINT_ENTRY("ibs-op", "Physical Address %" PRIx64,
427 		    ibsbuf[PMC_MPIDX_OP_DC_PHYSADDR]);
428 	}
429 }
430 #endif
431 
432 static int
pmcstat_print_multipart(struct pmclog_ev_callchain * cc)433 pmcstat_print_multipart(struct pmclog_ev_callchain *cc)
434 {
435 	int i;
436 	uint8_t *hdr = (uint8_t *)&cc->pl_pc[0];
437 	int offset = PMC_MULTIPART_HEADER_LENGTH / sizeof(uintptr_t);
438 
439 	for (i = 0; i < PMC_MULTIPART_HEADER_ENTRIES; i++) {
440 		uint8_t type = hdr[2 * i];
441 		uint8_t len = hdr[2 * i + 1];
442 
443 		if (type == PMC_CC_MULTIPART_NONE) {
444 			break;
445 		} else if (type == PMC_CC_MULTIPART_CALLCHAIN) {
446 			return (offset);
447 #if defined(__amd64__) || defined(__i386__)
448 		} else if (type == PMC_CC_MULTIPART_IBS_FETCH) {
449 			pmcstat_print_ibs_fetch(cc, offset);
450 		} else if (type == PMC_CC_MULTIPART_IBS_OP) {
451 			pmcstat_print_ibs_op(cc, offset);
452 #endif
453 		} else {
454 			PMCSTAT_PRINT_ENTRY("unsupported multipart type!");
455 		}
456 
457 		offset += len;
458 	}
459 
460 	return (offset);
461 }
462 
463 /*
464  * Print log entries as text.
465  */
466 
467 static int
pmcstat_print_log(void)468 pmcstat_print_log(void)
469 {
470 	struct pmclog_ev ev;
471 	uint32_t npc;
472 
473 	while (pmclog_read(args.pa_logparser, &ev) == 0) {
474 		assert(ev.pl_state == PMCLOG_OK);
475 		_pmcstat_current_tsc = ev.pl_tsc;
476 		switch (ev.pl_type) {
477 		case PMCLOG_TYPE_CALLCHAIN:
478 			PMCSTAT_PRINT_ENTRY("callchain",
479 			    "%d 0x%x %d %d %c", ev.pl_u.pl_cc.pl_pid,
480 			    ev.pl_u.pl_cc.pl_pmcid,
481 			    PMC_CALLCHAIN_CPUFLAGS_TO_CPU(ev.pl_u.pl_cc. \
482 				pl_cpuflags), ev.pl_u.pl_cc.pl_npc,
483 			    PMC_CALLCHAIN_CPUFLAGS_TO_USERMODE(ev.pl_u.pl_cc.\
484 			        pl_cpuflags) ? 'u' : 's');
485 			if ((ev.pl_u.pl_cc.pl_cpuflags & PMC_CC_F_MULTIPART)
486 			    != 0)
487 				npc = pmcstat_print_multipart(&ev.pl_u.pl_cc);
488 			else
489 				npc = 0;
490 			for (; npc < ev.pl_u.pl_cc.pl_npc; npc++)
491 				PMCSTAT_PRINT_ENTRY("...", "%p",
492 				    (void *) ev.pl_u.pl_cc.pl_pc[npc]);
493 			break;
494 		case PMCLOG_TYPE_CLOSELOG:
495 			PMCSTAT_PRINT_ENTRY("closelog",);
496 			break;
497 		case PMCLOG_TYPE_DROPNOTIFY:
498 			PMCSTAT_PRINT_ENTRY("drop",);
499 			break;
500 		case PMCLOG_TYPE_INITIALIZE:
501 			PMCSTAT_PRINT_ENTRY("initlog",
502 			    "0x%x \"%s\" tsc_freq=%" PRIu64,
503 			    ev.pl_u.pl_i.pl_version,
504 			    pmc_name_of_cputype(ev.pl_u.pl_i.pl_arch),
505 			    ev.pl_u.pl_i.pl_tsc_freq);
506 			if ((ev.pl_u.pl_i.pl_version & 0xFF000000) !=
507 			    PMC_VERSION_MAJOR << 24)
508 				warnx(
509 "WARNING: Log version 0x%x != expected version 0x%x.",
510 				    ev.pl_u.pl_i.pl_version, PMC_VERSION);
511 			break;
512 		case PMCLOG_TYPE_MAP_IN:
513 			PMCSTAT_PRINT_ENTRY("map-in","%d %p \"%s\"",
514 			    ev.pl_u.pl_mi.pl_pid,
515 			    (void *) ev.pl_u.pl_mi.pl_start,
516 			    ev.pl_u.pl_mi.pl_pathname);
517 			break;
518 		case PMCLOG_TYPE_MAP_OUT:
519 			PMCSTAT_PRINT_ENTRY("map-out","%d %p %p",
520 			    ev.pl_u.pl_mo.pl_pid,
521 			    (void *) ev.pl_u.pl_mo.pl_start,
522 			    (void *) ev.pl_u.pl_mo.pl_end);
523 			break;
524 		case PMCLOG_TYPE_PMCALLOCATE:
525 			PMCSTAT_PRINT_ENTRY("allocate","0x%x \"%s\" 0x%x",
526 			    ev.pl_u.pl_a.pl_pmcid,
527 			    ev.pl_u.pl_a.pl_evname,
528 			    ev.pl_u.pl_a.pl_flags);
529 			break;
530 		case PMCLOG_TYPE_PMCALLOCATEDYN:
531 			PMCSTAT_PRINT_ENTRY("allocatedyn","0x%x \"%s\" 0x%x",
532 			    ev.pl_u.pl_ad.pl_pmcid,
533 			    ev.pl_u.pl_ad.pl_evname,
534 			    ev.pl_u.pl_ad.pl_flags);
535 			break;
536 		case PMCLOG_TYPE_PMCATTACH:
537 			PMCSTAT_PRINT_ENTRY("attach","0x%x %d \"%s\"",
538 			    ev.pl_u.pl_t.pl_pmcid,
539 			    ev.pl_u.pl_t.pl_pid,
540 			    ev.pl_u.pl_t.pl_pathname);
541 			break;
542 		case PMCLOG_TYPE_PMCDETACH:
543 			PMCSTAT_PRINT_ENTRY("detach","0x%x %d",
544 			    ev.pl_u.pl_d.pl_pmcid,
545 			    ev.pl_u.pl_d.pl_pid);
546 			break;
547 		case PMCLOG_TYPE_PROCCSW:
548 			PMCSTAT_PRINT_ENTRY("cswval","0x%x %d %jd",
549 			    ev.pl_u.pl_c.pl_pmcid,
550 			    ev.pl_u.pl_c.pl_pid,
551 			    ev.pl_u.pl_c.pl_value);
552 			break;
553 		case PMCLOG_TYPE_PROC_CREATE:
554 			PMCSTAT_PRINT_ENTRY("create","%d %x \"%s\"",
555 			    ev.pl_u.pl_pc.pl_pid,
556 			    ev.pl_u.pl_pc.pl_flags,
557 			    ev.pl_u.pl_pc.pl_pcomm);
558 			break;
559 		case PMCLOG_TYPE_PROCEXEC:
560 			PMCSTAT_PRINT_ENTRY("exec","0x%x %d %p %p \"%s\"",
561 			    ev.pl_u.pl_x.pl_pmcid,
562 			    ev.pl_u.pl_x.pl_pid,
563 			    (void *)ev.pl_u.pl_x.pl_baseaddr,
564 			    (void *)ev.pl_u.pl_x.pl_dynaddr,
565 			    ev.pl_u.pl_x.pl_pathname);
566 			break;
567 		case PMCLOG_TYPE_PROCEXIT:
568 			PMCSTAT_PRINT_ENTRY("exitval","0x%x %d %jd",
569 			    ev.pl_u.pl_e.pl_pmcid,
570 			    ev.pl_u.pl_e.pl_pid,
571 			    ev.pl_u.pl_e.pl_value);
572 			break;
573 		case PMCLOG_TYPE_PROCFORK:
574 			PMCSTAT_PRINT_ENTRY("fork","%d %d",
575 			    ev.pl_u.pl_f.pl_oldpid,
576 			    ev.pl_u.pl_f.pl_newpid);
577 			break;
578 		case PMCLOG_TYPE_USERDATA:
579 			PMCSTAT_PRINT_ENTRY("userdata","0x%x",
580 			    ev.pl_u.pl_u.pl_userdata);
581 			break;
582 		case PMCLOG_TYPE_SYSEXIT:
583 			PMCSTAT_PRINT_ENTRY("exit","%d",
584 			    ev.pl_u.pl_se.pl_pid);
585 			break;
586 		case PMCLOG_TYPE_THR_CREATE:
587 			PMCSTAT_PRINT_ENTRY("thr-create","%d %d %x \"%s\"",
588 			    ev.pl_u.pl_tc.pl_tid,
589 			    ev.pl_u.pl_tc.pl_pid,
590 			    ev.pl_u.pl_tc.pl_flags,
591 			    ev.pl_u.pl_tc.pl_tdname);
592 			break;
593 		case PMCLOG_TYPE_THR_EXIT:
594 			PMCSTAT_PRINT_ENTRY("thr-exit","%d",
595 			    ev.pl_u.pl_tc.pl_tid);
596 			break;
597 		default:
598 			fprintf(args.pa_printfile, "unknown event (type %d).\n",
599 			    ev.pl_type);
600 		}
601 	}
602 
603 	if (ev.pl_state == PMCLOG_EOF)
604 		return (PMCSTAT_FINISHED);
605 	else if (ev.pl_state == PMCLOG_REQUIRE_DATA)
606 		return (PMCSTAT_RUNNING);
607 
608 	errx(EX_DATAERR,
609 	    "ERROR: event parsing failed (record %jd, offset 0x%jx).",
610 	    (uintmax_t) ev.pl_count + 1, ev.pl_offset);
611 	/*NOTREACHED*/
612 }
613 
614 /*
615  * Public Interfaces.
616  */
617 
618 /*
619  * Process a log file in offline analysis mode.
620  */
621 
622 int
pmcstat_process_log(void)623 pmcstat_process_log(void)
624 {
625 
626 	/*
627 	 * If analysis has not been asked for, just print the log to
628 	 * the current output file.
629 	 */
630 	if (args.pa_flags & FLAG_DO_PRINT)
631 		return (pmcstat_print_log());
632 	else
633 		return (pmcstat_analyze_log(&args, plugins, &pmcstat_stats, pmcstat_kernproc,
634 		    pmcstat_mergepmc, &pmcstat_npmcs, &ps_samples_period));
635 }
636 
637 /*
638  * Refresh top display.
639  */
640 
641 static void
pmcstat_refresh_top(void)642 pmcstat_refresh_top(void)
643 {
644 	int v_attrs;
645 	float v;
646 	char pmcname[40];
647 	struct pmcstat_pmcrecord *pmcpr;
648 
649 	/* If in pause mode do not refresh display. */
650 	if (pmcstat_pause)
651 		return;
652 
653 	/* Wait until PMC pop in the log. */
654 	pmcpr = pmcstat_pmcindex_to_pmcr(pmcstat_pmcinfilter);
655 	if (pmcpr == NULL)
656 		return;
657 
658 	/* Format PMC name. */
659 	if (pmcstat_mergepmc)
660 		snprintf(pmcname, sizeof(pmcname), "[%s]",
661 		    pmcstat_string_unintern(pmcpr->pr_pmcname));
662 	else
663 		snprintf(pmcname, sizeof(pmcname), "%s.%d",
664 		    pmcstat_string_unintern(pmcpr->pr_pmcname),
665 		    pmcstat_pmcinfilter);
666 
667 	/* Format samples count. */
668 	if (ps_samples_period > 0)
669 		v = (pmcpr->pr_samples * 100.0) / ps_samples_period;
670 	else
671 		v = 0.;
672 	v_attrs = PMCSTAT_ATTRPERCENT(v);
673 
674 	PMCSTAT_PRINTBEGIN();
675 	PMCSTAT_PRINTW("PMC: %s Samples: %u ",
676 	    pmcname,
677 	    pmcpr->pr_samples);
678 	PMCSTAT_ATTRON(v_attrs);
679 	PMCSTAT_PRINTW("(%.1f%%) ", v);
680 	PMCSTAT_ATTROFF(v_attrs);
681 	PMCSTAT_PRINTW(", %u unresolved\n\n",
682 	    pmcpr->pr_dubious_frames);
683 	if (plugins[args.pa_plugin].pl_topdisplay != NULL)
684 		plugins[args.pa_plugin].pl_topdisplay();
685 	PMCSTAT_PRINTEND();
686 }
687 
688 /*
689  * Find the next pmc index to display.
690  */
691 
692 static void
pmcstat_changefilter(void)693 pmcstat_changefilter(void)
694 {
695 	int pmcin;
696 	struct pmcstat_pmcrecord *pmcr;
697 
698 	/*
699 	 * Find the next merge target.
700 	 */
701 	if (pmcstat_mergepmc) {
702 		pmcin = pmcstat_pmcinfilter;
703 
704 		do {
705 			pmcr = pmcstat_pmcindex_to_pmcr(pmcstat_pmcinfilter);
706 			if (pmcr == NULL || pmcr == pmcr->pr_merge)
707 				break;
708 
709 			pmcstat_pmcinfilter++;
710 			if (pmcstat_pmcinfilter >= pmcstat_npmcs)
711 				pmcstat_pmcinfilter = 0;
712 
713 		} while (pmcstat_pmcinfilter != pmcin);
714 	}
715 }
716 
717 /*
718  * Top mode keypress.
719  */
720 
721 int
pmcstat_keypress_log(void)722 pmcstat_keypress_log(void)
723 {
724 	int c, ret = 0;
725 	WINDOW *w;
726 
727 	w = newwin(1, 0, 1, 0);
728 	c = wgetch(w);
729 	wprintw(w, "Key: %c => ", c);
730 	switch (c) {
731 	case 'A':
732 		if (args.pa_flags & FLAG_SKIP_TOP_FN_RES)
733 			args.pa_flags &= ~FLAG_SKIP_TOP_FN_RES;
734 		else
735 			args.pa_flags |= FLAG_SKIP_TOP_FN_RES;
736 		break;
737 	case 'c':
738 		wprintw(w, "enter mode 'd' or 'a' => ");
739 		c = wgetch(w);
740 		if (c == 'd') {
741 			args.pa_topmode = PMCSTAT_TOP_DELTA;
742 			wprintw(w, "switching to delta mode");
743 		} else {
744 			args.pa_topmode = PMCSTAT_TOP_ACCUM;
745 			wprintw(w, "switching to accumulation mode");
746 		}
747 		break;
748 	case 'I':
749 		if (args.pa_flags & FLAG_SHOW_OFFSET)
750 			args.pa_flags &= ~FLAG_SHOW_OFFSET;
751 		else
752 			args.pa_flags |= FLAG_SHOW_OFFSET;
753 		break;
754 	case 'm':
755 		pmcstat_mergepmc = !pmcstat_mergepmc;
756 		/*
757 		 * Changing merge state require data reset.
758 		 */
759 		if (plugins[args.pa_plugin].pl_shutdown != NULL)
760 			plugins[args.pa_plugin].pl_shutdown(NULL);
761 		pmcstat_stats_reset(0);
762 		if (plugins[args.pa_plugin].pl_init != NULL)
763 			plugins[args.pa_plugin].pl_init();
764 
765 		/* Update filter to be on a merge target. */
766 		pmcstat_changefilter();
767 		wprintw(w, "merge PMC %s", pmcstat_mergepmc ? "on" : "off");
768 		break;
769 	case 'n':
770 		/* Close current plugin. */
771 		if (plugins[args.pa_plugin].pl_shutdown != NULL)
772 			plugins[args.pa_plugin].pl_shutdown(NULL);
773 
774 		/* Find next top display available. */
775 		do {
776 			args.pa_plugin++;
777 			if (plugins[args.pa_plugin].pl_name == NULL)
778 				args.pa_plugin = 0;
779 		} while (plugins[args.pa_plugin].pl_topdisplay == NULL);
780 
781 		/* Open new plugin. */
782 		pmcstat_stats_reset(0);
783 		if (plugins[args.pa_plugin].pl_init != NULL)
784 			plugins[args.pa_plugin].pl_init();
785 		wprintw(w, "switching to plugin %s",
786 		    plugins[args.pa_plugin].pl_name);
787 		break;
788 	case 'p':
789 		pmcstat_pmcinfilter++;
790 		if (pmcstat_pmcinfilter >= pmcstat_npmcs)
791 			pmcstat_pmcinfilter = 0;
792 		pmcstat_changefilter();
793 		wprintw(w, "switching to PMC %s.%d",
794 		    pmcstat_pmcindex_to_name(pmcstat_pmcinfilter),
795 		    pmcstat_pmcinfilter);
796 		break;
797 	case ' ':
798 		pmcstat_pause = !pmcstat_pause;
799 		if (pmcstat_pause)
800 			wprintw(w, "pause => press space again to continue");
801 		break;
802 	case 'q':
803 		wprintw(w, "exiting...");
804 		ret = 1;
805 		break;
806 	default:
807 		if (plugins[args.pa_plugin].pl_topkeypress != NULL)
808 			if (plugins[args.pa_plugin].pl_topkeypress(c, (void *)w))
809 				ret = 1;
810 	}
811 
812 	wrefresh(w);
813 	delwin(w);
814 	return ret;
815 }
816 
817 
818 /*
819  * Top mode display.
820  */
821 
822 void
pmcstat_display_log(void)823 pmcstat_display_log(void)
824 {
825 
826 	pmcstat_refresh_top();
827 
828 	/* Reset everything if delta mode. */
829 	if (args.pa_topmode == PMCSTAT_TOP_DELTA) {
830 		if (plugins[args.pa_plugin].pl_shutdown != NULL)
831 			plugins[args.pa_plugin].pl_shutdown(NULL);
832 		pmcstat_stats_reset(0);
833 		if (plugins[args.pa_plugin].pl_init != NULL)
834 			plugins[args.pa_plugin].pl_init();
835 	}
836 }
837 
838 /*
839  * Configure a plugins.
840  */
841 
842 void
pmcstat_pluginconfigure_log(char * opt)843 pmcstat_pluginconfigure_log(char *opt)
844 {
845 
846 	if (strncmp(opt, "threshold=", 10) == 0) {
847 		pmcstat_threshold = atof(opt+10);
848 	} else {
849 		if (plugins[args.pa_plugin].pl_configure != NULL) {
850 			if (!plugins[args.pa_plugin].pl_configure(opt))
851 				err(EX_USAGE,
852 				    "ERROR: unknown option <%s>.", opt);
853 		}
854 	}
855 }
856 
857 void
pmcstat_log_shutdown_logging(void)858 pmcstat_log_shutdown_logging(void)
859 {
860 
861 	pmcstat_shutdown_logging(&args, plugins, &pmcstat_stats);
862 }
863 
864 void
pmcstat_log_initialize_logging(void)865 pmcstat_log_initialize_logging(void)
866 {
867 
868 	pmcstat_initialize_logging(&pmcstat_kernproc,
869 	    &args, plugins, &pmcstat_npmcs, &pmcstat_mergepmc);
870 }
871