1perf-intel-pt(1)
2================
3
4NAME
5----
6perf-intel-pt - Support for Intel Processor Trace within perf tools
7
8SYNOPSIS
9--------
10[verse]
11'perf record' -e intel_pt//
12
13DESCRIPTION
14-----------
15
16Intel Processor Trace (Intel PT) is an extension of Intel Architecture that
17collects information about software execution such as control flow, execution
18modes and timings and formats it into highly compressed binary packets.
19Technical details are documented in the Intel 64 and IA-32 Architectures
20Software Developer Manuals, Chapter 36 Intel Processor Trace.
21
22Intel PT is first supported in Intel Core M and 5th generation Intel Core
23processors that are based on the Intel micro-architecture code name Broadwell.
24
25Trace data is collected by 'perf record' and stored within the perf.data file.
26See below for options to 'perf record'.
27
28Trace data must be 'decoded' which involves walking the object code and matching
29the trace data packets. For example a TNT packet only tells whether a
30conditional branch was taken or not taken, so to make use of that packet the
31decoder must know precisely which instruction was being executed.
32
33Decoding is done on-the-fly.  The decoder outputs samples in the same format as
34samples output by perf hardware events, for example as though the "instructions"
35or "branches" events had been recorded.  Presently 3 tools support this:
36'perf script', 'perf report' and 'perf inject'.  See below for more information
37on using those tools.
38
39The main distinguishing feature of Intel PT is that the decoder can determine
40the exact flow of software execution.  Intel PT can be used to understand why
41and how did software get to a certain point, or behave a certain way.  The
42software does not have to be recompiled, so Intel PT works with debug or release
43builds, however the executed images are needed - which makes use in JIT-compiled
44environments, or with self-modified code, a challenge.  Also symbols need to be
45provided to make sense of addresses.
46
47A limitation of Intel PT is that it produces huge amounts of trace data
48(hundreds of megabytes per second per core) which takes a long time to decode,
49for example two or three orders of magnitude longer than it took to collect.
50Another limitation is the performance impact of tracing, something that will
51vary depending on the use-case and architecture.
52
53
54Quickstart
55----------
56
57It is important to start small.  That is because it is easy to capture vastly
58more data than can possibly be processed.
59
60The simplest thing to do with Intel PT is userspace profiling of small programs.
61Data is captured with 'perf record' e.g. to trace 'ls' userspace-only:
62
63	perf record -e intel_pt//u ls
64
65And profiled with 'perf report' e.g.
66
67	perf report
68
69To also trace kernel space presents a problem, namely kernel self-modifying
70code.  A fairly good kernel image is available in /proc/kcore but to get an
71accurate image a copy of /proc/kcore needs to be made under the same conditions
72as the data capture. 'perf record' can make a copy of /proc/kcore if the option
73--kcore is used, but access to /proc/kcore is restricted e.g.
74
75	sudo perf record -o pt_ls --kcore -e intel_pt// -- ls
76
77which will create a directory named 'pt_ls' and put the perf.data file (named
78simply 'data') and copies of /proc/kcore, /proc/kallsyms and /proc/modules into
79it.  The other tools understand the directory format, so to use 'perf report'
80becomes:
81
82	sudo perf report -i pt_ls
83
84Because samples are synthesized after-the-fact, the sampling period can be
85selected for reporting. e.g. sample every microsecond
86
87	sudo perf report pt_ls --itrace=i1usge
88
89See the sections below for more information about the --itrace option.
90
91Beware the smaller the period, the more samples that are produced, and the
92longer it takes to process them.
93
94Also note that the coarseness of Intel PT timing information will start to
95distort the statistical value of the sampling as the sampling period becomes
96smaller.
97
98To represent software control flow, "branches" samples are produced.  By default
99a branch sample is synthesized for every single branch.  To get an idea what
100data is available you can use the 'perf script' tool with all itrace sampling
101options, which will list all the samples.
102
103	perf record -e intel_pt//u ls
104	perf script --itrace=ibxwpe
105
106An interesting field that is not printed by default is 'flags' which can be
107displayed as follows:
108
109	perf script --itrace=ibxwpe -F+flags
110
111The flags are "bcrosyiABExgh" which stand for branch, call, return, conditional,
112system, asynchronous, interrupt, transaction abort, trace begin, trace end,
113in transaction, VM-entry, and VM-exit respectively.
114
115perf script also supports higher level ways to dump instruction traces:
116
117	perf script --insn-trace --xed
118
119Dump all instructions. This requires installing the xed tool (see XED below)
120Dumping all instructions in a long trace can be fairly slow. It is usually better
121to start with higher level decoding, like
122
123	perf script --call-trace
124
125or
126
127	perf script --call-ret-trace
128
129and then select a time range of interest. The time range can then be examined
130in detail with
131
132	perf script --time starttime,stoptime --insn-trace --xed
133
134While examining the trace it's also useful to filter on specific CPUs using
135the -C option
136
137	perf script --time starttime,stoptime --insn-trace --xed -C 1
138
139Dump all instructions in time range on CPU 1.
140
141Another interesting field that is not printed by default is 'ipc' which can be
142displayed as follows:
143
144	perf script --itrace=be -F+ipc
145
146There are two ways that instructions-per-cycle (IPC) can be calculated depending
147on the recording.
148
149If the 'cyc' config term (see config terms section below) was used, then IPC is
150calculated using the cycle count from CYC packets, otherwise MTC packets are
151used - refer to the 'mtc' config term.  When MTC is used, however, the values
152are less accurate because the timing is less accurate.
153
154Because Intel PT does not update the cycle count on every branch or instruction,
155the values will often be zero.  When there are values, they will be the number
156of instructions and number of cycles since the last update, and thus represent
157the average IPC since the last IPC for that event type.  Note IPC for "branches"
158events is calculated separately from IPC for "instructions" events.
159
160Even with the 'cyc' config term, it is possible to produce IPC information for
161every change of timestamp, but at the expense of accuracy.  That is selected by
162specifying the itrace 'A' option.  Due to the granularity of timestamps, the
163actual number of cycles increases even though the cycles reported does not.
164The number of instructions is known, but if IPC is reported, cycles can be too
165low and so IPC is too high.  Note that inaccuracy decreases as the period of
166sampling increases i.e. if the number of cycles is too low by a small amount,
167that becomes less significant if the number of cycles is large.  It may also be
168useful to use the 'A' option in conjunction with dlfilter-show-cycles.so to
169provide higher granularity cycle information.
170
171Also note that the IPC instruction count may or may not include the current
172instruction.  If the cycle count is associated with an asynchronous branch
173(e.g. page fault or interrupt), then the instruction count does not include the
174current instruction, otherwise it does.  That is consistent with whether or not
175that instruction has retired when the cycle count is updated.
176
177Another note, in the case of "branches" events, non-taken branches are not
178presently sampled, so IPC values for them do not appear e.g. a CYC packet with a
179TNT packet that starts with a non-taken branch.  To see every possible IPC
180value, "instructions" events can be used e.g. --itrace=i0ns
181
182While it is possible to create scripts to analyze the data, an alternative
183approach is available to export the data to a sqlite or postgresql database.
184Refer to script export-to-sqlite.py or export-to-postgresql.py for more details,
185and to script exported-sql-viewer.py for an example of using the database.
186
187There is also script intel-pt-events.py which provides an example of how to
188unpack the raw data for power events and PTWRITE. The script also displays
189branches, and supports 2 additional modes selected by option:
190
191 --insn-trace - instruction trace
192 --src-trace - source trace
193
194As mentioned above, it is easy to capture too much data.  One way to limit the
195data captured is to use 'snapshot' mode which is explained further below.
196Refer to 'new snapshot option' and 'Intel PT modes of operation' further below.
197
198Another problem that will be experienced is decoder errors.  They can be caused
199by inability to access the executed image, self-modified or JIT-ed code, or the
200inability to match side-band information (such as context switches and mmaps)
201which results in the decoder not knowing what code was executed.
202
203There is also the problem of perf not being able to copy the data fast enough,
204resulting in data lost because the buffer was full.  See 'Buffer handling' below
205for more details.
206
207
208perf record
209-----------
210
211new event
212~~~~~~~~~
213
214The Intel PT kernel driver creates a new PMU for Intel PT.  PMU events are
215selected by providing the PMU name followed by the "config" separated by slashes.
216An enhancement has been made to allow default "config" e.g. the option
217
218	-e intel_pt//
219
220will use a default config value.  Currently that is the same as
221
222	-e intel_pt/tsc,noretcomp=0/
223
224which is the same as
225
226	-e intel_pt/tsc=1,noretcomp=0/
227
228Note there are now new config terms - see section 'config terms' further below.
229
230The config terms are listed in /sys/devices/intel_pt/format.  They are bit
231fields within the config member of the struct perf_event_attr which is
232passed to the kernel by the perf_event_open system call.  They correspond to bit
233fields in the IA32_RTIT_CTL MSR.  Here is a list of them and their definitions:
234
235	$ grep -H . /sys/bus/event_source/devices/intel_pt/format/*
236	/sys/bus/event_source/devices/intel_pt/format/cyc:config:1
237	/sys/bus/event_source/devices/intel_pt/format/cyc_thresh:config:19-22
238	/sys/bus/event_source/devices/intel_pt/format/mtc:config:9
239	/sys/bus/event_source/devices/intel_pt/format/mtc_period:config:14-17
240	/sys/bus/event_source/devices/intel_pt/format/noretcomp:config:11
241	/sys/bus/event_source/devices/intel_pt/format/psb_period:config:24-27
242	/sys/bus/event_source/devices/intel_pt/format/tsc:config:10
243
244Note that the default config must be overridden for each term i.e.
245
246	-e intel_pt/noretcomp=0/
247
248is the same as:
249
250	-e intel_pt/tsc=1,noretcomp=0/
251
252So, to disable TSC packets use:
253
254	-e intel_pt/tsc=0/
255
256It is also possible to specify the config value explicitly:
257
258	-e intel_pt/config=0x400/
259
260Note that, as with all events, the event is suffixed with event modifiers:
261
262	u	userspace
263	k	kernel
264	h	hypervisor
265	G	guest
266	H	host
267	p	precise ip
268
269'h', 'G' and 'H' are for virtualization which is not supported by Intel PT.
270'p' is also not relevant to Intel PT.  So only options 'u' and 'k' are
271meaningful for Intel PT.
272
273perf_event_attr is displayed if the -vv option is used e.g.
274
275	------------------------------------------------------------
276	perf_event_attr:
277	type                             6
278	size                             112
279	config                           0x400
280	{ sample_period, sample_freq }   1
281	sample_type                      IP|TID|TIME|CPU|IDENTIFIER
282	read_format                      ID
283	disabled                         1
284	inherit                          1
285	exclude_kernel                   1
286	exclude_hv                       1
287	enable_on_exec                   1
288	sample_id_all                    1
289	------------------------------------------------------------
290	sys_perf_event_open: pid 31104  cpu 0  group_fd -1  flags 0x8
291	sys_perf_event_open: pid 31104  cpu 1  group_fd -1  flags 0x8
292	sys_perf_event_open: pid 31104  cpu 2  group_fd -1  flags 0x8
293	sys_perf_event_open: pid 31104  cpu 3  group_fd -1  flags 0x8
294	------------------------------------------------------------
295
296
297config terms
298~~~~~~~~~~~~
299
300The June 2015 version of Intel 64 and IA-32 Architectures Software Developer
301Manuals, Chapter 36 Intel Processor Trace, defined new Intel PT features.
302Some of the features are reflect in new config terms.  All the config terms are
303described below.
304
305tsc		Always supported.  Produces TSC timestamp packets to provide
306		timing information.  In some cases it is possible to decode
307		without timing information, for example a per-thread context
308		that does not overlap executable memory maps.
309
310		The default config selects tsc (i.e. tsc=1).
311
312noretcomp	Always supported.  Disables "return compression" so a TIP packet
313		is produced when a function returns.  Causes more packets to be
314		produced but might make decoding more reliable.
315
316		The default config does not select noretcomp (i.e. noretcomp=0).
317
318psb_period	Allows the frequency of PSB packets to be specified.
319
320		The PSB packet is a synchronization packet that provides a
321		starting point for decoding or recovery from errors.
322
323		Support for psb_period is indicated by:
324
325			/sys/bus/event_source/devices/intel_pt/caps/psb_cyc
326
327		which contains "1" if the feature is supported and "0"
328		otherwise.
329
330		Valid values are given by:
331
332			/sys/bus/event_source/devices/intel_pt/caps/psb_periods
333
334		which contains a hexadecimal value, the bits of which represent
335		valid values e.g. bit 2 set means value 2 is valid.
336
337		The psb_period value is converted to the approximate number of
338		trace bytes between PSB packets as:
339
340			2 ^ (value + 11)
341
342		e.g. value 3 means 16KiB bytes between PSBs
343
344		If an invalid value is entered, the error message
345		will give a list of valid values e.g.
346
347			$ perf record -e intel_pt/psb_period=15/u uname
348			Invalid psb_period for intel_pt. Valid values are: 0-5
349
350		If MTC packets are selected, the default config selects a value
351		of 3 (i.e. psb_period=3) or the nearest lower value that is
352		supported (0 is always supported).  Otherwise the default is 0.
353
354		If decoding is expected to be reliable and the buffer is large
355		then a large PSB period can be used.
356
357		Because a TSC packet is produced with PSB, the PSB period can
358		also affect the granularity to timing information in the absence
359		of MTC or CYC.
360
361mtc		Produces MTC timing packets.
362
363		MTC packets provide finer grain timestamp information than TSC
364		packets.  MTC packets record time using the hardware crystal
365		clock (CTC) which is related to TSC packets using a TMA packet.
366
367		Support for this feature is indicated by:
368
369			/sys/bus/event_source/devices/intel_pt/caps/mtc
370
371		which contains "1" if the feature is supported and
372		"0" otherwise.
373
374		The frequency of MTC packets can also be specified - see
375		mtc_period below.
376
377mtc_period	Specifies how frequently MTC packets are produced - see mtc
378		above for how to determine if MTC packets are supported.
379
380		Valid values are given by:
381
382			/sys/bus/event_source/devices/intel_pt/caps/mtc_periods
383
384		which contains a hexadecimal value, the bits of which represent
385		valid values e.g. bit 2 set means value 2 is valid.
386
387		The mtc_period value is converted to the MTC frequency as:
388
389			CTC-frequency / (2 ^ value)
390
391		e.g. value 3 means one eighth of CTC-frequency
392
393		Where CTC is the hardware crystal clock, the frequency of which
394		can be related to TSC via values provided in cpuid leaf 0x15.
395
396		If an invalid value is entered, the error message
397		will give a list of valid values e.g.
398
399			$ perf record -e intel_pt/mtc_period=15/u uname
400			Invalid mtc_period for intel_pt. Valid values are: 0,3,6,9
401
402		The default value is 3 or the nearest lower value
403		that is supported (0 is always supported).
404
405cyc		Produces CYC timing packets.
406
407		CYC packets provide even finer grain timestamp information than
408		MTC and TSC packets.  A CYC packet contains the number of CPU
409		cycles since the last CYC packet. Unlike MTC and TSC packets,
410		CYC packets are only sent when another packet is also sent.
411
412		Support for this feature is indicated by:
413
414			/sys/bus/event_source/devices/intel_pt/caps/psb_cyc
415
416		which contains "1" if the feature is supported and
417		"0" otherwise.
418
419		The number of CYC packets produced can be reduced by specifying
420		a threshold - see cyc_thresh below.
421
422cyc_thresh	Specifies how frequently CYC packets are produced - see cyc
423		above for how to determine if CYC packets are supported.
424
425		Valid cyc_thresh values are given by:
426
427			/sys/bus/event_source/devices/intel_pt/caps/cycle_thresholds
428
429		which contains a hexadecimal value, the bits of which represent
430		valid values e.g. bit 2 set means value 2 is valid.
431
432		The cyc_thresh value represents the minimum number of CPU cycles
433		that must have passed before a CYC packet can be sent.  The
434		number of CPU cycles is:
435
436			2 ^ (value - 1)
437
438		e.g. value 4 means 8 CPU cycles must pass before a CYC packet
439		can be sent.  Note a CYC packet is still only sent when another
440		packet is sent, not at, e.g. every 8 CPU cycles.
441
442		If an invalid value is entered, the error message
443		will give a list of valid values e.g.
444
445			$ perf record -e intel_pt/cyc,cyc_thresh=15/u uname
446			Invalid cyc_thresh for intel_pt. Valid values are: 0-12
447
448		CYC packets are not requested by default.
449
450pt		Specifies pass-through which enables the 'branch' config term.
451
452		The default config selects 'pt' if it is available, so a user will
453		never need to specify this term.
454
455branch		Enable branch tracing.  Branch tracing is enabled by default so to
456		disable branch tracing use 'branch=0'.
457
458		The default config selects 'branch' if it is available.
459
460ptw		Enable PTWRITE packets which are produced when a ptwrite instruction
461		is executed.
462
463		Support for this feature is indicated by:
464
465			/sys/bus/event_source/devices/intel_pt/caps/ptwrite
466
467		which contains "1" if the feature is supported and
468		"0" otherwise.
469
470fup_on_ptw	Enable a FUP packet to follow the PTWRITE packet.  The FUP packet
471		provides the address of the ptwrite instruction.  In the absence of
472		fup_on_ptw, the decoder will use the address of the previous branch
473		if branch tracing is enabled, otherwise the address will be zero.
474		Note that fup_on_ptw will work even when branch tracing is disabled.
475
476pwr_evt		Enable power events.  The power events provide information about
477		changes to the CPU C-state.
478
479		Support for this feature is indicated by:
480
481			/sys/bus/event_source/devices/intel_pt/caps/power_event_trace
482
483		which contains "1" if the feature is supported and
484		"0" otherwise.
485
486
487AUX area sampling option
488~~~~~~~~~~~~~~~~~~~~~~~~
489
490To select Intel PT "sampling" the AUX area sampling option can be used:
491
492	--aux-sample
493
494Optionally it can be followed by the sample size in bytes e.g.
495
496	--aux-sample=8192
497
498In addition, the Intel PT event to sample must be defined e.g.
499
500	-e intel_pt//u
501
502Samples on other events will be created containing Intel PT data e.g. the
503following will create Intel PT samples on the branch-misses event, note the
504events must be grouped using {}:
505
506	perf record --aux-sample -e '{intel_pt//u,branch-misses:u}'
507
508An alternative to '--aux-sample' is to add the config term 'aux-sample-size' to
509events.  In this case, the grouping is implied e.g.
510
511	perf record -e intel_pt//u -e branch-misses/aux-sample-size=8192/u
512
513is the same as:
514
515	perf record -e '{intel_pt//u,branch-misses/aux-sample-size=8192/u}'
516
517but allows for also using an address filter e.g.:
518
519	perf record -e intel_pt//u --filter 'filter * @/bin/ls' -e branch-misses/aux-sample-size=8192/u -- ls
520
521It is important to select a sample size that is big enough to contain at least
522one PSB packet.  If not a warning will be displayed:
523
524	Intel PT sample size (%zu) may be too small for PSB period (%zu)
525
526The calculation used for that is: if sample_size <= psb_period + 256 display the
527warning.  When sampling is used, psb_period defaults to 0 (2KiB).
528
529The default sample size is 4KiB.
530
531The sample size is passed in aux_sample_size in struct perf_event_attr.  The
532sample size is limited by the maximum event size which is 64KiB.  It is
533difficult to know how big the event might be without the trace sample attached,
534but the tool validates that the sample size is not greater than 60KiB.
535
536
537new snapshot option
538~~~~~~~~~~~~~~~~~~~
539
540The difference between full trace and snapshot from the kernel's perspective is
541that in full trace we don't overwrite trace data that the user hasn't collected
542yet (and indicated that by advancing aux_tail), whereas in snapshot mode we let
543the trace run and overwrite older data in the buffer so that whenever something
544interesting happens, we can stop it and grab a snapshot of what was going on
545around that interesting moment.
546
547To select snapshot mode a new option has been added:
548
549	-S
550
551Optionally it can be followed by the snapshot size e.g.
552
553	-S0x100000
554
555The default snapshot size is the auxtrace mmap size.  If neither auxtrace mmap size
556nor snapshot size is specified, then the default is 4MiB for privileged users
557(or if /proc/sys/kernel/perf_event_paranoid < 0), 128KiB for unprivileged users.
558If an unprivileged user does not specify mmap pages, the mmap pages will be
559reduced as described in the 'new auxtrace mmap size option' section below.
560
561The snapshot size is displayed if the option -vv is used e.g.
562
563	Intel PT snapshot size: %zu
564
565
566new auxtrace mmap size option
567~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
568
569Intel PT buffer size is specified by an addition to the -m option e.g.
570
571	-m,16
572
573selects a buffer size of 16 pages i.e. 64KiB.
574
575Note that the existing functionality of -m is unchanged.  The auxtrace mmap size
576is specified by the optional addition of a comma and the value.
577
578The default auxtrace mmap size for Intel PT is 4MiB/page_size for privileged users
579(or if /proc/sys/kernel/perf_event_paranoid < 0), 128KiB for unprivileged users.
580If an unprivileged user does not specify mmap pages, the mmap pages will be
581reduced from the default 512KiB/page_size to 256KiB/page_size, otherwise the
582user is likely to get an error as they exceed their mlock limit (Max locked
583memory as shown in /proc/self/limits).  Note that perf does not count the first
584512KiB (actually /proc/sys/kernel/perf_event_mlock_kb minus 1 page) per cpu
585against the mlock limit so an unprivileged user is allowed 512KiB per cpu plus
586their mlock limit (which defaults to 64KiB but is not multiplied by the number
587of cpus).
588
589In full-trace mode, powers of two are allowed for buffer size, with a minimum
590size of 2 pages.  In snapshot mode or sampling mode, it is the same but the
591minimum size is 1 page.
592
593The mmap size and auxtrace mmap size are displayed if the -vv option is used e.g.
594
595	mmap length 528384
596	auxtrace mmap length 4198400
597
598
599Intel PT modes of operation
600~~~~~~~~~~~~~~~~~~~~~~~~~~~
601
602Intel PT can be used in 3 modes:
603	full-trace mode
604	sample mode
605	snapshot mode
606
607Full-trace mode traces continuously e.g.
608
609	perf record -e intel_pt//u uname
610
611Sample mode attaches a Intel PT sample to other events e.g.
612
613	perf record --aux-sample -e intel_pt//u -e branch-misses:u
614
615Snapshot mode captures the available data when a signal is sent or "snapshot"
616control command is issued. e.g. using a signal
617
618	perf record -v -e intel_pt//u -S ./loopy 1000000000 &
619	[1] 11435
620	kill -USR2 11435
621	Recording AUX area tracing snapshot
622
623Note that the signal sent is SIGUSR2.
624Note that "Recording AUX area tracing snapshot" is displayed because the -v
625option is used.
626
627The advantage of using "snapshot" control command is that the access is
628controlled by access to a FIFO e.g.
629
630	$ mkfifo perf.control
631	$ mkfifo perf.ack
632	$ cat perf.ack &
633	[1] 15235
634	$ sudo ~/bin/perf record --control fifo:perf.control,perf.ack -S -e intel_pt//u -- sleep 60 &
635	[2] 15243
636	$ ps -e | grep perf
637	15244 pts/1    00:00:00 perf
638	$ kill -USR2 15244
639	bash: kill: (15244) - Operation not permitted
640	$ echo snapshot > perf.control
641	ack
642
643The 3 Intel PT modes of operation cannot be used together.
644
645
646Buffer handling
647~~~~~~~~~~~~~~~
648
649There may be buffer limitations (i.e. single ToPa entry) which means that actual
650buffer sizes are limited to powers of 2 up to 4MiB (MAX_ORDER).  In order to
651provide other sizes, and in particular an arbitrarily large size, multiple
652buffers are logically concatenated.  However an interrupt must be used to switch
653between buffers.  That has two potential problems:
654	a) the interrupt may not be handled in time so that the current buffer
655	becomes full and some trace data is lost.
656	b) the interrupts may slow the system and affect the performance
657	results.
658
659If trace data is lost, the driver sets 'truncated' in the PERF_RECORD_AUX event
660which the tools report as an error.
661
662In full-trace mode, the driver waits for data to be copied out before allowing
663the (logical) buffer to wrap-around.  If data is not copied out quickly enough,
664again 'truncated' is set in the PERF_RECORD_AUX event.  If the driver has to
665wait, the intel_pt event gets disabled.  Because it is difficult to know when
666that happens, perf tools always re-enable the intel_pt event after copying out
667data.
668
669
670Intel PT and build ids
671~~~~~~~~~~~~~~~~~~~~~~
672
673By default "perf record" post-processes the event stream to find all build ids
674for executables for all addresses sampled.  Deliberately, Intel PT is not
675decoded for that purpose (it would take too long).  Instead the build ids for
676all executables encountered (due to mmap, comm or task events) are included
677in the perf.data file.
678
679To see buildids included in the perf.data file use the command:
680
681	perf buildid-list
682
683If the perf.data file contains Intel PT data, that is the same as:
684
685	perf buildid-list --with-hits
686
687
688Snapshot mode and event disabling
689~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
690
691In order to make a snapshot, the intel_pt event is disabled using an IOCTL,
692namely PERF_EVENT_IOC_DISABLE.  However doing that can also disable the
693collection of side-band information.  In order to prevent that,  a dummy
694software event has been introduced that permits tracking events (like mmaps) to
695continue to be recorded while intel_pt is disabled.  That is important to ensure
696there is complete side-band information to allow the decoding of subsequent
697snapshots.
698
699A test has been created for that.  To find the test:
700
701	perf test list
702	...
703	23: Test using a dummy software event to keep tracking
704
705To run the test:
706
707	perf test 23
708	23: Test using a dummy software event to keep tracking     : Ok
709
710
711perf record modes (nothing new here)
712~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
713
714perf record essentially operates in one of three modes:
715	per thread
716	per cpu
717	workload only
718
719"per thread" mode is selected by -t or by --per-thread (with -p or -u or just a
720workload).
721"per cpu" is selected by -C or -a.
722"workload only" mode is selected by not using the other options but providing a
723command to run (i.e. the workload).
724
725In per-thread mode an exact list of threads is traced.  There is no inheritance.
726Each thread has its own event buffer.
727
728In per-cpu mode all processes (or processes from the selected cgroup i.e. -G
729option, or processes selected with -p or -u) are traced.  Each cpu has its own
730buffer. Inheritance is allowed.
731
732In workload-only mode, the workload is traced but with per-cpu buffers.
733Inheritance is allowed.  Note that you can now trace a workload in per-thread
734mode by using the --per-thread option.
735
736
737Privileged vs non-privileged users
738~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
739
740Unless /proc/sys/kernel/perf_event_paranoid is set to -1, unprivileged users
741have memory limits imposed upon them.  That affects what buffer sizes they can
742have as outlined above.
743
744The v4.2 kernel introduced support for a context switch metadata event,
745PERF_RECORD_SWITCH, which allows unprivileged users to see when their processes
746are scheduled out and in, just not by whom, which is left for the
747PERF_RECORD_SWITCH_CPU_WIDE, that is only accessible in system wide context,
748which in turn requires CAP_PERFMON or CAP_SYS_ADMIN.
749
750Please see the 45ac1403f564 ("perf: Add PERF_RECORD_SWITCH to indicate context
751switches") commit, that introduces these metadata events for further info.
752
753When working with kernels < v4.2, the following considerations must be taken,
754as the sched:sched_switch tracepoints will be used to receive such information:
755
756Unless /proc/sys/kernel/perf_event_paranoid is set to -1, unprivileged users are
757not permitted to use tracepoints which means there is insufficient side-band
758information to decode Intel PT in per-cpu mode, and potentially workload-only
759mode too if the workload creates new processes.
760
761Note also, that to use tracepoints, read-access to debugfs is required.  So if
762debugfs is not mounted or the user does not have read-access, it will again not
763be possible to decode Intel PT in per-cpu mode.
764
765
766sched_switch tracepoint
767~~~~~~~~~~~~~~~~~~~~~~~
768
769The sched_switch tracepoint is used to provide side-band data for Intel PT
770decoding in kernels where the PERF_RECORD_SWITCH metadata event isn't
771available.
772
773The sched_switch events are automatically added. e.g. the second event shown
774below:
775
776	$ perf record -vv -e intel_pt//u uname
777	------------------------------------------------------------
778	perf_event_attr:
779	type                             6
780	size                             112
781	config                           0x400
782	{ sample_period, sample_freq }   1
783	sample_type                      IP|TID|TIME|CPU|IDENTIFIER
784	read_format                      ID
785	disabled                         1
786	inherit                          1
787	exclude_kernel                   1
788	exclude_hv                       1
789	enable_on_exec                   1
790	sample_id_all                    1
791	------------------------------------------------------------
792	sys_perf_event_open: pid 31104  cpu 0  group_fd -1  flags 0x8
793	sys_perf_event_open: pid 31104  cpu 1  group_fd -1  flags 0x8
794	sys_perf_event_open: pid 31104  cpu 2  group_fd -1  flags 0x8
795	sys_perf_event_open: pid 31104  cpu 3  group_fd -1  flags 0x8
796	------------------------------------------------------------
797	perf_event_attr:
798	type                             2
799	size                             112
800	config                           0x108
801	{ sample_period, sample_freq }   1
802	sample_type                      IP|TID|TIME|CPU|PERIOD|RAW|IDENTIFIER
803	read_format                      ID
804	inherit                          1
805	sample_id_all                    1
806	exclude_guest                    1
807	------------------------------------------------------------
808	sys_perf_event_open: pid -1  cpu 0  group_fd -1  flags 0x8
809	sys_perf_event_open: pid -1  cpu 1  group_fd -1  flags 0x8
810	sys_perf_event_open: pid -1  cpu 2  group_fd -1  flags 0x8
811	sys_perf_event_open: pid -1  cpu 3  group_fd -1  flags 0x8
812	------------------------------------------------------------
813	perf_event_attr:
814	type                             1
815	size                             112
816	config                           0x9
817	{ sample_period, sample_freq }   1
818	sample_type                      IP|TID|TIME|IDENTIFIER
819	read_format                      ID
820	disabled                         1
821	inherit                          1
822	exclude_kernel                   1
823	exclude_hv                       1
824	mmap                             1
825	comm                             1
826	enable_on_exec                   1
827	task                             1
828	sample_id_all                    1
829	mmap2                            1
830	comm_exec                        1
831	------------------------------------------------------------
832	sys_perf_event_open: pid 31104  cpu 0  group_fd -1  flags 0x8
833	sys_perf_event_open: pid 31104  cpu 1  group_fd -1  flags 0x8
834	sys_perf_event_open: pid 31104  cpu 2  group_fd -1  flags 0x8
835	sys_perf_event_open: pid 31104  cpu 3  group_fd -1  flags 0x8
836	mmap size 528384B
837	AUX area mmap length 4194304
838	perf event ring buffer mmapped per cpu
839	Synthesizing auxtrace information
840	Linux
841	[ perf record: Woken up 1 times to write data ]
842	[ perf record: Captured and wrote 0.042 MB perf.data ]
843
844Note, the sched_switch event is only added if the user is permitted to use it
845and only in per-cpu mode.
846
847Note also, the sched_switch event is only added if TSC packets are requested.
848That is because, in the absence of timing information, the sched_switch events
849cannot be matched against the Intel PT trace.
850
851
852perf script
853-----------
854
855By default, perf script will decode trace data found in the perf.data file.
856This can be further controlled by new option --itrace.
857
858
859New --itrace option
860~~~~~~~~~~~~~~~~~~~
861
862Having no option is the same as
863
864	--itrace
865
866which, in turn, is the same as
867
868	--itrace=cepwx
869
870The letters are:
871
872	i	synthesize "instructions" events
873	b	synthesize "branches" events
874	x	synthesize "transactions" events
875	w	synthesize "ptwrite" events
876	p	synthesize "power" events (incl. PSB events)
877	c	synthesize branches events (calls only)
878	r	synthesize branches events (returns only)
879	e	synthesize tracing error events
880	d	create a debug log
881	g	synthesize a call chain (use with i or x)
882	G	synthesize a call chain on existing event records
883	l	synthesize last branch entries (use with i or x)
884	L	synthesize last branch entries on existing event records
885	s	skip initial number of events
886	q	quicker (less detailed) decoding
887	A	approximate IPC
888	Z	prefer to ignore timestamps (so-called "timeless" decoding)
889
890"Instructions" events look like they were recorded by "perf record -e
891instructions".
892
893"Branches" events look like they were recorded by "perf record -e branches". "c"
894and "r" can be combined to get calls and returns.
895
896"Transactions" events correspond to the start or end of transactions. The
897'flags' field can be used in perf script to determine whether the event is a
898transaction start, commit or abort.
899
900Note that "instructions", "branches" and "transactions" events depend on code
901flow packets which can be disabled by using the config term "branch=0".  Refer
902to the config terms section above.
903
904"ptwrite" events record the payload of the ptwrite instruction and whether
905"fup_on_ptw" was used.  "ptwrite" events depend on PTWRITE packets which are
906recorded only if the "ptw" config term was used.  Refer to the config terms
907section above.  perf script "synth" field displays "ptwrite" information like
908this: "ip: 0 payload: 0x123456789abcdef0"  where "ip" is 1 if "fup_on_ptw" was
909used.
910
911"Power" events correspond to power event packets and CBR (core-to-bus ratio)
912packets.  While CBR packets are always recorded when tracing is enabled, power
913event packets are recorded only if the "pwr_evt" config term was used.  Refer to
914the config terms section above.  The power events record information about
915C-state changes, whereas CBR is indicative of CPU frequency.  perf script
916"event,synth" fields display information like this:
917	cbr:  cbr: 22 freq: 2189 MHz (200%)
918	mwait:  hints: 0x60 extensions: 0x1
919	pwre:  hw: 0 cstate: 2 sub-cstate: 0
920	exstop:  ip: 1
921	pwrx:  deepest cstate: 2 last cstate: 2 wake reason: 0x4
922Where:
923	"cbr" includes the frequency and the percentage of maximum non-turbo
924	"mwait" shows mwait hints and extensions
925	"pwre" shows C-state transitions (to a C-state deeper than C0) and
926	whether	initiated by hardware
927	"exstop" indicates execution stopped and whether the IP was recorded
928	exactly,
929	"pwrx" indicates return to C0
930For more details refer to the Intel 64 and IA-32 Architectures Software
931Developer Manuals.
932
933PSB events show when a PSB+ occurred and also the byte-offset in the trace.
934Emitting a PSB+ can cause a CPU a slight delay. When doing timing analysis
935of code with Intel PT, it is useful to know if a timing bubble was caused
936by Intel PT or not.
937
938Error events show where the decoder lost the trace.  Error events
939are quite important.  Users must know if what they are seeing is a complete
940picture or not. The "e" option may be followed by flags which affect what errors
941will or will not be reported.  Each flag must be preceded by either '+' or '-'.
942The flags supported by Intel PT are:
943		-o	Suppress overflow errors
944		-l	Suppress trace data lost errors
945For example, for errors but not overflow or data lost errors:
946
947	--itrace=e-o-l
948
949The "d" option will cause the creation of a file "intel_pt.log" containing all
950decoded packets and instructions.  Note that this option slows down the decoder
951and that the resulting file may be very large.  The "d" option may be followed
952by flags which affect what debug messages will or will not be logged. Each flag
953must be preceded by either '+' or '-'. The flags support by Intel PT are:
954		-a	Suppress logging of perf events
955		+a	Log all perf events
956		+o	Output to stdout instead of "intel_pt.log"
957By default, logged perf events are filtered by any specified time ranges, but
958flag +a overrides that.
959
960In addition, the period of the "instructions" event can be specified. e.g.
961
962	--itrace=i10us
963
964sets the period to 10us i.e. one  instruction sample is synthesized for each 10
965microseconds of trace.  Alternatives to "us" are "ms" (milliseconds),
966"ns" (nanoseconds), "t" (TSC ticks) or "i" (instructions).
967
968"ms", "us" and "ns" are converted to TSC ticks.
969
970The timing information included with Intel PT does not give the time of every
971instruction.  Consequently, for the purpose of sampling, the decoder estimates
972the time since the last timing packet based on 1 tick per instruction.  The time
973on the sample is *not* adjusted and reflects the last known value of TSC.
974
975For Intel PT, the default period is 100us.
976
977Setting it to a zero period means "as often as possible".
978
979In the case of Intel PT that is the same as a period of 1 and a unit of
980'instructions' (i.e. --itrace=i1i).
981
982Also the call chain size (default 16, max. 1024) for instructions or
983transactions events can be specified. e.g.
984
985	--itrace=ig32
986	--itrace=xg32
987
988Also the number of last branch entries (default 64, max. 1024) for instructions or
989transactions events can be specified. e.g.
990
991       --itrace=il10
992       --itrace=xl10
993
994Note that last branch entries are cleared for each sample, so there is no overlap
995from one sample to the next.
996
997The G and L options are designed in particular for sample mode, and work much
998like g and l but add call chain and branch stack to the other selected events
999instead of synthesized events. For example, to record branch-misses events for
1000'ls' and then add a call chain derived from the Intel PT trace:
1001
1002	perf record --aux-sample -e '{intel_pt//u,branch-misses:u}' -- ls
1003	perf report --itrace=Ge
1004
1005Although in fact G is a default for perf report, so that is the same as just:
1006
1007	perf report
1008
1009One caveat with the G and L options is that they work poorly with "Large PEBS".
1010Large PEBS means PEBS records will be accumulated by hardware and the written
1011into the event buffer in one go.  That reduces interrupts, but can give very
1012late timestamps.  Because the Intel PT trace is synchronized by timestamps,
1013the PEBS events do not match the trace.  Currently, Large PEBS is used only in
1014certain circumstances:
1015	- hardware supports it
1016	- PEBS is used
1017	- event period is specified, instead of frequency
1018	- the sample type is limited to the following flags:
1019		PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_ADDR |
1020		PERF_SAMPLE_ID | PERF_SAMPLE_CPU | PERF_SAMPLE_STREAM_ID |
1021		PERF_SAMPLE_DATA_SRC | PERF_SAMPLE_IDENTIFIER |
1022		PERF_SAMPLE_TRANSACTION | PERF_SAMPLE_PHYS_ADDR |
1023		PERF_SAMPLE_REGS_INTR | PERF_SAMPLE_REGS_USER |
1024		PERF_SAMPLE_PERIOD (and sometimes) | PERF_SAMPLE_TIME
1025Because Intel PT sample mode uses a different sample type to the list above,
1026Large PEBS is not used with Intel PT sample mode. To avoid Large PEBS in other
1027cases, avoid specifying the event period i.e. avoid the 'perf record' -c option,
1028--count option, or 'period' config term.
1029
1030To disable trace decoding entirely, use the option --no-itrace.
1031
1032It is also possible to skip events generated (instructions, branches, transactions)
1033at the beginning. This is useful to ignore initialization code.
1034
1035	--itrace=i0nss1000000
1036
1037skips the first million instructions.
1038
1039The q option changes the way the trace is decoded.  The decoding is much faster
1040but much less detailed.  Specifically, with the q option, the decoder does not
1041decode TNT packets, and does not walk object code, but gets the ip from FUP and
1042TIP packets.  The q option can be used with the b and i options but the period
1043is not used.  The q option decodes more quickly, but is useful only if the
1044control flow of interest is represented or indicated by FUP, TIP, TIP.PGE, or
1045TIP.PGD packets (refer below).  However the q option could be used to find time
1046ranges that could then be decoded fully using the --time option.
1047
1048What will *not* be decoded with the (single) q option:
1049
1050	- direct calls and jmps
1051	- conditional branches
1052	- non-branch instructions
1053
1054What *will* be decoded with the (single) q option:
1055
1056	- asynchronous branches such as interrupts
1057	- indirect branches
1058	- function return target address *if* the noretcomp config term (refer
1059	config terms section) was used
1060	- start of (control-flow) tracing
1061	- end of (control-flow) tracing, if it is not out of context
1062	- power events, ptwrite, transaction start and abort
1063	- instruction pointer associated with PSB packets
1064
1065Note the q option does not specify what events will be synthesized e.g. the p
1066option must be used also to show power events.
1067
1068Repeating the q option (double-q i.e. qq) results in even faster decoding and even
1069less detail.  The decoder decodes only extended PSB (PSB+) packets, getting the
1070instruction pointer if there is a FUP packet within PSB+ (i.e. between PSB and
1071PSBEND).  Note PSB packets occur regularly in the trace based on the psb_period
1072config term (refer config terms section).  There will be a FUP packet if the
1073PSB+ occurs while control flow is being traced.
1074
1075What will *not* be decoded with the qq option:
1076
1077	- everything except instruction pointer associated with PSB packets
1078
1079What *will* be decoded with the qq option:
1080
1081	- instruction pointer associated with PSB packets
1082
1083The Z option is equivalent to having recorded a trace without TSC
1084(i.e. config term tsc=0). It can be useful to avoid timestamp issues when
1085decoding a trace of a virtual machine.
1086
1087
1088dlfilter-show-cycles.so
1089~~~~~~~~~~~~~~~~~~~~~~~
1090
1091Cycles can be displayed using dlfilter-show-cycles.so in which case the itrace A
1092option can be useful to provide higher granularity cycle information:
1093
1094	perf script --itrace=A --call-trace --dlfilter dlfilter-show-cycles.so
1095
1096To see a list of dlfilters:
1097
1098	perf script -v --list-dlfilters
1099
1100See also linkperf:perf-dlfilters[1]
1101
1102
1103dump option
1104~~~~~~~~~~~
1105
1106perf script has an option (-D) to "dump" the events i.e. display the binary
1107data.
1108
1109When -D is used, Intel PT packets are displayed.  The packet decoder does not
1110pay attention to PSB packets, but just decodes the bytes - so the packets seen
1111by the actual decoder may not be identical in places where the data is corrupt.
1112One example of that would be when the buffer-switching interrupt has been too
1113slow, and the buffer has been filled completely.  In that case, the last packet
1114in the buffer might be truncated and immediately followed by a PSB as the trace
1115continues in the next buffer.
1116
1117To disable the display of Intel PT packets, combine the -D option with
1118--no-itrace.
1119
1120
1121perf report
1122-----------
1123
1124By default, perf report will decode trace data found in the perf.data file.
1125This can be further controlled by new option --itrace exactly the same as
1126perf script, with the exception that the default is --itrace=igxe.
1127
1128
1129perf inject
1130-----------
1131
1132perf inject also accepts the --itrace option in which case tracing data is
1133removed and replaced with the synthesized events. e.g.
1134
1135	perf inject --itrace -i perf.data -o perf.data.new
1136
1137Below is an example of using Intel PT with autofdo.  It requires autofdo
1138(https://github.com/google/autofdo) and gcc version 5.  The bubble
1139sort example is from the AutoFDO tutorial (https://gcc.gnu.org/wiki/AutoFDO/Tutorial)
1140amended to take the number of elements as a parameter.
1141
1142	$ gcc-5 -O3 sort.c -o sort_optimized
1143	$ ./sort_optimized 30000
1144	Bubble sorting array of 30000 elements
1145	2254 ms
1146
1147	$ cat ~/.perfconfig
1148	[intel-pt]
1149		mispred-all = on
1150
1151	$ perf record -e intel_pt//u ./sort 3000
1152	Bubble sorting array of 3000 elements
1153	58 ms
1154	[ perf record: Woken up 2 times to write data ]
1155	[ perf record: Captured and wrote 3.939 MB perf.data ]
1156	$ perf inject -i perf.data -o inj --itrace=i100usle --strip
1157	$ ./create_gcov --binary=./sort --profile=inj --gcov=sort.gcov -gcov_version=1
1158	$ gcc-5 -O3 -fauto-profile=sort.gcov sort.c -o sort_autofdo
1159	$ ./sort_autofdo 30000
1160	Bubble sorting array of 30000 elements
1161	2155 ms
1162
1163Note there is currently no advantage to using Intel PT instead of LBR, but
1164that may change in the future if greater use is made of the data.
1165
1166
1167PEBS via Intel PT
1168-----------------
1169
1170Some hardware has the feature to redirect PEBS records to the Intel PT trace.
1171Recording is selected by using the aux-output config term e.g.
1172
1173	perf record -c 10000 -e '{intel_pt/branch=0/,cycles/aux-output/ppp}' uname
1174
1175Originally, software only supported redirecting at most one PEBS event because it
1176was not able to differentiate one event from another. To overcome that, more recent
1177kernels and perf tools add support for the PERF_RECORD_AUX_OUTPUT_HW_ID side-band event.
1178To check for the presence of that event in a PEBS-via-PT trace:
1179
1180	perf script -D --no-itrace | grep PERF_RECORD_AUX_OUTPUT_HW_ID
1181
1182To display PEBS events from the Intel PT trace, use the itrace 'o' option e.g.
1183
1184	perf script --itrace=oe
1185
1186XED
1187---
1188
1189include::build-xed.txt[]
1190
1191
1192Tracing Virtual Machines
1193------------------------
1194
1195Currently, only kernel tracing is supported and only with either "timeless" decoding
1196(i.e. no TSC timestamps) or VM Time Correlation. VM Time Correlation is an extra step
1197using 'perf inject' and requires unchanging VMX TSC Offset and no VMX TSC Scaling.
1198
1199Other limitations and caveats
1200
1201 VMX controls may suppress packets needed for decoding resulting in decoding errors
1202 VMX controls may block the perf NMI to the host potentially resulting in lost trace data
1203 Guest kernel self-modifying code (e.g. jump labels or JIT-compiled eBPF) will result in decoding errors
1204 Guest thread information is unknown
1205 Guest VCPU is unknown but may be able to be inferred from the host thread
1206 Callchains are not supported
1207
1208Example using "timeless" decoding
1209
1210Start VM
1211
1212 $ sudo virsh start kubuntu20.04
1213 Domain kubuntu20.04 started
1214
1215Mount the guest file system.  Note sshfs needs -o direct_io to enable reading of proc files.  root access is needed to read /proc/kcore.
1216
1217 $ mkdir vm0
1218 $ sshfs -o direct_io root@vm0:/ vm0
1219
1220Copy the guest /proc/kallsyms, /proc/modules and /proc/kcore
1221
1222 $ perf buildid-cache -v --kcore vm0/proc/kcore
1223 kcore added to build-id cache directory /home/user/.debug/[kernel.kcore]/9600f316a53a0f54278885e8d9710538ec5f6a08/2021021807494306
1224 $ KALLSYMS=/home/user/.debug/[kernel.kcore]/9600f316a53a0f54278885e8d9710538ec5f6a08/2021021807494306/kallsyms
1225
1226Find the VM process
1227
1228 $ ps -eLl | grep 'KVM\|PID'
1229 F S   UID     PID    PPID     LWP  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
1230 3 S 64055    1430       1    1440  1  80   0 - 1921718 -    ?        00:02:47 CPU 0/KVM
1231 3 S 64055    1430       1    1441  1  80   0 - 1921718 -    ?        00:02:41 CPU 1/KVM
1232 3 S 64055    1430       1    1442  1  80   0 - 1921718 -    ?        00:02:38 CPU 2/KVM
1233 3 S 64055    1430       1    1443  2  80   0 - 1921718 -    ?        00:03:18 CPU 3/KVM
1234
1235Start an open-ended perf record, tracing the VM process, do something on the VM, and then ctrl-C to stop.
1236TSC is not supported and tsc=0 must be specified.  That means mtc is useless, so add mtc=0.
1237However, IPC can still be determined, hence cyc=1 can be added.
1238Only kernel decoding is supported, so 'k' must be specified.
1239Intel PT traces both the host and the guest so --guest and --host need to be specified.
1240Without timestamps, --per-thread must be specified to distinguish threads.
1241
1242 $ sudo perf kvm --guest --host --guestkallsyms $KALLSYMS record --kcore -e intel_pt/tsc=0,mtc=0,cyc=1/k -p 1430 --per-thread
1243 ^C
1244 [ perf record: Woken up 1 times to write data ]
1245 [ perf record: Captured and wrote 5.829 MB ]
1246
1247perf script can be used to provide an instruction trace
1248
1249 $ perf script --guestkallsyms $KALLSYMS --insn-trace --xed -F+ipc | grep -C10 vmresume | head -21
1250       CPU 0/KVM  1440  ffffffff82133cdd __vmx_vcpu_run+0x3d ([kernel.kallsyms])                movq  0x48(%rax), %r9
1251       CPU 0/KVM  1440  ffffffff82133ce1 __vmx_vcpu_run+0x41 ([kernel.kallsyms])                movq  0x50(%rax), %r10
1252       CPU 0/KVM  1440  ffffffff82133ce5 __vmx_vcpu_run+0x45 ([kernel.kallsyms])                movq  0x58(%rax), %r11
1253       CPU 0/KVM  1440  ffffffff82133ce9 __vmx_vcpu_run+0x49 ([kernel.kallsyms])                movq  0x60(%rax), %r12
1254       CPU 0/KVM  1440  ffffffff82133ced __vmx_vcpu_run+0x4d ([kernel.kallsyms])                movq  0x68(%rax), %r13
1255       CPU 0/KVM  1440  ffffffff82133cf1 __vmx_vcpu_run+0x51 ([kernel.kallsyms])                movq  0x70(%rax), %r14
1256       CPU 0/KVM  1440  ffffffff82133cf5 __vmx_vcpu_run+0x55 ([kernel.kallsyms])                movq  0x78(%rax), %r15
1257       CPU 0/KVM  1440  ffffffff82133cf9 __vmx_vcpu_run+0x59 ([kernel.kallsyms])                movq  (%rax), %rax
1258       CPU 0/KVM  1440  ffffffff82133cfc __vmx_vcpu_run+0x5c ([kernel.kallsyms])                callq  0xffffffff82133c40
1259       CPU 0/KVM  1440  ffffffff82133c40 vmx_vmenter+0x0 ([kernel.kallsyms])            jz 0xffffffff82133c46
1260       CPU 0/KVM  1440  ffffffff82133c42 vmx_vmenter+0x2 ([kernel.kallsyms])            vmresume         IPC: 0.11 (50/445)
1261           :1440  1440  ffffffffbb678b06 native_write_msr+0x6 ([guest.kernel.kallsyms])                 nopl  %eax, (%rax,%rax,1)
1262           :1440  1440  ffffffffbb678b0b native_write_msr+0xb ([guest.kernel.kallsyms])                 retq     IPC: 0.04 (2/41)
1263           :1440  1440  ffffffffbb666646 lapic_next_deadline+0x26 ([guest.kernel.kallsyms])             data16 nop
1264           :1440  1440  ffffffffbb666648 lapic_next_deadline+0x28 ([guest.kernel.kallsyms])             xor %eax, %eax
1265           :1440  1440  ffffffffbb66664a lapic_next_deadline+0x2a ([guest.kernel.kallsyms])             popq  %rbp
1266           :1440  1440  ffffffffbb66664b lapic_next_deadline+0x2b ([guest.kernel.kallsyms])             retq     IPC: 0.16 (4/25)
1267           :1440  1440  ffffffffbb74607f clockevents_program_event+0x8f ([guest.kernel.kallsyms])               test %eax, %eax
1268           :1440  1440  ffffffffbb746081 clockevents_program_event+0x91 ([guest.kernel.kallsyms])               jz 0xffffffffbb74603c    IPC: 0.06 (2/30)
1269           :1440  1440  ffffffffbb74603c clockevents_program_event+0x4c ([guest.kernel.kallsyms])               popq  %rbx
1270           :1440  1440  ffffffffbb74603d clockevents_program_event+0x4d ([guest.kernel.kallsyms])               popq  %r12
1271
1272Example using VM Time Correlation
1273
1274Start VM
1275
1276 $ sudo virsh start kubuntu20.04
1277 Domain kubuntu20.04 started
1278
1279Mount the guest file system.  Note sshfs needs -o direct_io to enable reading of proc files.  root access is needed to read /proc/kcore.
1280
1281 $ mkdir -p vm0
1282 $ sshfs -o direct_io root@vm0:/ vm0
1283
1284Copy the guest /proc/kallsyms, /proc/modules and /proc/kcore
1285
1286 $ perf buildid-cache -v --kcore vm0/proc/kcore
1287 same kcore found in /home/user/.debug/[kernel.kcore]/cc9c55a98c5e4ec0aeda69302554aabed5cd6491/2021021312450777
1288 $ KALLSYMS=/home/user/.debug/\[kernel.kcore\]/cc9c55a98c5e4ec0aeda69302554aabed5cd6491/2021021312450777/kallsyms
1289
1290Find the VM process
1291
1292 $ ps -eLl | grep 'KVM\|PID'
1293 F S   UID     PID    PPID     LWP  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
1294 3 S 64055   16998       1   17005 13  80   0 - 1818189 -    ?        00:00:16 CPU 0/KVM
1295 3 S 64055   16998       1   17006  4  80   0 - 1818189 -    ?        00:00:05 CPU 1/KVM
1296 3 S 64055   16998       1   17007  3  80   0 - 1818189 -    ?        00:00:04 CPU 2/KVM
1297 3 S 64055   16998       1   17008  4  80   0 - 1818189 -    ?        00:00:05 CPU 3/KVM
1298
1299Start an open-ended perf record, tracing the VM process, do something on the VM, and then ctrl-C to stop.
1300IPC can be determined, hence cyc=1 can be added.
1301Only kernel decoding is supported, so 'k' must be specified.
1302Intel PT traces both the host and the guest so --guest and --host need to be specified.
1303
1304 $ sudo perf kvm --guest --host --guestkallsyms $KALLSYMS record --kcore -e intel_pt/cyc=1/k -p 16998
1305 ^C[ perf record: Woken up 1 times to write data ]
1306 [ perf record: Captured and wrote 9.041 MB perf.data.kvm ]
1307
1308Now 'perf inject' can be used to determine the VMX TCS Offset. Note, Intel PT TSC packets are
1309only 7-bytes, so the TSC Offset might differ from the actual value in the 8th byte. That will
1310have no effect i.e. the resulting timestamps will be correct anyway.
1311
1312 $ perf inject -i perf.data.kvm --vm-time-correlation=dry-run
1313 ERROR: Unknown TSC Offset for VMCS 0x1bff6a
1314 VMCS: 0x1bff6a  TSC Offset 0xffffe42722c64c41
1315 ERROR: Unknown TSC Offset for VMCS 0x1cbc08
1316 VMCS: 0x1cbc08  TSC Offset 0xffffe42722c64c41
1317 ERROR: Unknown TSC Offset for VMCS 0x1c3ce8
1318 VMCS: 0x1c3ce8  TSC Offset 0xffffe42722c64c41
1319 ERROR: Unknown TSC Offset for VMCS 0x1cbce9
1320 VMCS: 0x1cbce9  TSC Offset 0xffffe42722c64c41
1321
1322Each virtual CPU has a different Virtual Machine Control Structure (VMCS)
1323shown above with the calculated TSC Offset. For an unchanging TSC Offset
1324they should all be the same for the same virtual machine.
1325
1326Now that the TSC Offset is known, it can be provided to 'perf inject'
1327
1328 $ perf inject -i perf.data.kvm --vm-time-correlation="dry-run 0xffffe42722c64c41"
1329
1330Note the options for 'perf inject' --vm-time-correlation are:
1331
1332 [ dry-run ] [ <TSC Offset> [ : <VMCS> [ , <VMCS> ]... ]  ]...
1333
1334So it is possible to specify different TSC Offsets for different VMCS.
1335The option "dry-run" will cause the file to be processed but without updating it.
1336Note it is also possible to get a intel_pt.log file by adding option --itrace=d
1337
1338There were no errors so, do it for real
1339
1340 $ perf inject -i perf.data.kvm --vm-time-correlation=0xffffe42722c64c41 --force
1341
1342'perf script' can be used to see if there are any decoder errors
1343
1344 $ perf script -i perf.data.kvm --guestkallsyms $KALLSYMS --itrace=e-o
1345
1346There were none.
1347
1348'perf script' can be used to provide an instruction trace showing timestamps
1349
1350 $ perf script -i perf.data.kvm --guestkallsyms $KALLSYMS --insn-trace --xed -F+ipc | grep -C10 vmresume | head -21
1351       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133cdd __vmx_vcpu_run+0x3d ([kernel.kallsyms])                 movq  0x48(%rax), %r9
1352       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133ce1 __vmx_vcpu_run+0x41 ([kernel.kallsyms])                 movq  0x50(%rax), %r10
1353       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133ce5 __vmx_vcpu_run+0x45 ([kernel.kallsyms])                 movq  0x58(%rax), %r11
1354       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133ce9 __vmx_vcpu_run+0x49 ([kernel.kallsyms])                 movq  0x60(%rax), %r12
1355       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133ced __vmx_vcpu_run+0x4d ([kernel.kallsyms])                 movq  0x68(%rax), %r13
1356       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133cf1 __vmx_vcpu_run+0x51 ([kernel.kallsyms])                 movq  0x70(%rax), %r14
1357       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133cf5 __vmx_vcpu_run+0x55 ([kernel.kallsyms])                 movq  0x78(%rax), %r15
1358       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133cf9 __vmx_vcpu_run+0x59 ([kernel.kallsyms])                 movq  (%rax), %rax
1359       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133cfc __vmx_vcpu_run+0x5c ([kernel.kallsyms])                 callq  0xffffffff82133c40
1360       CPU 1/KVM 17006 [001] 11500.262865593:  ffffffff82133c40 vmx_vmenter+0x0 ([kernel.kallsyms])             jz 0xffffffff82133c46
1361       CPU 1/KVM 17006 [001] 11500.262866075:  ffffffff82133c42 vmx_vmenter+0x2 ([kernel.kallsyms])             vmresume         IPC: 0.05 (40/769)
1362          :17006 17006 [001] 11500.262869216:  ffffffff82200cb0 asm_sysvec_apic_timer_interrupt+0x0 ([guest.kernel.kallsyms])           clac
1363          :17006 17006 [001] 11500.262869216:  ffffffff82200cb3 asm_sysvec_apic_timer_interrupt+0x3 ([guest.kernel.kallsyms])           pushq  $0xffffffffffffffff
1364          :17006 17006 [001] 11500.262869216:  ffffffff82200cb5 asm_sysvec_apic_timer_interrupt+0x5 ([guest.kernel.kallsyms])           callq  0xffffffff82201160
1365          :17006 17006 [001] 11500.262869216:  ffffffff82201160 error_entry+0x0 ([guest.kernel.kallsyms])               cld
1366          :17006 17006 [001] 11500.262869216:  ffffffff82201161 error_entry+0x1 ([guest.kernel.kallsyms])               pushq  %rsi
1367          :17006 17006 [001] 11500.262869216:  ffffffff82201162 error_entry+0x2 ([guest.kernel.kallsyms])               movq  0x8(%rsp), %rsi
1368          :17006 17006 [001] 11500.262869216:  ffffffff82201167 error_entry+0x7 ([guest.kernel.kallsyms])               movq  %rdi, 0x8(%rsp)
1369          :17006 17006 [001] 11500.262869216:  ffffffff8220116c error_entry+0xc ([guest.kernel.kallsyms])               pushq  %rdx
1370          :17006 17006 [001] 11500.262869216:  ffffffff8220116d error_entry+0xd ([guest.kernel.kallsyms])               pushq  %rcx
1371          :17006 17006 [001] 11500.262869216:  ffffffff8220116e error_entry+0xe ([guest.kernel.kallsyms])               pushq  %rax
1372
1373
1374
1375SEE ALSO
1376--------
1377
1378linkperf:perf-record[1], linkperf:perf-script[1], linkperf:perf-report[1],
1379linkperf:perf-inject[1]
1380