요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
==================================
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.
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);
...
}
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.
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.
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);
[..]
}
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 실행을 계속합니다.
enabled 상태에 따라 probe 호출 여부만 달라지고 caller context는 유지됩니다.
tracepoint는 code의 중요한 위치에 둘 수 있는 lightweight hook입니다. 임의 개수의 parameter를 전달할 수 있고 prototype은 header file의 tracepoint declaration에 기술합니다.
주요 용도는 tracing과 performance accounting입니다.
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-77tracepoint에는 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);
...
}
header declaration과 한 C file의 definition, 여러 call site가 하나의 tracepoint를 구성합니다.
각 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를 안전하게 만듭니다.
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할 수 있습니다.
여러 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-151tracepoint 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를 피할 수 있습니다.
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 세 개를 제공합니다.
생성 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-180header 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는 작은 enabled 검사만 수행하고 실제 trace code는 C file wrapper에 둡니다.
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);
[..]
}
요약·해설
tracepoints.rst:1-180tracepoint는 off 상태 비용이 작은 runtime hook입니다. header declaration과 단일 definition, type-safe probe registration, synchronized removal과 enabled guard를 함께 지켜야 안전하게 사용할 수 있습니다.