← Documents Documentation/trace/tracepoints.rst GitHub 원문 ↗

Linux 6.18.37 · Tracing

Linux Kernel Tracepoint 사용법

kernel tracepoint 선언·정의·probe 등록과 안전한 제거, static-key enabled guard, TRACE_EVENT 및 header wrapper 패턴을 설명합니다.

Source pathDocumentation/trace/tracepoints.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

tracepoints.rst:1-180

tracepoint는 off 상태 비용이 작은 runtime hook입니다. header declaration과 단일 definition, type-safe probe registration, synchronized removal과 enabled guard를 함께 지켜야 안전하게 사용할 수 있습니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ==================================
2 Using the Linux Kernel Tracepoints
3 ==================================
4
5 :Author: Mathieu Desnoyers
6
7
8 This document introduces Linux Kernel Tracepoints and their use. It
9 provides examples of how to insert tracepoints in the kernel and
10 connect probe functions to them and provides some examples of probe
11 functions.
12
13
14 Purpose of tracepoints
15 ----------------------
16 A tracepoint placed in code provides a hook to call a function (probe)
17 that you can provide at runtime. A tracepoint can be "on" (a probe is
18 connected to it) or "off" (no probe is attached). When a tracepoint is
19 "off" it has no effect, except for adding a tiny time penalty
20 (checking a condition for a branch) and space penalty (adding a few
21 bytes for the function call at the end of the instrumented function
22 and adds a data structure in a separate section). When a tracepoint
23 is "on", the function you provide is called each time the tracepoint
24 is executed, in the execution context of the caller. When the function
25 provided ends its execution, it returns to the caller (continuing from
26 the tracepoint site).
27
28 You can put tracepoints at important locations in the code. They are
29 lightweight hooks that can pass an arbitrary number of parameters,
30 whose prototypes are described in a tracepoint declaration placed in a
31 header file.
32
33 They can be used for tracing and performance accounting.
34
35
36 Usage
37 -----
38 Two elements are required for tracepoints :
39
40 - A tracepoint definition, placed in a header file.
41 - The tracepoint statement, in C code.
42
43 In order to use tracepoints, you should include linux/tracepoint.h.
44
45 In include/trace/events/subsys.h::
46
47 #undef TRACE_SYSTEM
48 #define TRACE_SYSTEM subsys
49
50 #if !defined(_TRACE_SUBSYS_H) || defined(TRACE_HEADER_MULTI_READ)
51 #define _TRACE_SUBSYS_H
52
53 #include <linux/tracepoint.h>
54
55 DECLARE_TRACE(subsys_eventname,
56 TP_PROTO(int firstarg, struct task_struct *p),
57 TP_ARGS(firstarg, p));
58
59 #endif /* _TRACE_SUBSYS_H */
60
61 /* This part must be outside protection */
62 #include <trace/define_trace.h>
63
64 In subsys/file.c (where the tracing statement must be added)::
65
66 #include <trace/events/subsys.h>
67
68 #define CREATE_TRACE_POINTS
69 DEFINE_TRACE(subsys_eventname);
70
71 void somefct(void)
72 {
73 ...
74 trace_subsys_eventname_tp(arg, task);
75 ...
76 }
77
78 Where :
79 - subsys_eventname is an identifier unique to your event
80
81 - subsys is the name of your subsystem.
82 - eventname is the name of the event to trace.
83
84 - `TP_PROTO(int firstarg, struct task_struct *p)` is the prototype of the
85 function called by this tracepoint.
86
87 - `TP_ARGS(firstarg, p)` are the parameters names, same as found in the
88 prototype.
89
90 - if you use the header in multiple source files, `#define CREATE_TRACE_POINTS`
91 should appear only in one source file.
92
93 Connecting a function (probe) to a tracepoint is done by providing a
94 probe (function to call) for the specific tracepoint through
95 register_trace_subsys_eventname(). Removing a probe is done through
96 unregister_trace_subsys_eventname(); it will remove the probe.
97
98 tracepoint_synchronize_unregister() must be called before the end of
99 the module exit function to make sure there is no caller left using
100 the probe. This, and the fact that preemption is disabled around the
101 probe call, make sure that probe removal and module unload are safe.
102
103 The tracepoint mechanism supports inserting multiple instances of the
104 same tracepoint, but a single definition must be made of a given
105 tracepoint name over all the kernel to make sure no type conflict will
106 occur. Name mangling of the tracepoints is done using the prototypes
107 to make sure typing is correct. Verification of probe type correctness
108 is done at the registration site by the compiler. Tracepoints can be
109 put in inline functions, inlined static functions, and unrolled loops
110 as well as regular functions.
111
112 The naming scheme "subsys_event" is suggested here as a convention
113 intended to limit collisions. Tracepoint names are global to the
114 kernel: they are considered as being the same whether they are in the
115 core kernel image or in modules.
116
117 If the tracepoint has to be used in kernel modules, an
118 EXPORT_TRACEPOINT_SYMBOL_GPL() or EXPORT_TRACEPOINT_SYMBOL() can be
119 used to export the defined tracepoints.
120
121 If you need to do a bit of work for a tracepoint parameter, and
122 that work is only used for the tracepoint, that work can be encapsulated
123 within an if statement with the following::
124
125 if (trace_foo_bar_enabled()) {
126 int i;
127 int tot = 0;
128
129 for (i = 0; i < count; i++)
130 tot += calculate_nuggets();
131
132 trace_foo_bar_tp(tot);
133 }
134
135 All trace_<tracepoint>_tp() calls have a matching trace_<tracepoint>_enabled()
136 function defined that returns true if the tracepoint is enabled and
137 false otherwise. The trace_<tracepoint>_tp() should always be within the
138 block of the if (trace_<tracepoint>_enabled()) to prevent races between
139 the tracepoint being enabled and the check being seen.
140
141 The advantage of using the trace_<tracepoint>_enabled() is that it uses
142 the static_key of the tracepoint to allow the if statement to be implemented
143 with jump labels and avoid conditional branches.
144
145 .. note:: The convenience macro TRACE_EVENT provides an alternative way to
146 define tracepoints. Note, DECLARE_TRACE(foo) creates a function
147 "trace_foo_tp()" whereas TRACE_EVENT(foo) creates a function
148 "trace_foo()", and also exposes the tracepoint as a trace event in
149 /sys/kernel/tracing/events directory. Check http://lwn.net/Articles/379903,
150 http://lwn.net/Articles/381064 and http://lwn.net/Articles/383362
151 for a series of articles with more details.
152
153 If you require calling a tracepoint from a header file, it is not
154 recommended to call one directly or to use the trace_<tracepoint>_enabled()
155 function call, as tracepoints in header files can have side effects if a
156 header is included from a file that has CREATE_TRACE_POINTS set, as
157 well as the trace_<tracepoint>() is not that small of an inline
158 and can bloat the kernel if used by other inlined functions. Instead,
159 include tracepoint-defs.h and use tracepoint_enabled().
160
161 In a C file::
162
163 void do_trace_foo_bar_wrapper(args)
164 {
165 trace_foo_bar_tp(args); // for tracepoints created via DECLARE_TRACE
166 // or
167 trace_foo_bar(args); // for tracepoints created via TRACE_EVENT
168 }
169
170 In the header file::
171
172 DECLARE_TRACEPOINT(foo_bar);
173
174 static inline void some_inline_function()
175 {
176 [..]
177 if (tracepoint_enabled(foo_bar))
178 do_trace_foo_bar_wrapper(args);
179 [..]
180 }
181

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

tracepoint의 목적과 실행 비용

1-35

저자는 Mathieu Desnoyers입니다. 이 문서는 Linux Kernel Tracepoint의 개념과 사용법, kernel에 tracepoint를 삽입하는 방법, probe function을 연결하는 방법과 probe 예제를 소개합니다.

code에 놓인 tracepoint는 runtime에 제공하는 function, 즉 probe를 호출할 수 있는 hook입니다. probe가 연결되면 tracepoint는 on이고 연결된 probe가 없으면 off입니다.

off 상태에서는 branch condition을 확인하는 아주 작은 시간 비용, instrumented function 끝의 function call을 위한 몇 byte와 별도 section의 data structure에 필요한 공간 비용만 생깁니다.

on 상태에서는 tracepoint가 실행될 때마다 caller의 execution context에서 연결된 function을 호출합니다. probe가 끝나면 tracepoint site 다음 위치로 돌아가 caller 실행을 계속합니다.

tracepoint 실행 경로
Caller reaches tracepointCheck enabled state
OffContinue with tiny branch cost
OnCall probe in caller context
Probe returnsContinue after tracepoint site

enabled 상태에 따라 probe 호출 여부만 달라지고 caller context는 유지됩니다.

tracepoint는 code의 중요한 위치에 둘 수 있는 lightweight hook입니다. 임의 개수의 parameter를 전달할 수 있고 prototype은 header file의 tracepoint declaration에 기술합니다.

주요 용도는 tracing과 performance accounting입니다.

tracepoint 상태
상태동작
offcondition 확인과 작은 code/data 공간 비용
oncaller context에서 probe를 호출하고 복귀

probe 연결 상태에 따른 동작과 비용입니다.

==================================
Using the Linux Kernel Tracepoints
==================================

:Author: Mathieu Desnoyers


This document introduces Linux Kernel Tracepoints and their use. It
provides examples of how to insert tracepoints in the kernel and
connect probe functions to them and provides some examples of probe
functions.


Purpose of tracepoints
----------------------
A tracepoint placed in code provides a hook to call a function (probe)
that you can provide at runtime. A tracepoint can be "on" (a probe is
connected to it) or "off" (no probe is attached). When a tracepoint is
"off" it has no effect, except for adding a tiny time penalty
(checking a condition for a branch) and space penalty (adding a few
bytes for the function call at the end of the instrumented function
and adds a data structure in a separate section).  When a tracepoint
is "on", the function you provide is called each time the tracepoint
is executed, in the execution context of the caller. When the function
provided ends its execution, it returns to the caller (continuing from
the tracepoint site).

You can put tracepoints at important locations in the code. They are
lightweight hooks that can pass an arbitrary number of parameters,
whose prototypes are described in a tracepoint declaration placed in a
header file.

They can be used for tracing and performance accounting.

tracepoint 선언과 C statement

36-77

tracepoint에는 header file의 tracepoint definition과 C code의 tracepoint statement 두 요소가 필요합니다. 사용하려면 `linux/tracepoint.h`를 include해야 합니다.

`include/trace/events/subsys.h` 예제는 `TRACE_SYSTEM`을 `subsys`로 정하고 multi-read가 가능한 header guard 안에서 `DECLARE_TRACE`로 event prototype과 argument 이름을 선언합니다. `trace/define_trace.h` include는 header protection 밖에 있어야 합니다.

	#undef TRACE_SYSTEM
	#define TRACE_SYSTEM subsys

	#if !defined(_TRACE_SUBSYS_H) || defined(TRACE_HEADER_MULTI_READ)
	#define _TRACE_SUBSYS_H

	#include <linux/tracepoint.h>

	DECLARE_TRACE(subsys_eventname,
		TP_PROTO(int firstarg, struct task_struct *p),
		TP_ARGS(firstarg, p));

	#endif /* _TRACE_SUBSYS_H */

	/* This part must be outside protection */
	#include <trace/define_trace.h>

trace statement를 넣는 `subsys/file.c`에서는 event header를 include하고 한 source file에서만 `CREATE_TRACE_POINTS`를 정의한 뒤 `DEFINE_TRACE`로 storage를 만듭니다. 실제 instrumented function은 `trace_subsys_eventname_tp(arg, task)`를 호출합니다.

	#include <trace/events/subsys.h>

	#define CREATE_TRACE_POINTS
	DEFINE_TRACE(subsys_eventname);

	void somefct(void)
	{
		...
		trace_subsys_eventname_tp(arg, task);
		...
	}
tracepoint 정의 구성
subsys.hDECLARE_TRACE + TP_PROTO + TP_ARGS
one C fileCREATE_TRACE_POINTS + DEFINE_TRACE
instrumented codetrace_subsys_eventname_tp(args)

header declaration과 한 C file의 definition, 여러 call site가 하나의 tracepoint를 구성합니다.

필수 요소
요소역할
linux/tracepoint.htracepoint API 선언
DECLARE_TRACE이름, prototype, argument 선언
trace/define_trace.hheader guard 밖에서 definition 생성 지원
CREATE_TRACE_POINTS한 source file에서 tracepoint 생성
DEFINE_TRACEtracepoint definition

각 macro와 include 위치의 역할을 정리합니다.

Usage
-----
Two elements are required for tracepoints :

- A tracepoint definition, placed in a header file.
- The tracepoint statement, in C code.

In order to use tracepoints, you should include linux/tracepoint.h.

In include/trace/events/subsys.h::

	#undef TRACE_SYSTEM
	#define TRACE_SYSTEM subsys

	#if !defined(_TRACE_SUBSYS_H) || defined(TRACE_HEADER_MULTI_READ)
	#define _TRACE_SUBSYS_H

	#include <linux/tracepoint.h>

	DECLARE_TRACE(subsys_eventname,
		TP_PROTO(int firstarg, struct task_struct *p),
		TP_ARGS(firstarg, p));

	#endif /* _TRACE_SUBSYS_H */

	/* This part must be outside protection */
	#include <trace/define_trace.h>

In subsys/file.c (where the tracing statement must be added)::

	#include <trace/events/subsys.h>

	#define CREATE_TRACE_POINTS
	DEFINE_TRACE(subsys_eventname);

	void somefct(void)
	{
		...
		trace_subsys_eventname_tp(arg, task);
		...
	}

이름·type 검증과 probe 수명

78-120

`subsys_eventname`은 event의 kernel-wide unique identifier입니다. `subsys`는 subsystem 이름이고 `eventname`은 추적할 event 이름입니다.

`TP_PROTO(int firstarg, struct task_struct *p)`는 tracepoint가 호출할 function prototype이고, `TP_ARGS(firstarg, p)`는 prototype과 같은 parameter 이름 목록입니다. header를 여러 source file에서 쓸 때 `CREATE_TRACE_POINTS`는 오직 한 file에만 있어야 합니다.

특정 tracepoint에 probe를 연결하려면 `register_trace_subsys_eventname()`에 호출할 function을 전달합니다. 제거는 `unregister_trace_subsys_eventname()`으로 합니다.

module exit function이 끝나기 전에 `tracepoint_synchronize_unregister()`를 호출해 probe를 사용 중인 caller가 남지 않았음을 보장해야 합니다. probe 호출 주위에서 preemption이 disabled되는 특성과 함께 probe 제거와 module unload를 안전하게 만듭니다.

probe 등록과 제거
register_trace_*()Probe visible
Tracepoint executionCall probe with preemption disabled
unregister_trace_*()Remove registration
tracepoint_synchronize_unregister()Wait for remaining callers
Module unloadSafe exit

registration부터 grace synchronization과 module unload까지의 수명입니다.

같은 tracepoint의 call instance는 여러 곳에 삽입할 수 있지만 kernel 전체에서 같은 tracepoint 이름의 definition은 하나만 있어야 type conflict를 막을 수 있습니다. prototype을 이용한 name mangling으로 type을 맞추고 compiler가 registration site에서 probe type correctness를 검사합니다.

tracepoint는 regular function뿐 아니라 inline function, inlined static function, unrolled loop에도 둘 수 있습니다.

이름 충돌을 줄이기 위한 convention으로 `subsys_event` 형식을 권장합니다. tracepoint 이름은 core kernel image와 module 위치에 관계없이 kernel 전체의 global namespace를 사용합니다.

kernel module에서 tracepoint를 사용해야 하면 `EXPORT_TRACEPOINT_SYMBOL_GPL()` 또는 `EXPORT_TRACEPOINT_SYMBOL()`로 정의된 tracepoint를 export할 수 있습니다.

tracepoint naming과 type 규칙
규칙이유
한 이름당 definition 하나type conflict 방지
subsys_event namingglobal namespace collision 완화
compiler registration checkprobe prototype 검증
EXPORT_TRACEPOINT_SYMBOL[_GPL]module에서 symbol 사용

여러 call site와 module에서 하나의 ABI를 유지합니다.

Where :
  - subsys_eventname is an identifier unique to your event

    - subsys is the name of your subsystem.
    - eventname is the name of the event to trace.

  - `TP_PROTO(int firstarg, struct task_struct *p)` is the prototype of the
    function called by this tracepoint.

  - `TP_ARGS(firstarg, p)` are the parameters names, same as found in the
    prototype.

  - if you use the header in multiple source files, `#define CREATE_TRACE_POINTS`
    should appear only in one source file.

Connecting a function (probe) to a tracepoint is done by providing a
probe (function to call) for the specific tracepoint through
register_trace_subsys_eventname().  Removing a probe is done through
unregister_trace_subsys_eventname(); it will remove the probe.

tracepoint_synchronize_unregister() must be called before the end of
the module exit function to make sure there is no caller left using
the probe. This, and the fact that preemption is disabled around the
probe call, make sure that probe removal and module unload are safe.

The tracepoint mechanism supports inserting multiple instances of the
same tracepoint, but a single definition must be made of a given
tracepoint name over all the kernel to make sure no type conflict will
occur. Name mangling of the tracepoints is done using the prototypes
to make sure typing is correct. Verification of probe type correctness
is done at the registration site by the compiler. Tracepoints can be
put in inline functions, inlined static functions, and unrolled loops
as well as regular functions.

The naming scheme "subsys_event" is suggested here as a convention
intended to limit collisions. Tracepoint names are global to the
kernel: they are considered as being the same whether they are in the
core kernel image or in modules.

If the tracepoint has to be used in kernel modules, an
EXPORT_TRACEPOINT_SYMBOL_GPL() or EXPORT_TRACEPOINT_SYMBOL() can be
used to export the defined tracepoints.

enabled guard와 TRACE_EVENT 대안

121-151

tracepoint parameter를 만들기 위한 추가 작업이 오직 tracepoint가 켜졌을 때만 필요하다면 `trace_foo_bar_enabled()` guard 안에 넣을 수 있습니다. 예제는 여러 값을 계산해 합한 뒤 tracepoint에 전달합니다.

	if (trace_foo_bar_enabled()) {
		int i;
		int tot = 0;

		for (i = 0; i < count; i++)
			tot += calculate_nuggets();

		trace_foo_bar_tp(tot);
	}

모든 `trace_<tracepoint>_tp()` call에는 tracepoint 활성 상태를 반환하는 `trace_<tracepoint>_enabled()` function이 대응됩니다. enable 상태 확인과 tracepoint 호출 사이 race를 막기 위해 call은 항상 enabled guard block 안에 있어야 합니다.

enabled function은 tracepoint의 `static_key`를 사용하므로 compiler가 if statement를 jump label로 구현해 일반 conditional branch를 피할 수 있습니다.

비싼 parameter 계산 guard
trace_foo_bar_enabled()static_key / jump label
falseSkip calculation
truecalculate_nuggets()
trace_foo_bar_tp(tot)Emit probe call

tracepoint가 꺼졌을 때 전용 계산을 건너뜁니다.

편의 macro인 `TRACE_EVENT`는 tracepoint를 정의하는 다른 방법입니다. `DECLARE_TRACE(foo)`는 `trace_foo_tp()` function을 만들지만 `TRACE_EVENT(foo)`는 `trace_foo()`를 만들고 `/sys/kernel/tracing/events`에 trace event로도 노출합니다. 원문은 추가 설명을 위한 LWN article URL 세 개를 제공합니다.

DECLARE_TRACE와 TRACE_EVENT
방식호출 functiontracefs event
DECLARE_TRACE(foo)trace_foo_tp()자동 노출 아님
TRACE_EVENT(foo)trace_foo()/sys/kernel/tracing/events에 노출

생성 function 이름과 event tracing 노출 여부가 다릅니다.

If you need to do a bit of work for a tracepoint parameter, and
that work is only used for the tracepoint, that work can be encapsulated
within an if statement with the following::

	if (trace_foo_bar_enabled()) {
		int i;
		int tot = 0;

		for (i = 0; i < count; i++)
			tot += calculate_nuggets();

		trace_foo_bar_tp(tot);
	}

All trace_<tracepoint>_tp() calls have a matching trace_<tracepoint>_enabled()
function defined that returns true if the tracepoint is enabled and
false otherwise. The trace_<tracepoint>_tp() should always be within the
block of the if (trace_<tracepoint>_enabled()) to prevent races between
the tracepoint being enabled and the check being seen.

The advantage of using the trace_<tracepoint>_enabled() is that it uses
the static_key of the tracepoint to allow the if statement to be implemented
with jump labels and avoid conditional branches.

.. note:: The convenience macro TRACE_EVENT provides an alternative way to
      define tracepoints. Note, DECLARE_TRACE(foo) creates a function
      "trace_foo_tp()" whereas TRACE_EVENT(foo) creates a function
      "trace_foo()", and also exposes the tracepoint as a trace event in
      /sys/kernel/tracing/events directory.  Check http://lwn.net/Articles/379903,
      http://lwn.net/Articles/381064 and http://lwn.net/Articles/383362
      for a series of articles with more details.

header에서 안전하게 호출하는 wrapper

152-180

header file에서 tracepoint를 호출해야 할 때 직접 call하거나 `trace_<tracepoint>_enabled()`를 쓰는 것은 권장하지 않습니다. `CREATE_TRACE_POINTS`가 설정된 file에서 header를 include하면 side effect가 생길 수 있고, `trace_<tracepoint>()` inline은 작지 않아 다른 inline function에서 사용하면 kernel code size를 부풀릴 수 있습니다.

대신 header에는 `tracepoint-defs.h`를 include하고 `tracepoint_enabled()`를 사용합니다. 실제 trace call은 C file의 non-inline wrapper에 둡니다.

C file wrapper는 `DECLARE_TRACE`로 만든 tracepoint면 `trace_foo_bar_tp(args)`를, `TRACE_EVENT`로 만든 tracepoint면 `trace_foo_bar(args)`를 호출합니다.

	void do_trace_foo_bar_wrapper(args)
	{
		trace_foo_bar_tp(args); // for tracepoints created via DECLARE_TRACE
					//   or
		trace_foo_bar(args);    // for tracepoints created via TRACE_EVENT
	}

header에서는 `DECLARE_TRACEPOINT(foo_bar)`로 최소 declaration만 두고 inline function 안에서 `tracepoint_enabled(foo_bar)`를 검사한 뒤 wrapper를 호출합니다.

	DECLARE_TRACEPOINT(foo_bar);

	static inline void some_inline_function()
	{
		[..]
		if (tracepoint_enabled(foo_bar))
			do_trace_foo_bar_wrapper(args);
		[..]
	}
header-safe tracepoint 호출
Header inline functiontracepoint_enabled(foo_bar)
do_trace_foo_bar_wrapper(args)Non-inline C function
DECLARE_TRACEtrace_foo_bar_tp(args)
TRACE_EVENTtrace_foo_bar(args)

header는 작은 enabled 검사만 수행하고 실제 trace code는 C file wrapper에 둡니다.

header 호출 원칙
위치사용 API
HeaderDECLARE_TRACEPOINT + tracepoint_enabled
C filewrapper + trace_* call

side effect와 inline code bloat를 피하는 배치입니다.


If you require calling a tracepoint from a header file, it is not
recommended to call one directly or to use the trace_<tracepoint>_enabled()
function call, as tracepoints in header files can have side effects if a
header is included from a file that has CREATE_TRACE_POINTS set, as
well as the trace_<tracepoint>() is not that small of an inline
and can bloat the kernel if used by other inlined functions. Instead,
include tracepoint-defs.h and use tracepoint_enabled().

In a C file::

	void do_trace_foo_bar_wrapper(args)
	{
		trace_foo_bar_tp(args); // for tracepoints created via DECLARE_TRACE
					//   or
		trace_foo_bar(args);    // for tracepoints created via TRACE_EVENT
	}

In the header file::

	DECLARE_TRACEPOINT(foo_bar);

	static inline void some_inline_function()
	{
		[..]
		if (tracepoint_enabled(foo_bar))
			do_trace_foo_bar_wrapper(args);
		[..]
	}