xref: /qemu/docs/devel/tracing.rst (revision e50caf4a5c0cb8d478e0c80b11d5a8a9306a89fd)
1=======
2Tracing
3=======
4
5Introduction
6============
7
8This document describes the tracing infrastructure in QEMU and how to use it
9for debugging, profiling, and observing execution.
10
11Quickstart
12==========
13
141. Build with the 'simple' trace backend::
15
16    ./configure --enable-trace-backends=simple
17    make
18
192. Create a file with the events you want to trace::
20
21    echo memory_region_ops_read >/tmp/events
22
233. Run the virtual machine to produce a trace file::
24
25    qemu --trace events=/tmp/events ... # your normal QEMU invocation
26
274. Pretty-print the binary trace file::
28
29    ./scripts/simpletrace.py trace-events-all trace-* # Override * with QEMU <pid>
30
31Trace events
32============
33
34Sub-directory setup
35-------------------
36
37Each directory in the source tree can declare a set of static trace events
38in a local "trace-events" file. All directories which contain "trace-events"
39files must be listed in the "trace-events-subdirs" make variable in the top
40level Makefile.objs. During build, the "trace-events" file in each listed
41subdirectory will be processed by the "tracetool" script to generate code for
42the trace events.
43
44The individual "trace-events" files are merged into a "trace-events-all" file,
45which is also installed into "/usr/share/qemu" with the name "trace-events".
46This merged file is to be used by the "simpletrace.py" script to later analyse
47traces in the simpletrace data format.
48
49In the sub-directory the following files will be automatically generated
50
51 - trace.c - the trace event state declarations
52 - trace.h - the trace event enums and probe functions
53 - trace-dtrace.h - DTrace event probe specification
54 - trace-dtrace.dtrace - DTrace event probe helper declaration
55 - trace-dtrace.o - binary DTrace provider (generated by dtrace)
56 - trace-ust.h - UST event probe helper declarations
57
58Source files in the sub-directory should #include the local 'trace.h' file,
59without any sub-directory path prefix. eg io/channel-buffer.c would do::
60
61  #include "trace.h"
62
63To access the 'io/trace.h' file. While it is possible to include a trace.h
64file from outside a source file's own sub-directory, this is discouraged in
65general. It is strongly preferred that all events be declared directly in
66the sub-directory that uses them. The only exception is where there are some
67shared trace events defined in the top level directory trace-events file.
68The top level directory generates trace files with a filename prefix of
69"trace/trace-root" instead of just "trace". This is to avoid ambiguity between
70a trace.h in the current directory, vs the top level directory.
71
72Using trace events
73------------------
74
75Trace events are invoked directly from source code like this::
76
77    #include "trace.h"  /* needed for trace event prototype */
78
79    void *qemu_vmalloc(size_t size)
80    {
81        void *ptr;
82        size_t align = QEMU_VMALLOC_ALIGN;
83
84        if (size < align) {
85            align = getpagesize();
86        }
87        ptr = qemu_memalign(align, size);
88        trace_qemu_vmalloc(size, ptr);
89        return ptr;
90    }
91
92Declaring trace events
93----------------------
94
95The "tracetool" script produces the trace.h header file which is included by
96every source file that uses trace events.  Since many source files include
97trace.h, it uses a minimum of types and other header files included to keep the
98namespace clean and compile times and dependencies down.
99
100Trace events should use types as follows:
101
102 * Use stdint.h types for fixed-size types.  Most offsets and guest memory
103   addresses are best represented with uint32_t or uint64_t.  Use fixed-size
104   types over primitive types whose size may change depending on the host
105   (32-bit versus 64-bit) so trace events don't truncate values or break
106   the build.
107
108 * Use void * for pointers to structs or for arrays.  The trace.h header
109   cannot include all user-defined struct declarations and it is therefore
110   necessary to use void * for pointers to structs.
111
112 * For everything else, use primitive scalar types (char, int, long) with the
113   appropriate signedness.
114
115 * Avoid floating point types (float and double) because SystemTap does not
116   support them.  In most cases it is possible to round to an integer type
117   instead.  This may require scaling the value first by multiplying it by 1000
118   or the like when digits after the decimal point need to be preserved.
119
120Format strings should reflect the types defined in the trace event.  Take
121special care to use PRId64 and PRIu64 for int64_t and uint64_t types,
122respectively.  This ensures portability between 32- and 64-bit platforms.
123Format strings must not end with a newline character.  It is the responsibility
124of backends to adapt line ending for proper logging.
125
126Each event declaration will start with the event name, then its arguments,
127finally a format string for pretty-printing. For example::
128
129    qemu_vmalloc(size_t size, void *ptr) "size %zu ptr %p"
130    qemu_vfree(void *ptr) "ptr %p"
131
132
133Hints for adding new trace events
134---------------------------------
135
1361. Trace state changes in the code.  Interesting points in the code usually
137   involve a state change like starting, stopping, allocating, freeing.  State
138   changes are good trace events because they can be used to understand the
139   execution of the system.
140
1412. Trace guest operations.  Guest I/O accesses like reading device registers
142   are good trace events because they can be used to understand guest
143   interactions.
144
1453. Use correlator fields so the context of an individual line of trace output
146   can be understood.  For example, trace the pointer returned by malloc and
147   used as an argument to free.  This way mallocs and frees can be matched up.
148   Trace events with no context are not very useful.
149
1504. Name trace events after their function.  If there are multiple trace events
151   in one function, append a unique distinguisher at the end of the name.
152
153Generic interface and monitor commands
154======================================
155
156You can programmatically query and control the state of trace events through a
157backend-agnostic interface provided by the header "trace/control.h".
158
159Note that some of the backends do not provide an implementation for some parts
160of this interface, in which case QEMU will just print a warning (please refer to
161header "trace/control.h" to see which routines are backend-dependent).
162
163The state of events can also be queried and modified through monitor commands:
164
165* ``info trace-events``
166  View available trace events and their state.  State 1 means enabled, state 0
167  means disabled.
168
169* ``trace-event NAME on|off``
170  Enable/disable a given trace event or a group of events (using wildcards).
171
172The "--trace events=<file>" command line argument can be used to enable the
173events listed in <file> from the very beginning of the program. This file must
174contain one event name per line.
175
176If a line in the "--trace events=<file>" file begins with a '-', the trace event
177will be disabled instead of enabled.  This is useful when a wildcard was used
178to enable an entire family of events but one noisy event needs to be disabled.
179
180Wildcard matching is supported in both the monitor command "trace-event" and the
181events list file. That means you can enable/disable the events having a common
182prefix in a batch. For example, virtio-blk trace events could be enabled using
183the following monitor command::
184
185    trace-event virtio_blk_* on
186
187Trace backends
188==============
189
190The "tracetool" script automates tedious trace event code generation and also
191keeps the trace event declarations independent of the trace backend.  The trace
192events are not tightly coupled to a specific trace backend, such as LTTng or
193SystemTap.  Support for trace backends can be added by extending the "tracetool"
194script.
195
196The trace backends are chosen at configure time::
197
198    ./configure --enable-trace-backends=simple
199
200For a list of supported trace backends, try ./configure --help or see below.
201If multiple backends are enabled, the trace is sent to them all.
202
203If no backends are explicitly selected, configure will default to the
204"log" backend.
205
206The following subsections describe the supported trace backends.
207
208Nop
209---
210
211The "nop" backend generates empty trace event functions so that the compiler
212can optimize out trace events completely.  This imposes no performance
213penalty.
214
215Note that regardless of the selected trace backend, events with the "disable"
216property will be generated with the "nop" backend.
217
218Log
219---
220
221The "log" backend sends trace events directly to standard error.  This
222effectively turns trace events into debug printfs.
223
224This is the simplest backend and can be used together with existing code that
225uses DPRINTF().
226
227Simpletrace
228-----------
229
230The "simple" backend supports common use cases and comes as part of the QEMU
231source tree.  It may not be as powerful as platform-specific or third-party
232trace backends but it is portable.  This is the recommended trace backend
233unless you have specific needs for more advanced backends.
234
235Monitor commands
236~~~~~~~~~~~~~~~~
237
238* ``trace-file on|off|flush|set <path>``
239  Enable/disable/flush the trace file or set the trace file name.
240
241Analyzing trace files
242~~~~~~~~~~~~~~~~~~~~~
243
244The "simple" backend produces binary trace files that can be formatted with the
245simpletrace.py script.  The script takes the "trace-events-all" file and the
246binary trace::
247
248    ./scripts/simpletrace.py trace-events-all trace-12345
249
250You must ensure that the same "trace-events-all" file was used to build QEMU,
251otherwise trace event declarations may have changed and output will not be
252consistent.
253
254Ftrace
255------
256
257The "ftrace" backend writes trace data to ftrace marker. This effectively
258sends trace events to ftrace ring buffer, and you can compare qemu trace
259data and kernel(especially kvm.ko when using KVM) trace data.
260
261if you use KVM, enable kvm events in ftrace::
262
263   # echo 1 > /sys/kernel/debug/tracing/events/kvm/enable
264
265After running qemu by root user, you can get the trace::
266
267   # cat /sys/kernel/debug/tracing/trace
268
269Restriction: "ftrace" backend is restricted to Linux only.
270
271Syslog
272------
273
274The "syslog" backend sends trace events using the POSIX syslog API. The log
275is opened specifying the LOG_DAEMON facility and LOG_PID option (so events
276are tagged with the pid of the particular QEMU process that generated
277them). All events are logged at LOG_INFO level.
278
279NOTE: syslog may squash duplicate consecutive trace events and apply rate
280      limiting.
281
282Restriction: "syslog" backend is restricted to POSIX compliant OS.
283
284LTTng Userspace Tracer
285----------------------
286
287The "ust" backend uses the LTTng Userspace Tracer library.  There are no
288monitor commands built into QEMU, instead UST utilities should be used to list,
289enable/disable, and dump traces.
290
291Package lttng-tools is required for userspace tracing. You must ensure that the
292current user belongs to the "tracing" group, or manually launch the
293lttng-sessiond daemon for the current user prior to running any instance of
294QEMU.
295
296While running an instrumented QEMU, LTTng should be able to list all available
297events::
298
299    lttng list -u
300
301Create tracing session::
302
303    lttng create mysession
304
305Enable events::
306
307    lttng enable-event qemu:g_malloc -u
308
309Where the events can either be a comma-separated list of events, or "-a" to
310enable all tracepoint events. Start and stop tracing as needed::
311
312    lttng start
313    lttng stop
314
315View the trace::
316
317    lttng view
318
319Destroy tracing session::
320
321    lttng destroy
322
323Babeltrace can be used at any later time to view the trace::
324
325    babeltrace $HOME/lttng-traces/mysession-<date>-<time>
326
327SystemTap
328---------
329
330The "dtrace" backend uses DTrace sdt probes but has only been tested with
331SystemTap.  When SystemTap support is detected a .stp file with wrapper probes
332is generated to make use in scripts more convenient.  This step can also be
333performed manually after a build in order to change the binary name in the .stp
334probes::
335
336    scripts/tracetool.py --backends=dtrace --format=stap \
337                         --binary path/to/qemu-binary \
338                         --target-type system \
339                         --target-name x86_64 \
340                         --group=all \
341                         trace-events-all \
342                         qemu.stp
343
344To facilitate simple usage of systemtap where there merely needs to be printf
345logging of certain probes, a helper script "qemu-trace-stap" is provided.
346Consult its manual page for guidance on its usage.
347
348Trace event properties
349======================
350
351Each event in the "trace-events-all" file can be prefixed with a space-separated
352list of zero or more of the following event properties.
353
354"disable"
355---------
356
357If a specific trace event is going to be invoked a huge number of times, this
358might have a noticeable performance impact even when the event is
359programmatically disabled.
360
361In this case you should declare such event with the "disable" property. This
362will effectively disable the event at compile time (by using the "nop" backend),
363thus having no performance impact at all on regular builds (i.e., unless you
364edit the "trace-events-all" file).
365
366In addition, there might be cases where relatively complex computations must be
367performed to generate values that are only used as arguments for a trace
368function. In these cases you can use 'trace_event_get_state_backends()' to
369guard such computations, so they are skipped if the event has been either
370compile-time disabled or run-time disabled. If the event is compile-time
371disabled, this check will have no performance impact.
372
373::
374
375    #include "trace.h"  /* needed for trace event prototype */
376
377    void *qemu_vmalloc(size_t size)
378    {
379        void *ptr;
380        size_t align = QEMU_VMALLOC_ALIGN;
381
382        if (size < align) {
383            align = getpagesize();
384        }
385        ptr = qemu_memalign(align, size);
386        if (trace_event_get_state_backends(TRACE_QEMU_VMALLOC)) {
387            void *complex;
388            /* some complex computations to produce the 'complex' value */
389            trace_qemu_vmalloc(size, ptr, complex);
390        }
391        return ptr;
392    }
393
394"tcg"
395-----
396
397Guest code generated by TCG can be traced by defining an event with the "tcg"
398event property. Internally, this property generates two events:
399"<eventname>_trans" to trace the event at translation time, and
400"<eventname>_exec" to trace the event at execution time.
401
402Instead of using these two events, you should instead use the function
403"trace_<eventname>_tcg" during translation (TCG code generation). This function
404will automatically call "trace_<eventname>_trans", and will generate the
405necessary TCG code to call "trace_<eventname>_exec" during guest code execution.
406
407Events with the "tcg" property can be declared in the "trace-events" file with a
408mix of native and TCG types, and "trace_<eventname>_tcg" will gracefully forward
409them to the "<eventname>_trans" and "<eventname>_exec" events. Since TCG values
410are not known at translation time, these are ignored by the "<eventname>_trans"
411event. Because of this, the entry in the "trace-events" file needs two printing
412formats (separated by a comma)::
413
414    tcg foo(uint8_t a1, TCGv_i32 a2) "a1=%d", "a1=%d a2=%d"
415
416For example::
417
418    #include "trace-tcg.h"
419
420    void some_disassembly_func (...)
421    {
422        uint8_t a1 = ...;
423        TCGv_i32 a2 = ...;
424        trace_foo_tcg(a1, a2);
425    }
426
427This will immediately call::
428
429    void trace_foo_trans(uint8_t a1);
430
431and will generate the TCG code to call::
432
433    void trace_foo(uint8_t a1, uint32_t a2);
434
435"vcpu"
436------
437
438Identifies events that trace vCPU-specific information. It implicitly adds a
439"CPUState*" argument, and extends the tracing print format to show the vCPU
440information. If used together with the "tcg" property, it adds a second
441"TCGv_env" argument that must point to the per-target global TCG register that
442points to the vCPU when guest code is executed (usually the "cpu_env" variable).
443
444The "tcg" and "vcpu" properties are currently only honored in the root
445./trace-events file.
446
447The following example events::
448
449    foo(uint32_t a) "a=%x"
450    vcpu bar(uint32_t a) "a=%x"
451    tcg vcpu baz(uint32_t a) "a=%x", "a=%x"
452
453Can be used as::
454
455    #include "trace-tcg.h"
456
457    CPUArchState *env;
458    TCGv_ptr cpu_env;
459
460    void some_disassembly_func(...)
461    {
462        /* trace emitted at this point */
463        trace_foo(0xd1);
464        /* trace emitted at this point */
465        trace_bar(env_cpu(env), 0xd2);
466        /* trace emitted at this point (env) and when guest code is executed (cpu_env) */
467        trace_baz_tcg(env_cpu(env), cpu_env, 0xd3);
468    }
469
470If the translating vCPU has address 0xc1 and code is later executed by vCPU
4710xc2, this would be an example output::
472
473    // at guest code translation
474    foo a=0xd1
475    bar cpu=0xc1 a=0xd2
476    baz_trans cpu=0xc1 a=0xd3
477    // at guest code execution
478    baz_exec cpu=0xc2 a=0xd3
479