1# SPDX-License-Identifier: GPL-2.0
2# intel-pt-events.py: Print Intel PT Events including Power Events and PTWRITE
3# Copyright (c) 2017-2021, Intel Corporation.
4#
5# This program is free software; you can redistribute it and/or modify it
6# under the terms and conditions of the GNU General Public License,
7# version 2, as published by the Free Software Foundation.
8#
9# This program is distributed in the hope it will be useful, but WITHOUT
10# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12# more details.
13
14from __future__ import print_function
15
16import os
17import sys
18import struct
19import argparse
20
21from libxed import LibXED
22from ctypes import create_string_buffer, addressof
23
24sys.path.append(os.environ['PERF_EXEC_PATH'] + \
25	'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
26
27from perf_trace_context import perf_set_itrace_options, \
28	perf_sample_insn, perf_sample_srccode
29
30try:
31	broken_pipe_exception = BrokenPipeError
32except:
33	broken_pipe_exception = IOError
34
35glb_switch_str		= {}
36glb_insn		= False
37glb_disassembler	= None
38glb_src			= False
39glb_source_file_name	= None
40glb_line_number		= None
41glb_dso			= None
42
43def get_optional_null(perf_dict, field):
44	if field in perf_dict:
45		return perf_dict[field]
46	return ""
47
48def get_optional_zero(perf_dict, field):
49	if field in perf_dict:
50		return perf_dict[field]
51	return 0
52
53def get_optional_bytes(perf_dict, field):
54	if field in perf_dict:
55		return perf_dict[field]
56	return bytes()
57
58def get_optional(perf_dict, field):
59	if field in perf_dict:
60		return perf_dict[field]
61	return "[unknown]"
62
63def get_offset(perf_dict, field):
64	if field in perf_dict:
65		return "+%#x" % perf_dict[field]
66	return ""
67
68def trace_begin():
69	ap = argparse.ArgumentParser(usage = "", add_help = False)
70	ap.add_argument("--insn-trace", action='store_true')
71	ap.add_argument("--src-trace", action='store_true')
72	ap.add_argument("--all-switch-events", action='store_true')
73	global glb_args
74	global glb_insn
75	global glb_src
76	glb_args = ap.parse_args()
77	if glb_args.insn_trace:
78		print("Intel PT Instruction Trace")
79		itrace = "i0nsepwx"
80		glb_insn = True
81	elif glb_args.src_trace:
82		print("Intel PT Source Trace")
83		itrace = "i0nsepwx"
84		glb_insn = True
85		glb_src = True
86	else:
87		print("Intel PT Branch Trace, Power Events and PTWRITE")
88		itrace = "bepwx"
89	global glb_disassembler
90	try:
91		glb_disassembler = LibXED()
92	except:
93		glb_disassembler = None
94	perf_set_itrace_options(perf_script_context, itrace)
95
96def trace_end():
97	print("End")
98
99def trace_unhandled(event_name, context, event_fields_dict):
100		print(' '.join(['%s=%s'%(k,str(v))for k,v in sorted(event_fields_dict.items())]))
101
102def print_ptwrite(raw_buf):
103	data = struct.unpack_from("<IQ", raw_buf)
104	flags = data[0]
105	payload = data[1]
106	exact_ip = flags & 1
107	print("IP: %u payload: %#x" % (exact_ip, payload), end=' ')
108
109def print_cbr(raw_buf):
110	data = struct.unpack_from("<BBBBII", raw_buf)
111	cbr = data[0]
112	f = (data[4] + 500) / 1000
113	p = ((cbr * 1000 / data[2]) + 5) / 10
114	print("%3u  freq: %4u MHz  (%3u%%)" % (cbr, f, p), end=' ')
115
116def print_mwait(raw_buf):
117	data = struct.unpack_from("<IQ", raw_buf)
118	payload = data[1]
119	hints = payload & 0xff
120	extensions = (payload >> 32) & 0x3
121	print("hints: %#x extensions: %#x" % (hints, extensions), end=' ')
122
123def print_pwre(raw_buf):
124	data = struct.unpack_from("<IQ", raw_buf)
125	payload = data[1]
126	hw = (payload >> 7) & 1
127	cstate = (payload >> 12) & 0xf
128	subcstate = (payload >> 8) & 0xf
129	print("hw: %u cstate: %u sub-cstate: %u" % (hw, cstate, subcstate),
130		end=' ')
131
132def print_exstop(raw_buf):
133	data = struct.unpack_from("<I", raw_buf)
134	flags = data[0]
135	exact_ip = flags & 1
136	print("IP: %u" % (exact_ip), end=' ')
137
138def print_pwrx(raw_buf):
139	data = struct.unpack_from("<IQ", raw_buf)
140	payload = data[1]
141	deepest_cstate = payload & 0xf
142	last_cstate = (payload >> 4) & 0xf
143	wake_reason = (payload >> 8) & 0xf
144	print("deepest cstate: %u last cstate: %u wake reason: %#x" %
145		(deepest_cstate, last_cstate, wake_reason), end=' ')
146
147def print_psb(raw_buf):
148	data = struct.unpack_from("<IQ", raw_buf)
149	offset = data[1]
150	print("offset: %#x" % (offset), end=' ')
151
152def common_start_str(comm, sample):
153	ts = sample["time"]
154	cpu = sample["cpu"]
155	pid = sample["pid"]
156	tid = sample["tid"]
157	return "%16s %5u/%-5u [%03u] %9u.%09u  " % (comm, pid, tid, cpu, ts / 1000000000, ts %1000000000)
158
159def print_common_start(comm, sample, name):
160	flags_disp = get_optional_null(sample, "flags_disp")
161	# Unused fields:
162	# period      = sample["period"]
163	# phys_addr   = sample["phys_addr"]
164	# weight      = sample["weight"]
165	# transaction = sample["transaction"]
166	# cpumode     = get_optional_zero(sample, "cpumode")
167	print(common_start_str(comm, sample) + "%7s  %19s" % (name, flags_disp), end=' ')
168
169def print_instructions_start(comm, sample):
170	if "x" in get_optional_null(sample, "flags"):
171		print(common_start_str(comm, sample) + "x", end=' ')
172	else:
173		print(common_start_str(comm, sample), end='  ')
174
175def disassem(insn, ip):
176	inst = glb_disassembler.Instruction()
177	glb_disassembler.SetMode(inst, 0) # Assume 64-bit
178	buf = create_string_buffer(64)
179	buf.value = insn
180	return glb_disassembler.DisassembleOne(inst, addressof(buf), len(insn), ip)
181
182def print_common_ip(param_dict, sample, symbol, dso):
183	ip   = sample["ip"]
184	offs = get_offset(param_dict, "symoff")
185	if "cyc_cnt" in sample:
186		cyc_cnt = sample["cyc_cnt"]
187		insn_cnt = get_optional_zero(sample, "insn_cnt")
188		ipc_str = "  IPC: %#.2f (%u/%u)" % (insn_cnt / cyc_cnt, insn_cnt, cyc_cnt)
189	else:
190		ipc_str = ""
191	if glb_insn and glb_disassembler is not None:
192		insn = perf_sample_insn(perf_script_context)
193		if insn and len(insn):
194			cnt, text = disassem(insn, ip)
195			byte_str = ("%x" % ip).rjust(16)
196			if sys.version_info.major >= 3:
197				for k in range(cnt):
198					byte_str += " %02x" % insn[k]
199			else:
200				for k in xrange(cnt):
201					byte_str += " %02x" % ord(insn[k])
202			print("%-40s  %-30s" % (byte_str, text), end=' ')
203		print("%s%s (%s)" % (symbol, offs, dso), end=' ')
204	else:
205		print("%16x %s%s (%s)" % (ip, symbol, offs, dso), end=' ')
206	if "addr_correlates_sym" in sample:
207		addr   = sample["addr"]
208		dso    = get_optional(sample, "addr_dso")
209		symbol = get_optional(sample, "addr_symbol")
210		offs   = get_offset(sample, "addr_symoff")
211		print("=> %x %s%s (%s)%s" % (addr, symbol, offs, dso, ipc_str))
212	else:
213		print(ipc_str)
214
215def print_srccode(comm, param_dict, sample, symbol, dso, with_insn):
216	ip = sample["ip"]
217	if symbol == "[unknown]":
218		start_str = common_start_str(comm, sample) + ("%x" % ip).rjust(16).ljust(40)
219	else:
220		offs = get_offset(param_dict, "symoff")
221		start_str = common_start_str(comm, sample) + (symbol + offs).ljust(40)
222
223	if with_insn and glb_insn and glb_disassembler is not None:
224		insn = perf_sample_insn(perf_script_context)
225		if insn and len(insn):
226			cnt, text = disassem(insn, ip)
227		start_str += text.ljust(30)
228
229	global glb_source_file_name
230	global glb_line_number
231	global glb_dso
232
233	source_file_name, line_number, source_line = perf_sample_srccode(perf_script_context)
234	if source_file_name:
235		if glb_line_number == line_number and glb_source_file_name == source_file_name:
236			src_str = ""
237		else:
238			if len(source_file_name) > 40:
239				src_file = ("..." + source_file_name[-37:]) + " "
240			else:
241				src_file = source_file_name.ljust(41)
242			if source_line is None:
243				src_str = src_file + str(line_number).rjust(4) + " <source not found>"
244			else:
245				src_str = src_file + str(line_number).rjust(4) + " " + source_line
246		glb_dso = None
247	elif dso == glb_dso:
248		src_str = ""
249	else:
250		src_str = dso
251		glb_dso = dso
252
253	glb_line_number = line_number
254	glb_source_file_name = source_file_name
255
256	print(start_str, src_str)
257
258def do_process_event(param_dict):
259	event_attr = param_dict["attr"]
260	sample	   = param_dict["sample"]
261	raw_buf	   = param_dict["raw_buf"]
262	comm	   = param_dict["comm"]
263	name	   = param_dict["ev_name"]
264	# Unused fields:
265	# callchain  = param_dict["callchain"]
266	# brstack    = param_dict["brstack"]
267	# brstacksym = param_dict["brstacksym"]
268
269	# Symbol and dso info are not always resolved
270	dso    = get_optional(param_dict, "dso")
271	symbol = get_optional(param_dict, "symbol")
272
273	cpu = sample["cpu"]
274	if cpu in glb_switch_str:
275		print(glb_switch_str[cpu])
276		del glb_switch_str[cpu]
277
278	if name[0:12] == "instructions":
279		if glb_src:
280			print_srccode(comm, param_dict, sample, symbol, dso, True)
281		else:
282			print_instructions_start(comm, sample)
283			print_common_ip(param_dict, sample, symbol, dso)
284	elif name[0:8] == "branches":
285		if glb_src:
286			print_srccode(comm, param_dict, sample, symbol, dso, False)
287		else:
288			print_common_start(comm, sample, name)
289			print_common_ip(param_dict, sample, symbol, dso)
290	elif name == "ptwrite":
291		print_common_start(comm, sample, name)
292		print_ptwrite(raw_buf)
293		print_common_ip(param_dict, sample, symbol, dso)
294	elif name == "cbr":
295		print_common_start(comm, sample, name)
296		print_cbr(raw_buf)
297		print_common_ip(param_dict, sample, symbol, dso)
298	elif name == "mwait":
299		print_common_start(comm, sample, name)
300		print_mwait(raw_buf)
301		print_common_ip(param_dict, sample, symbol, dso)
302	elif name == "pwre":
303		print_common_start(comm, sample, name)
304		print_pwre(raw_buf)
305		print_common_ip(param_dict, sample, symbol, dso)
306	elif name == "exstop":
307		print_common_start(comm, sample, name)
308		print_exstop(raw_buf)
309		print_common_ip(param_dict, sample, symbol, dso)
310	elif name == "pwrx":
311		print_common_start(comm, sample, name)
312		print_pwrx(raw_buf)
313		print_common_ip(param_dict, sample, symbol, dso)
314	elif name == "psb":
315		print_common_start(comm, sample, name)
316		print_psb(raw_buf)
317		print_common_ip(param_dict, sample, symbol, dso)
318	else:
319		print_common_start(comm, sample, name)
320		print_common_ip(param_dict, sample, symbol, dso)
321
322def process_event(param_dict):
323	try:
324		do_process_event(param_dict)
325	except broken_pipe_exception:
326		# Stop python printing broken pipe errors and traceback
327		sys.stdout = open(os.devnull, 'w')
328		sys.exit(1)
329
330def auxtrace_error(typ, code, cpu, pid, tid, ip, ts, msg, cpumode, *x):
331	try:
332		print("%16s %5u/%-5u [%03u] %9u.%09u  error type %u code %u: %s ip 0x%16x" %
333			("Trace error", pid, tid, cpu, ts / 1000000000, ts %1000000000, typ, code, msg, ip))
334	except broken_pipe_exception:
335		# Stop python printing broken pipe errors and traceback
336		sys.stdout = open(os.devnull, 'w')
337		sys.exit(1)
338
339def context_switch(ts, cpu, pid, tid, np_pid, np_tid, machine_pid, out, out_preempt, *x):
340	if out:
341		out_str = "Switch out "
342	else:
343		out_str = "Switch In  "
344	if out_preempt:
345		preempt_str = "preempt"
346	else:
347		preempt_str = ""
348	if machine_pid == -1:
349		machine_str = ""
350	else:
351		machine_str = "machine PID %d" % machine_pid
352	switch_str = "%16s %5d/%-5d [%03u] %9u.%09u %5d/%-5d %s %s" % \
353		(out_str, pid, tid, cpu, ts / 1000000000, ts %1000000000, np_pid, np_tid, machine_str, preempt_str)
354	if glb_args.all_switch_events:
355		print(switch_str);
356	else:
357		global glb_switch_str
358		glb_switch_str[cpu] = switch_str
359