← Documents Documentation/userspace-api/perf_ring_buffer.rst GitHub 원문 ↗

Linux 6.18.37 · 사용자 공간 API

Perf 링 버퍼

perf의 일반·AUX ring buffer 배치, 추적 모드, 생산자·소비자 접근, 메모리 순서와 snapshot 동작을 설명합니다.

Source pathDocumentation/userspace-api/perf_ring_buffer.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

perf_ring_buffer.rst:1-830

일반 perf ring buffer는 커널이 record를 생산하고 사용자 공간 perf가 소비하는 공유 메모리 큐이며, CPU·thread mapping에 따라 buffer 수와 수집 범위가 달라집니다. 정확성의 핵심은 `data_head`와 `data_tail`을 공개하는 A~D 메모리 순서이고, AUX ring buffer는 같은 관리 원리를 사용하면서 하드웨어가 trace data를 직접 기록합니다. 분석할 때는 일반 buffer의 `PERF_RECORD_AUX`, perf 파일의 `PERF_RECORD_AUXTRACE`, 실제 AUX 데이터 세 층을 구분해야 합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 ================
4 Perf ring buffer
5 ================
6
7 .. CONTENTS
8
9 1. Introduction
10
11 2. Ring buffer implementation
12 2.1 Basic algorithm
13 2.2 Ring buffer for different tracing modes
14 2.2.1 Default mode
15 2.2.2 Per-thread mode
16 2.2.3 Per-CPU mode
17 2.2.4 System wide mode
18 2.3 Accessing buffer
19 2.3.1 Producer-consumer model
20 2.3.2 Properties of the ring buffers
21 2.3.3 Writing samples into buffer
22 2.3.4 Reading samples from buffer
23 2.3.5 Memory synchronization
24
25 3. The mechanism of AUX ring buffer
26 3.1 The relationship between AUX and regular ring buffers
27 3.2 AUX events
28 3.3 Snapshot mode
29
30
31 1. Introduction
32 ===============
33
34 The ring buffer is a fundamental mechanism for data transfer. perf uses
35 ring buffers to transfer event data from kernel to user space, another
36 kind of ring buffer which is so called auxiliary (AUX) ring buffer also
37 plays an important role for hardware tracing with Intel PT, Arm
38 CoreSight, etc.
39
40 The ring buffer implementation is critical but it's also a very
41 challenging work. On the one hand, the kernel and perf tool in the user
42 space use the ring buffer to exchange data and stores data into data
43 file, thus the ring buffer needs to transfer data with high throughput;
44 on the other hand, the ring buffer management should avoid significant
45 overload to distract profiling results.
46
47 This documentation dives into the details for perf ring buffer with two
48 parts: firstly it explains the perf ring buffer implementation, then the
49 second part discusses the AUX ring buffer mechanism.
50
51 2. Ring buffer implementation
52 =============================
53
54 2.1 Basic algorithm
55 -------------------
56
57 That said, a typical ring buffer is managed by a head pointer and a tail
58 pointer; the head pointer is manipulated by a writer and the tail
59 pointer is updated by a reader respectively.
60
61 ::
62
63 +---------------------------+
64 | | |***|***|***| | |
65 +---------------------------+
66 `-> Tail `-> Head
67
68 * : the data is filled by the writer.
69
70 Figure 1. Ring buffer
71
72 Perf uses the same way to manage its ring buffer. In the implementation
73 there are two key data structures held together in a set of consecutive
74 pages, the control structure and then the ring buffer itself. The page
75 with the control structure in is known as the "user page". Being held
76 in continuous virtual addresses simplifies locating the ring buffer
77 address, it is in the pages after the page with the user page.
78
79 The control structure is named as ``perf_event_mmap_page``, it contains a
80 head pointer ``data_head`` and a tail pointer ``data_tail``. When the
81 kernel starts to fill records into the ring buffer, it updates the head
82 pointer to reserve the memory so later it can safely store events into
83 the buffer. On the other side, when the user page is a writable mapping,
84 the perf tool has the permission to update the tail pointer after consuming
85 data from the ring buffer. Yet another case is for the user page's
86 read-only mapping, which is to be addressed in the section
87 :ref:`writing_samples_into_buffer`.
88
89 ::
90
91 user page ring buffer
92 +---------+---------+ +---------------------------------------+
93 |data_head|data_tail|...| | |***|***|***|***|***| | | |
94 +---------+---------+ +---------------------------------------+
95 ` `----------------^ ^
96 `----------------------------------------------|
97
98 * : the data is filled by the writer.
99
100 Figure 2. Perf ring buffer
101
102 When using the ``perf record`` tool, we can specify the ring buffer size
103 with option ``-m`` or ``--mmap-pages=``, the given size will be rounded up
104 to a power of two that is a multiple of a page size. Though the kernel
105 allocates at once for all memory pages, it's deferred to map the pages
106 to VMA area until the perf tool accesses the buffer from the user space.
107 In other words, at the first time accesses the buffer's page from user
108 space in the perf tool, a data abort exception for page fault is taken
109 and the kernel uses this occasion to map the page into process VMA
110 (see ``perf_mmap_fault()``), thus the perf tool can continue to access
111 the page after returning from the exception.
112
113 2.2 Ring buffer for different tracing modes
114 -------------------------------------------
115
116 The perf profiles programs with different modes: default mode, per thread
117 mode, per cpu mode, and system wide mode. This section describes these
118 modes and how the ring buffer meets requirements for them. At last we
119 will review the race conditions caused by these modes.
120
121 2.2.1 Default mode
122 ^^^^^^^^^^^^^^^^^^
123
124 Usually we execute ``perf record`` command followed by a profiling program
125 name, like below command::
126
127 perf record test_program
128
129 This command doesn't specify any options for CPU and thread modes, the
130 perf tool applies the default mode on the perf event. It maps all the
131 CPUs in the system and the profiled program's PID on the perf event, and
132 it enables inheritance mode on the event so that child tasks inherits
133 the events. As a result, the perf event is attributed as::
134
135 evsel::cpus::map[] = { 0 .. _SC_NPROCESSORS_ONLN-1 }
136 evsel::threads::map[] = { pid }
137 evsel::attr::inherit = 1
138
139 These attributions finally will be reflected on the deployment of ring
140 buffers. As shown below, the perf tool allocates individual ring buffer
141 for each CPU, but it only enables events for the profiled program rather
142 than for all threads in the system. The *T1* thread represents the
143 thread context of the 'test_program', whereas *T2* and *T3* are irrelevant
144 threads in the system. The perf samples are exclusively collected for
145 the *T1* thread and stored in the ring buffer associated with the CPU on
146 which the *T1* thread is running.
147
148 ::
149
150 T1 T2 T1
151 +----+ +-----------+ +----+
152 CPU0 |xxxx| |xxxxxxxxxxx| |xxxx|
153 +----+--------------+-----------+----------+----+-------->
154 | |
155 v v
156 +-----------------------------------------------------+
157 | Ring buffer 0 |
158 +-----------------------------------------------------+
159
160 T1
161 +-----+
162 CPU1 |xxxxx|
163 -----+-----+--------------------------------------------->
164 |
165 v
166 +-----------------------------------------------------+
167 | Ring buffer 1 |
168 +-----------------------------------------------------+
169
170 T1 T3
171 +----+ +-------+
172 CPU2 |xxxx| |xxxxxxx|
173 --------------------------+----+--------+-------+-------->
174 |
175 v
176 +-----------------------------------------------------+
177 | Ring buffer 2 |
178 +-----------------------------------------------------+
179
180 T1
181 +--------------+
182 CPU3 |xxxxxxxxxxxxxx|
183 -----------+--------------+------------------------------>
184 |
185 v
186 +-----------------------------------------------------+
187 | Ring buffer 3 |
188 +-----------------------------------------------------+
189
190 T1: Thread 1; T2: Thread 2; T3: Thread 3
191 x: Thread is in running state
192
193 Figure 3. Ring buffer for default mode
194
195 2.2.2 Per-thread mode
196 ^^^^^^^^^^^^^^^^^^^^^
197
198 By specifying option ``--per-thread`` in perf command, e.g.
199
200 ::
201
202 perf record --per-thread test_program
203
204 The perf event doesn't map to any CPUs and is only bound to the
205 profiled process, thus, the perf event's attributions are::
206
207 evsel::cpus::map[0] = { -1 }
208 evsel::threads::map[] = { pid }
209 evsel::attr::inherit = 0
210
211 In this mode, a single ring buffer is allocated for the profiled thread;
212 if the thread is scheduled on a CPU, the events on that CPU will be
213 enabled; and if the thread is scheduled out from the CPU, the events on
214 the CPU will be disabled. When the thread is migrated from one CPU to
215 another, the events are to be disabled on the previous CPU and enabled
216 on the next CPU correspondingly.
217
218 ::
219
220 T1 T2 T1
221 +----+ +-----------+ +----+
222 CPU0 |xxxx| |xxxxxxxxxxx| |xxxx|
223 +----+--------------+-----------+----------+----+-------->
224 | |
225 | T1 |
226 | +-----+ |
227 CPU1 | |xxxxx| |
228 --|--+-----+----------------------------------|---------->
229 | | |
230 | | T1 T3 |
231 | | +----+ +---+ |
232 CPU2 | | |xxxx| |xxx| |
233 --|-----|-----------------+----+--------+---+-|---------->
234 | | | |
235 | | T1 | |
236 | | +--------------+ | |
237 CPU3 | | |xxxxxxxxxxxxxx| | |
238 --|-----|--+--------------+-|-----------------|---------->
239 | | | | |
240 v v v v v
241 +-----------------------------------------------------+
242 | Ring buffer |
243 +-----------------------------------------------------+
244
245 T1: Thread 1
246 x: Thread is in running state
247
248 Figure 4. Ring buffer for per-thread mode
249
250 When perf runs in per-thread mode, a ring buffer is allocated for the
251 profiled thread *T1*. The ring buffer is dedicated for thread *T1*, if the
252 thread *T1* is running, the perf events will be recorded into the ring
253 buffer; when the thread is sleeping, all associated events will be
254 disabled, thus no trace data will be recorded into the ring buffer.
255
256 2.2.3 Per-CPU mode
257 ^^^^^^^^^^^^^^^^^^
258
259 The option ``-C`` is used to collect samples on the list of CPUs, for
260 example the below perf command receives option ``-C 0,2``::
261
262 perf record -C 0,2 test_program
263
264 It maps the perf event to CPUs 0 and 2, and the event is not associated to any
265 PID. Thus the perf event attributions are set as::
266
267 evsel::cpus::map[0] = { 0, 2 }
268 evsel::threads::map[] = { -1 }
269 evsel::attr::inherit = 0
270
271 This results in the session of ``perf record`` will sample all threads on CPU0
272 and CPU2, and be terminated until test_program exits. Even there have tasks
273 running on CPU1 and CPU3, since the ring buffer is absent for them, any
274 activities on these two CPUs will be ignored. A usage case is to combine the
275 options for per-thread mode and per-CPU mode, e.g. the options ``–C 0,2`` and
276 ``––per–thread`` are specified together, the samples are recorded only when
277 the profiled thread is scheduled on any of the listed CPUs.
278
279 ::
280
281 T1 T2 T1
282 +----+ +-----------+ +----+
283 CPU0 |xxxx| |xxxxxxxxxxx| |xxxx|
284 +----+--------------+-----------+----------+----+-------->
285 | | |
286 v v v
287 +-----------------------------------------------------+
288 | Ring buffer 0 |
289 +-----------------------------------------------------+
290
291 T1
292 +-----+
293 CPU1 |xxxxx|
294 -----+-----+--------------------------------------------->
295
296 T1 T3
297 +----+ +-------+
298 CPU2 |xxxx| |xxxxxxx|
299 --------------------------+----+--------+-------+-------->
300 | |
301 v v
302 +-----------------------------------------------------+
303 | Ring buffer 1 |
304 +-----------------------------------------------------+
305
306 T1
307 +--------------+
308 CPU3 |xxxxxxxxxxxxxx|
309 -----------+--------------+------------------------------>
310
311 T1: Thread 1; T2: Thread 2; T3: Thread 3
312 x: Thread is in running state
313
314 Figure 5. Ring buffer for per-CPU mode
315
316 2.2.4 System wide mode
317 ^^^^^^^^^^^^^^^^^^^^^^
318
319 By using option ``–a`` or ``––all–cpus``, perf collects samples on all CPUs
320 for all tasks, we call it as the system wide mode, the command is::
321
322 perf record -a test_program
323
324 Similar to the per-CPU mode, the perf event doesn't bind to any PID, and
325 it maps to all CPUs in the system::
326
327 evsel::cpus::map[] = { 0 .. _SC_NPROCESSORS_ONLN-1 }
328 evsel::threads::map[] = { -1 }
329 evsel::attr::inherit = 0
330
331 In the system wide mode, every CPU has its own ring buffer, all threads
332 are monitored during the running state and the samples are recorded into
333 the ring buffer belonging to the CPU which the events occurred on.
334
335 ::
336
337 T1 T2 T1
338 +----+ +-----------+ +----+
339 CPU0 |xxxx| |xxxxxxxxxxx| |xxxx|
340 +----+--------------+-----------+----------+----+-------->
341 | | |
342 v v v
343 +-----------------------------------------------------+
344 | Ring buffer 0 |
345 +-----------------------------------------------------+
346
347 T1
348 +-----+
349 CPU1 |xxxxx|
350 -----+-----+--------------------------------------------->
351 |
352 v
353 +-----------------------------------------------------+
354 | Ring buffer 1 |
355 +-----------------------------------------------------+
356
357 T1 T3
358 +----+ +-------+
359 CPU2 |xxxx| |xxxxxxx|
360 --------------------------+----+--------+-------+-------->
361 | |
362 v v
363 +-----------------------------------------------------+
364 | Ring buffer 2 |
365 +-----------------------------------------------------+
366
367 T1
368 +--------------+
369 CPU3 |xxxxxxxxxxxxxx|
370 -----------+--------------+------------------------------>
371 |
372 v
373 +-----------------------------------------------------+
374 | Ring buffer 3 |
375 +-----------------------------------------------------+
376
377 T1: Thread 1; T2: Thread 2; T3: Thread 3
378 x: Thread is in running state
379
380 Figure 6. Ring buffer for system wide mode
381
382 2.3 Accessing buffer
383 --------------------
384
385 Based on the understanding of how the ring buffer is allocated in
386 various modes, this section explains access the ring buffer.
387
388 2.3.1 Producer-consumer model
389 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
390
391 In the Linux kernel, the PMU events can produce samples which are stored
392 into the ring buffer; the perf command in user space consumes the
393 samples by reading out data from the ring buffer and finally saves the
394 data into the file for post analysis. It’s a typical producer-consumer
395 model for using the ring buffer.
396
397 The perf process polls on the PMU events and sleeps when no events are
398 incoming. To prevent frequent exchanges between the kernel and user
399 space, the kernel event core layer introduces a watermark, which is
400 stored in the ``perf_buffer::watermark``. When a sample is recorded into
401 the ring buffer, and if the used buffer exceeds the watermark, the
402 kernel wakes up the perf process to read samples from the ring buffer.
403
404 ::
405
406 Perf
407 / | Read samples
408 Polling / `--------------| Ring buffer
409 v v ;---------------------v
410 +----------------+ +---------+---------+ +-------------------+
411 |Event wait queue| |data_head|data_tail| |***|***| | |***|
412 +----------------+ +---------+---------+ +-------------------+
413 ^ ^ `------------------------^
414 | Wake up tasks | Store samples
415 +-----------------------------+
416 | Kernel event core layer |
417 +-----------------------------+
418
419 * : the data is filled by the writer.
420
421 Figure 7. Writing and reading the ring buffer
422
423 When the kernel event core layer notifies the user space, because
424 multiple events might share the same ring buffer for recording samples,
425 the core layer iterates every event associated with the ring buffer and
426 wakes up tasks waiting on the event. This is fulfilled by the kernel
427 function ``ring_buffer_wakeup()``.
428
429 After the perf process is woken up, it starts to check the ring buffers
430 one by one, if it finds any ring buffer containing samples it will read
431 out the samples for statistics or saving into the data file. Given the
432 perf process is able to run on any CPU, this leads to the ring buffer
433 potentially being accessed from multiple CPUs simultaneously, which
434 causes race conditions. The race condition handling is described in the
435 section :ref:`memory_synchronization`.
436
437 2.3.2 Properties of the ring buffers
438 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
439
440 Linux kernel supports two write directions for the ring buffer: forward and
441 backward. The forward writing saves samples from the beginning of the ring
442 buffer, the backward writing stores data from the end of the ring buffer with
443 the reversed direction. The perf tool determines the writing direction.
444
445 Additionally, the tool can map buffers in either read-write mode or read-only
446 mode to the user space.
447
448 The ring buffer in the read-write mode is mapped with the property
449 ``PROT_READ | PROT_WRITE``. With the write permission, the perf tool
450 updates the ``data_tail`` to indicate the data start position. Combining
451 with the head pointer ``data_head``, which works as the end position of
452 the current data, the perf tool can easily know where read out the data
453 from.
454
455 Alternatively, in the read-only mode, only the kernel keeps to update
456 the ``data_head`` while the user space cannot access the ``data_tail`` due
457 to the mapping property ``PROT_READ``.
458
459 As a result, the matrix below illustrates the various combinations of
460 direction and mapping characteristics. The perf tool employs two of these
461 combinations to support buffer types: the non-overwrite buffer and the
462 overwritable buffer.
463
464 .. list-table::
465 :widths: 1 1 1
466 :header-rows: 1
467
468 * - Mapping mode
469 - Forward
470 - Backward
471 * - read-write
472 - Non-overwrite ring buffer
473 - Not used
474 * - read-only
475 - Not used
476 - Overwritable ring buffer
477
478 The non-overwrite ring buffer uses the read-write mapping with forward
479 writing. It starts to save data from the beginning of the ring buffer
480 and wrap around when overflow, which is used with the read-write mode in
481 the normal ring buffer. When the consumer doesn't keep up with the
482 producer, it would lose some data, the kernel keeps how many records it
483 lost and generates the ``PERF_RECORD_LOST`` records in the next time
484 when it finds a space in the ring buffer.
485
486 The overwritable ring buffer uses the backward writing with the
487 read-only mode. It saves the data from the end of the ring buffer and
488 the ``data_head`` keeps the position of current data, the perf always
489 knows where it starts to read and until the end of the ring buffer, thus
490 it don't need the ``data_tail``. In this mode, it will not generate the
491 ``PERF_RECORD_LOST`` records.
492
493 .. _writing_samples_into_buffer:
494
495 2.3.3 Writing samples into buffer
496 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
497
498 When a sample is taken and saved into the ring buffer, the kernel
499 prepares sample fields based on the sample type; then it prepares the
500 info for writing ring buffer which is stored in the structure
501 ``perf_output_handle``. In the end, the kernel outputs the sample into
502 the ring buffer and updates the head pointer in the user page so the
503 perf tool can see the latest value.
504
505 The structure ``perf_output_handle`` serves as a temporary context for
506 tracking the information related to the buffer. The advantages of it is
507 that it enables concurrent writing to the buffer by different events.
508 For example, a software event and a hardware PMU event both are enabled
509 for profiling, two instances of ``perf_output_handle`` serve as separate
510 contexts for the software event and the hardware event respectively.
511 This allows each event to reserve its own memory space for populating
512 the record data.
513
514 2.3.4 Reading samples from buffer
515 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
516
517 In the user space, the perf tool utilizes the ``perf_event_mmap_page``
518 structure to handle the head and tail of the buffer. It also uses
519 ``perf_mmap`` structure to keep track of a context for the ring buffer, this
520 context includes information about the buffer's starting and ending
521 addresses. Additionally, the mask value can be utilized to compute the
522 circular buffer pointer even for an overflow.
523
524 Similar to the kernel, the perf tool in the user space first reads out
525 the recorded data from the ring buffer, and then updates the buffer's
526 tail pointer ``perf_event_mmap_page::data_tail``.
527
528 .. _memory_synchronization:
529
530 2.3.5 Memory synchronization
531 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
532
533 The modern CPUs with relaxed memory model cannot promise the memory
534 ordering, this means it’s possible to access the ring buffer and the
535 ``perf_event_mmap_page`` structure out of order. To assure the specific
536 sequence for memory accessing perf ring buffer, memory barriers are
537 used to assure the data dependency. The rationale for the memory
538 synchronization is as below::
539
540 Kernel User space
541
542 if (LOAD ->data_tail) { LOAD ->data_head
543 (A) smp_rmb() (C)
544 STORE $data LOAD $data
545 smp_wmb() (B) smp_mb() (D)
546 STORE ->data_head STORE ->data_tail
547 }
548
549 The comments in tools/include/linux/ring_buffer.h gives nice description
550 for why and how to use memory barriers, here we will just provide an
551 alternative explanation:
552
553 (A) is a control dependency so that CPU assures order between checking
554 pointer ``perf_event_mmap_page::data_tail`` and filling sample into ring
555 buffer;
556
557 (D) pairs with (A). (D) separates the ring buffer data reading from
558 writing the pointer ``data_tail``, perf tool first consumes samples and then
559 tells the kernel that the data chunk has been released. Since a reading
560 operation is followed by a writing operation, thus (D) is a full memory
561 barrier.
562
563 (B) is a writing barrier in the middle of two writing operations, which
564 makes sure that recording a sample must be prior to updating the head
565 pointer.
566
567 (C) pairs with (B). (C) is a read memory barrier to ensure the head
568 pointer is fetched before reading samples.
569
570 To implement the above algorithm, the ``perf_output_put_handle()`` function
571 in the kernel and two helpers ``ring_buffer_read_head()`` and
572 ``ring_buffer_write_tail()`` in the user space are introduced, they rely
573 on memory barriers as described above to ensure the data dependency.
574
575 Some architectures support one-way permeable barrier with load-acquire
576 and store-release operations, these barriers are more relaxed with less
577 performance penalty, so (C) and (D) can be optimized to use barriers
578 ``smp_load_acquire()`` and ``smp_store_release()`` respectively.
579
580 If an architecture doesn’t support load-acquire and store-release in its
581 memory model, it will roll back to the old fashion of memory barrier
582 operations. In this case, ``smp_load_acquire()`` encapsulates
583 ``READ_ONCE()`` + ``smp_mb()``, since ``smp_mb()`` is costly,
584 ``ring_buffer_read_head()`` doesn't invoke ``smp_load_acquire()`` and it uses
585 the barriers ``READ_ONCE()`` + ``smp_rmb()`` instead.
586
587 3. The mechanism of AUX ring buffer
588 ===================================
589
590 In this chapter, we will explain the implementation of the AUX ring
591 buffer. In the first part it will discuss the connection between the
592 AUX ring buffer and the regular ring buffer, then the second part will
593 examine how the AUX ring buffer co-works with the regular ring buffer,
594 as well as the additional features introduced by the AUX ring buffer for
595 the sampling mechanism.
596
597 3.1 The relationship between AUX and regular ring buffers
598 ---------------------------------------------------------
599
600 Generally, the AUX ring buffer is an auxiliary for the regular ring
601 buffer. The regular ring buffer is primarily used to store the event
602 samples and every event format complies with the definition in the
603 union ``perf_event``; the AUX ring buffer is for recording the hardware
604 trace data and the trace data format is hardware IP dependent.
605
606 The general use and advantage of the AUX ring buffer is that it is
607 written directly by hardware rather than by the kernel. For example,
608 regular profile samples that write to the regular ring buffer cause an
609 interrupt. Tracing execution requires a high number of samples and
610 using interrupts would be overwhelming for the regular ring buffer
611 mechanism. Having an AUX buffer allows for a region of memory more
612 decoupled from the kernel and written to directly by hardware tracing.
613
614 The AUX ring buffer reuses the same algorithm with the regular ring
615 buffer for the buffer management. The control structure
616 ``perf_event_mmap_page`` extends the new fields ``aux_head`` and ``aux_tail``
617 for the head and tail pointers of the AUX ring buffer.
618
619 During the initialisation phase, besides the mmap()-ed regular ring
620 buffer, the perf tool invokes a second syscall in the
621 ``auxtrace_mmap__mmap()`` function for the mmap of the AUX buffer with
622 non-zero file offset; ``rb_alloc_aux()`` in the kernel allocates pages
623 correspondingly, these pages will be deferred to map into VMA when
624 handling the page fault, which is the same lazy mechanism with the
625 regular ring buffer.
626
627 AUX events and AUX trace data are two different things. Let's see an
628 example::
629
630 perf record -a -e cycles -e cs_etm// -- sleep 2
631
632 The above command enables two events: one is the event *cycles* from PMU
633 and another is the AUX event *cs_etm* from Arm CoreSight, both are saved
634 into the regular ring buffer while the CoreSight's AUX trace data is
635 stored in the AUX ring buffer.
636
637 As a result, we can see the regular ring buffer and the AUX ring buffer
638 are allocated in pairs. The perf in default mode allocates the regular
639 ring buffer and the AUX ring buffer per CPU-wise, which is the same as
640 the system wide mode, however, the default mode records samples only for
641 the profiled program, whereas the latter mode profiles for all programs
642 in the system. For per-thread mode, the perf tool allocates only one
643 regular ring buffer and one AUX ring buffer for the whole session. For
644 the per-CPU mode, the perf allocates two kinds of ring buffers for
645 selected CPUs specified by the option ``-C``.
646
647 The below figure demonstrates the buffers' layout in the system wide
648 mode; if there are any activities on one CPU, the AUX event samples and
649 the hardware trace data will be recorded into the dedicated buffers for
650 the CPU.
651
652 ::
653
654 T1 T2 T1
655 +----+ +-----------+ +----+
656 CPU0 |xxxx| |xxxxxxxxxxx| |xxxx|
657 +----+--------------+-----------+----------+----+-------->
658 | | |
659 v v v
660 +-----------------------------------------------------+
661 | Ring buffer 0 |
662 +-----------------------------------------------------+
663 | | |
664 v v v
665 +-----------------------------------------------------+
666 | AUX Ring buffer 0 |
667 +-----------------------------------------------------+
668
669 T1
670 +-----+
671 CPU1 |xxxxx|
672 -----+-----+--------------------------------------------->
673 |
674 v
675 +-----------------------------------------------------+
676 | Ring buffer 1 |
677 +-----------------------------------------------------+
678 |
679 v
680 +-----------------------------------------------------+
681 | AUX Ring buffer 1 |
682 +-----------------------------------------------------+
683
684 T1 T3
685 +----+ +-------+
686 CPU2 |xxxx| |xxxxxxx|
687 --------------------------+----+--------+-------+-------->
688 | |
689 v v
690 +-----------------------------------------------------+
691 | Ring buffer 2 |
692 +-----------------------------------------------------+
693 | |
694 v v
695 +-----------------------------------------------------+
696 | AUX Ring buffer 2 |
697 +-----------------------------------------------------+
698
699 T1
700 +--------------+
701 CPU3 |xxxxxxxxxxxxxx|
702 -----------+--------------+------------------------------>
703 |
704 v
705 +-----------------------------------------------------+
706 | Ring buffer 3 |
707 +-----------------------------------------------------+
708 |
709 v
710 +-----------------------------------------------------+
711 | AUX Ring buffer 3 |
712 +-----------------------------------------------------+
713
714 T1: Thread 1; T2: Thread 2; T3: Thread 3
715 x: Thread is in running state
716
717 Figure 8. AUX ring buffer for system wide mode
718
719 3.2 AUX events
720 --------------
721
722 Similar to ``perf_output_begin()`` and ``perf_output_end()``'s working for the
723 regular ring buffer, ``perf_aux_output_begin()`` and ``perf_aux_output_end()``
724 serve for the AUX ring buffer for processing the hardware trace data.
725
726 Once the hardware trace data is stored into the AUX ring buffer, the PMU
727 driver will stop hardware tracing by calling the ``pmu::stop()`` callback.
728 Similar to the regular ring buffer, the AUX ring buffer needs to apply
729 the memory synchronization mechanism as discussed in the section
730 :ref:`memory_synchronization`. Since the AUX ring buffer is managed by the
731 PMU driver, the barrier (B), which is a writing barrier to ensure the trace
732 data is externally visible prior to updating the head pointer, is asked
733 to be implemented in the PMU driver.
734
735 Then ``pmu::stop()`` can safely call the ``perf_aux_output_end()`` function to
736 finish two things:
737
738 - It fills an event ``PERF_RECORD_AUX`` into the regular ring buffer, this
739 event delivers the information of the start address and data size for a
740 chunk of hardware trace data has been stored into the AUX ring buffer;
741
742 - Since the hardware trace driver has stored new trace data into the AUX
743 ring buffer, the argument *size* indicates how many bytes have been
744 consumed by the hardware tracing, thus ``perf_aux_output_end()`` updates the
745 header pointer ``perf_buffer::aux_head`` to reflect the latest buffer usage.
746
747 At the end, the PMU driver will restart hardware tracing. During this
748 temporary suspending period, it will lose hardware trace data, which
749 will introduce a discontinuity during decoding phase.
750
751 The event ``PERF_RECORD_AUX`` presents an AUX event which is handled in the
752 kernel, but it lacks the information for saving the AUX trace data in
753 the perf file. When the perf tool copies the trace data from AUX ring
754 buffer to the perf data file, it synthesizes a ``PERF_RECORD_AUXTRACE``
755 event which is not a kernel ABI, it's defined by the perf tool to describe
756 which portion of data in the AUX ring buffer is saved. Afterwards, the perf
757 tool reads out the AUX trace data from the perf file based on the
758 ``PERF_RECORD_AUXTRACE`` events, and the ``PERF_RECORD_AUX`` event is used to
759 decode a chunk of data by correlating with time order.
760
761 3.3 Snapshot mode
762 -----------------
763
764 Perf supports snapshot mode for AUX ring buffer, in this mode, users
765 only record AUX trace data at a specific time point which users are
766 interested in. E.g. below gives an example of how to take snapshots
767 with 1 second interval with Arm CoreSight::
768
769 perf record -e cs_etm//u -S -a program &
770 PERFPID=$!
771 while true; do
772 kill -USR2 $PERFPID
773 sleep 1
774 done
775
776 The main flow for snapshot mode is:
777
778 - Before a snapshot is taken, the AUX ring buffer acts in free run mode.
779 During free run mode the perf doesn't record any of the AUX events and
780 trace data;
781
782 - Once the perf tool receives the *USR2* signal, it triggers the callback
783 function ``auxtrace_record::snapshot_start()`` to deactivate hardware
784 tracing. The kernel driver then populates the AUX ring buffer with the
785 hardware trace data, and the event ``PERF_RECORD_AUX`` is stored in the
786 regular ring buffer;
787
788 - Then perf tool takes a snapshot, ``record__read_auxtrace_snapshot()``
789 reads out the hardware trace data from the AUX ring buffer and saves it
790 into perf data file;
791
792 - After the snapshot is finished, ``auxtrace_record::snapshot_finish()``
793 restarts the PMU event for AUX tracing.
794
795 The perf only accesses the head pointer ``perf_event_mmap_page::aux_head``
796 in snapshot mode and doesn’t touch tail pointer ``aux_tail``, this is
797 because the AUX ring buffer can overflow in free run mode, the tail
798 pointer is useless in this case. Alternatively, the callback
799 ``auxtrace_record::find_snapshot()`` is introduced for making the decision
800 of whether the AUX ring buffer has been wrapped around or not, at the
801 end it fixes up the AUX buffer's head which are used to calculate the
802 trace data size.
803
804 As we know, the buffers' deployment can be per-thread mode, per-CPU
805 mode, or system wide mode, and the snapshot can be applied to any of
806 these modes. Below is an example of taking snapshot with system wide
807 mode.
808
809 ::
810
811 Snapshot is taken
812 |
813 v
814 +------------------------+
815 | AUX Ring buffer 0 | <- aux_head
816 +------------------------+
817 v
818 +--------------------------------+
819 | AUX Ring buffer 1 | <- aux_head
820 +--------------------------------+
821 v
822 +--------------------------------------------+
823 | AUX Ring buffer 2 | <- aux_head
824 +--------------------------------------------+
825 v
826 +---------------------------------------+
827 | AUX Ring buffer 3 | <- aux_head
828 +---------------------------------------+
829
830 Figure 9. Snapshot with system wide mode
831

3. 한국어 전문 번역

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

문서 구성

1-30

이 문서는 perf ring buffer의 구현과 AUX ring buffer의 동작을 다음 순서로 설명합니다.

Perf ring buffer 문서 목차
주제
1소개
2.1기본 ring buffer 알고리즘
2.2default, per-thread, per-CPU, system-wide 추적 모드
2.3생산자·소비자 접근, 쓰기·읽기, 메모리 동기화
3.1AUX와 일반 ring buffer의 관계
3.2AUX event
3.3snapshot 모드

일반 ring buffer의 배치·접근을 먼저 다룬 뒤 AUX 추적 메커니즘으로 이어집니다.

.. SPDX-License-Identifier: GPL-2.0

================
Perf ring buffer
================

.. CONTENTS

    1. Introduction

    2. Ring buffer implementation
    2.1  Basic algorithm
    2.2  Ring buffer for different tracing modes
    2.2.1       Default mode
    2.2.2       Per-thread mode
    2.2.3       Per-CPU mode
    2.2.4       System wide mode
    2.3  Accessing buffer
    2.3.1       Producer-consumer model
    2.3.2       Properties of the ring buffers
    2.3.3       Writing samples into buffer
    2.3.4       Reading samples from buffer
    2.3.5       Memory synchronization

    3. The mechanism of AUX ring buffer
    3.1  The relationship between AUX and regular ring buffers
    3.2  AUX events
    3.3  Snapshot mode

1. 소개

31-50

ring buffer는 데이터 전송의 기본 메커니즘입니다. perf는 커널에서 사용자 공간으로 event 데이터를 옮기는 데 ring buffer를 사용하며, Intel PT와 Arm CoreSight 같은 하드웨어 추적에는 auxiliary, 즉 AUX ring buffer도 중요한 역할을 합니다.

ring buffer 구현은 핵심적이면서도 어렵습니다. 커널과 사용자 공간 perf 도구가 데이터를 교환해 파일에 저장하려면 처리량이 높아야 하지만, buffer 관리 부하가 프로파일링 결과를 왜곡할 만큼 커져서도 안 됩니다.

문서의 첫 부분은 perf ring buffer 구현을 설명하고, 두 번째 부분은 AUX ring buffer 메커니즘을 다룹니다.

1. Introduction
===============

The ring buffer is a fundamental mechanism for data transfer.  perf uses
ring buffers to transfer event data from kernel to user space, another
kind of ring buffer which is so called auxiliary (AUX) ring buffer also
plays an important role for hardware tracing with Intel PT, Arm
CoreSight, etc.

The ring buffer implementation is critical but it's also a very
challenging work.  On the one hand, the kernel and perf tool in the user
space use the ring buffer to exchange data and stores data into data
file, thus the ring buffer needs to transfer data with high throughput;
on the other hand, the ring buffer management should avoid significant
overload to distract profiling results.

This documentation dives into the details for perf ring buffer with two
parts: firstly it explains the perf ring buffer implementation, then the
second part discusses the AUX ring buffer mechanism.

2.1 기본 알고리즘

51-112

일반적인 ring buffer는 head와 tail 포인터로 관리합니다. writer가 head를 조작하고 reader가 tail을 갱신합니다.

Figure 1. 기본 ring buffer
Writer reserves space at HeadWriter fills records between Tail and HeadReader consumes records from TailReader advances Tail and the positions wrap around

writer가 head까지 데이터를 채우고 reader가 tail부터 소비합니다.

perf도 같은 방식으로 ring buffer를 관리합니다. 연속된 가상 페이지 묶음에 두 핵심 데이터 구조가 함께 놓이는데, 먼저 제어 구조가 있고 그 뒤에 ring buffer가 있습니다. 제어 구조를 담은 페이지를 user page라고 하며, ring buffer는 이 페이지 다음의 연속 가상 주소에서 쉽게 찾을 수 있습니다.

제어 구조 `perf_event_mmap_page`에는 head 포인터 `data_head`와 tail 포인터 `data_tail`이 있습니다. 커널은 record를 채우기 시작할 때 head를 갱신해 메모리를 예약한 뒤 안전하게 event를 저장합니다. user page가 쓰기 가능한 mapping이면 perf 도구는 데이터를 소비한 뒤 tail을 갱신할 수 있습니다. 읽기 전용 mapping의 경우는 뒤의 buffer 속성 절에서 별도로 다룹니다.

Figure 2. Perf ring buffer 배치
가상 메모리 영역내용역할
user page`data_head`, `data_tail`커널과 perf 도구가 생산·소비 위치를 공유
ring buffer pagesperf record 데이터tail에서 head까지 유효 데이터 저장
연속 가상 주소user page 다음에 data pages 배치ring buffer 시작 주소 계산 단순화

user page의 포인터가 뒤따르는 data page 영역을 가리킵니다.

`perf record`의 `-m` 또는 `--mmap-pages=` 옵션으로 ring buffer 크기를 지정할 수 있습니다. 값은 page size의 배수이면서 2의 거듭제곱인 크기로 올림됩니다.

커널은 모든 메모리 페이지를 한 번에 할당하지만 사용자 공간 perf가 buffer 페이지에 접근할 때까지 VMA mapping은 미룹니다. 최초 접근 시 page fault에 따른 data abort가 발생하고, 커널은 `perf_mmap_fault()`에서 해당 페이지를 프로세스 VMA에 mapping합니다. 예외에서 돌아오면 perf 도구가 페이지 접근을 계속할 수 있습니다.

2. Ring buffer implementation
=============================

2.1 Basic algorithm
-------------------

That said, a typical ring buffer is managed by a head pointer and a tail
pointer; the head pointer is manipulated by a writer and the tail
pointer is updated by a reader respectively.

::

        +---------------------------+
        |   |   |***|***|***|   |   |
        +---------------------------+
                `-> Tail    `-> Head

        * : the data is filled by the writer.

                Figure 1. Ring buffer

Perf uses the same way to manage its ring buffer.  In the implementation
there are two key data structures held together in a set of consecutive
pages, the control structure and then the ring buffer itself.  The page
with the control structure in is known as the "user page".  Being held
in continuous virtual addresses simplifies locating the ring buffer
address, it is in the pages after the page with the user page.

The control structure is named as ``perf_event_mmap_page``, it contains a
head pointer ``data_head`` and a tail pointer ``data_tail``.  When the
kernel starts to fill records into the ring buffer, it updates the head
pointer to reserve the memory so later it can safely store events into
the buffer.  On the other side, when the user page is a writable mapping,
the perf tool has the permission to update the tail pointer after consuming
data from the ring buffer.  Yet another case is for the user page's
read-only mapping, which is to be addressed in the section
:ref:`writing_samples_into_buffer`.

::

          user page                          ring buffer
    +---------+---------+   +---------------------------------------+
    |data_head|data_tail|...|   |   |***|***|***|***|***|   |   |   |
    +---------+---------+   +---------------------------------------+
        `          `----------------^                   ^
         `----------------------------------------------|

              * : the data is filled by the writer.

                Figure 2. Perf ring buffer

When using the ``perf record`` tool, we can specify the ring buffer size
with option ``-m`` or ``--mmap-pages=``, the given size will be rounded up
to a power of two that is a multiple of a page size.  Though the kernel
allocates at once for all memory pages, it's deferred to map the pages
to VMA area until the perf tool accesses the buffer from the user space.
In other words, at the first time accesses the buffer's page from user
space in the perf tool, a data abort exception for page fault is taken
and the kernel uses this occasion to map the page into process VMA
(see ``perf_mmap_fault()``), thus the perf tool can continue to access
the page after returning from the exception.

2.2 추적 모드별 ring buffer

113-120

perf는 default, per-thread, per-CPU, system-wide 모드로 프로그램을 프로파일링합니다. 각 모드는 CPU와 thread event mapping이 다르고, 그 차이가 ring buffer 배치와 경쟁 조건을 결정합니다.

추적 모드 비교
모드CPU 범위thread 범위buffer 배치
default모든 CPU대상 PID와 상속된 자식CPU별
per-thread특정 CPU에 고정하지 않음대상 threadthread 전용 1개
per-CPU선택한 CPU모든 thread선택 CPU별
system-wide모든 CPU모든 threadCPU별

세부 절에서 각 mapping과 buffer 소유 범위를 설명합니다.

2.2 Ring buffer for different tracing modes
-------------------------------------------

The perf profiles programs with different modes: default mode, per thread
mode, per cpu mode, and system wide mode.  This section describes these
modes and how the ring buffer meets requirements for them.  At last we
will review the race conditions caused by these modes.

2.2.1 Default 모드

121-194

보통 다음처럼 `perf record` 뒤에 프로파일링할 프로그램 이름을 지정합니다.

perf record test_program

CPU나 thread 모드 옵션을 지정하지 않았으므로 perf는 default 모드를 적용합니다. 시스템의 모든 CPU와 대상 프로그램 PID를 event에 mapping하고, 자식 태스크가 event를 상속하도록 inheritance를 활성화합니다.

evsel::cpus::map[]    = { 0 .. _SC_NPROCESSORS_ONLN-1 }
evsel::threads::map[] = { pid }
evsel::attr::inherit  = 1

이 속성은 ring buffer 배치에 반영됩니다. perf는 CPU마다 별도 ring buffer를 할당하지만, 시스템의 모든 thread가 아니라 대상 프로그램과 상속된 작업에 대해서만 event를 활성화합니다.

Figure 3. Default 모드의 buffer
CPU관찰되는 실행sample 저장 위치
CPU0T1 구간만 수집, T2는 제외Ring buffer 0
CPU1T1 구간만 수집Ring buffer 1
CPU2T1 구간만 수집, T3는 제외Ring buffer 2
CPU3T1 구간만 수집Ring buffer 3

T1은 test_program의 thread이고 T2와 T3은 무관한 thread입니다.

따라서 T1 sample은 T1이 실행된 CPU에 연결된 ring buffer에만 저장됩니다.

2.2.1 Default mode
^^^^^^^^^^^^^^^^^^

Usually we execute ``perf record`` command followed by a profiling program
name, like below command::

        perf record test_program

This command doesn't specify any options for CPU and thread modes, the
perf tool applies the default mode on the perf event.  It maps all the
CPUs in the system and the profiled program's PID on the perf event, and
it enables inheritance mode on the event so that child tasks inherits
the events.  As a result, the perf event is attributed as::

    evsel::cpus::map[]    = { 0 .. _SC_NPROCESSORS_ONLN-1 }
    evsel::threads::map[] = { pid }
    evsel::attr::inherit  = 1

These attributions finally will be reflected on the deployment of ring
buffers.  As shown below, the perf tool allocates individual ring buffer
for each CPU, but it only enables events for the profiled program rather
than for all threads in the system.  The *T1* thread represents the
thread context of the 'test_program', whereas *T2* and *T3* are irrelevant
threads in the system.   The perf samples are exclusively collected for
the *T1* thread and stored in the ring buffer associated with the CPU on
which the *T1* thread is running.

::

              T1                      T2                 T1
            +----+              +-----------+          +----+
    CPU0    |xxxx|              |xxxxxxxxxxx|          |xxxx|
            +----+--------------+-----------+----------+----+-------->
              |                                          |
              v                                          v
            +-----------------------------------------------------+
            |                  Ring buffer 0                      |
            +-----------------------------------------------------+

                   T1
                 +-----+
    CPU1         |xxxxx|
            -----+-----+--------------------------------------------->
                    |
                    v
            +-----------------------------------------------------+
            |                  Ring buffer 1                      |
            +-----------------------------------------------------+

                                        T1              T3
                                      +----+        +-------+
    CPU2                              |xxxx|        |xxxxxxx|
            --------------------------+----+--------+-------+-------->
                                        |
                                        v
            +-----------------------------------------------------+
            |                  Ring buffer 2                      |
            +-----------------------------------------------------+

                              T1
                       +--------------+
    CPU3               |xxxxxxxxxxxxxx|
            -----------+--------------+------------------------------>
                              |
                              v
            +-----------------------------------------------------+
            |                  Ring buffer 3                      |
            +-----------------------------------------------------+

	    T1: Thread 1; T2: Thread 2; T3: Thread 3
	    x: Thread is in running state

                Figure 3. Ring buffer for default mode

2.2.2 Per-thread 모드

195-255

`--per-thread` 옵션은 다음처럼 사용합니다.

perf record --per-thread test_program

이 event는 어떤 CPU에도 mapping되지 않고 대상 프로세스에만 연결되며, 상속도 비활성화됩니다.

evsel::cpus::map[0]   = { -1 }
evsel::threads::map[] = { pid }
evsel::attr::inherit  = 0

대상 thread를 위한 ring buffer 하나만 할당합니다. thread가 CPU에 schedule되면 해당 CPU의 event를 활성화하고, CPU에서 빠지면 비활성화합니다. CPU 사이를 이동할 때는 이전 CPU의 event를 끄고 다음 CPU의 event를 켭니다.

Figure 4. Per-thread buffer
T1 is scheduled on a CPU and that CPU's events are enabledT1 samples flow into the single thread ring bufferT1 migrates and previous CPU events are disabledNext CPU events are enabled; T2 and T3 remain excluded

T1이 CPU0, CPU1, CPU3, CPU2, CPU0으로 이동해도 모든 sample은 하나의 buffer로 모입니다.

T1이 실행 중일 때만 관련 event가 ring buffer에 기록됩니다. T1이 잠들면 연결된 event가 모두 비활성화되어 trace data가 기록되지 않습니다.

2.2.2 Per-thread mode
^^^^^^^^^^^^^^^^^^^^^

By specifying option ``--per-thread`` in perf command, e.g.

::

        perf record --per-thread test_program

The perf event doesn't map to any CPUs and is only bound to the
profiled process, thus, the perf event's attributions are::

    evsel::cpus::map[0]   = { -1 }
    evsel::threads::map[] = { pid }
    evsel::attr::inherit  = 0

In this mode, a single ring buffer is allocated for the profiled thread;
if the thread is scheduled on a CPU, the events on that CPU will be
enabled; and if the thread is scheduled out from the CPU, the events on
the CPU will be disabled.  When the thread is migrated from one CPU to
another, the events are to be disabled on the previous CPU and enabled
on the next CPU correspondingly.

::

              T1                      T2                 T1
            +----+              +-----------+          +----+
    CPU0    |xxxx|              |xxxxxxxxxxx|          |xxxx|
            +----+--------------+-----------+----------+----+-------->
              |                                           |
              |    T1                                     |
              |  +-----+                                  |
    CPU1      |  |xxxxx|                                  |
            --|--+-----+----------------------------------|---------->
              |     |                                     |
              |     |                   T1            T3  |
              |     |                 +----+        +---+ |
    CPU2      |     |                 |xxxx|        |xxx| |
            --|-----|-----------------+----+--------+---+-|---------->
              |     |                   |                 |
              |     |         T1        |                 |
              |     |  +--------------+ |                 |
    CPU3      |     |  |xxxxxxxxxxxxxx| |                 |
            --|-----|--+--------------+-|-----------------|---------->
              |     |         |         |                 |
              v     v         v         v                 v
            +-----------------------------------------------------+
            |                  Ring buffer                        |
            +-----------------------------------------------------+

            T1: Thread 1
            x: Thread is in running state

                Figure 4. Ring buffer for per-thread mode

When perf runs in per-thread mode, a ring buffer is allocated for the
profiled thread *T1*.  The ring buffer is dedicated for thread *T1*, if the
thread *T1* is running, the perf events will be recorded into the ring
buffer; when the thread is sleeping, all associated events will be
disabled, thus no trace data will be recorded into the ring buffer.

2.2.3 Per-CPU 모드

256-315

`-C` 옵션은 sample을 수집할 CPU 목록을 지정합니다. 다음 명령은 CPU0과 CPU2를 선택합니다.

perf record -C 0,2 test_program

perf event는 CPU0과 CPU2에 mapping되고 특정 PID에는 연결되지 않습니다.

evsel::cpus::map[0]   = { 0, 2 }
evsel::threads::map[] = { -1 }
evsel::attr::inherit  = 0

`perf record` 세션은 CPU0과 CPU2에서 실행되는 모든 thread를 sample하며 test_program이 끝날 때 종료됩니다. CPU1과 CPU3의 활동은 ring buffer가 없으므로 무시됩니다.

per-thread와 per-CPU 옵션을 함께 사용할 수도 있습니다. 예를 들어 `-C 0,2`와 `--per-thread`를 함께 주면 대상 thread가 지정 CPU 중 하나에서 실행될 때만 sample을 기록합니다.

Figure 5. Per-CPU buffer
CPU수집 여부buffer
CPU0T1과 T2 모두 수집Ring buffer 0
CPU1수집하지 않음없음
CPU2T1과 T3 모두 수집Ring buffer 1
CPU3수집하지 않음없음

선택된 CPU의 모든 실행 구간이 해당 CPU buffer로 들어갑니다.

2.2.3 Per-CPU mode
^^^^^^^^^^^^^^^^^^

The option ``-C`` is used to collect samples on the list of CPUs, for
example the below perf command receives option ``-C 0,2``::

	perf record -C 0,2 test_program

It maps the perf event to CPUs 0 and 2, and the event is not associated to any
PID.  Thus the perf event attributions are set as::

    evsel::cpus::map[0]   = { 0, 2 }
    evsel::threads::map[] = { -1 }
    evsel::attr::inherit  = 0

This results in the session of ``perf record`` will sample all threads on CPU0
and CPU2, and be terminated until test_program exits.  Even there have tasks
running on CPU1 and CPU3, since the ring buffer is absent for them, any
activities on these two CPUs will be ignored.  A usage case is to combine the
options for per-thread mode and per-CPU mode, e.g. the options ``–C 0,2`` and
``––per–thread`` are specified together, the samples are recorded only when
the profiled thread is scheduled on any of the listed CPUs.

::

              T1                      T2                 T1
            +----+              +-----------+          +----+
    CPU0    |xxxx|              |xxxxxxxxxxx|          |xxxx|
            +----+--------------+-----------+----------+----+-------->
              |                       |                  |
              v                       v                  v
            +-----------------------------------------------------+
            |                  Ring buffer 0                      |
            +-----------------------------------------------------+

                   T1
                 +-----+
    CPU1         |xxxxx|
            -----+-----+--------------------------------------------->

                                        T1              T3
                                      +----+        +-------+
    CPU2                              |xxxx|        |xxxxxxx|
            --------------------------+----+--------+-------+-------->
                                        |               |
                                        v               v
            +-----------------------------------------------------+
            |                  Ring buffer 1                      |
            +-----------------------------------------------------+

                              T1
                       +--------------+
    CPU3               |xxxxxxxxxxxxxx|
            -----------+--------------+------------------------------>

            T1: Thread 1; T2: Thread 2; T3: Thread 3
            x: Thread is in running state

                Figure 5. Ring buffer for per-CPU mode

2.2.4 System-wide 모드

316-381

`-a` 또는 `--all-cpus`를 사용하면 모든 CPU에서 모든 태스크의 sample을 수집합니다.

perf record -a test_program

per-CPU 모드와 마찬가지로 event는 PID에 묶이지 않으며 시스템의 모든 CPU에 mapping됩니다.

evsel::cpus::map[]    = { 0 .. _SC_NPROCESSORS_ONLN-1 }
evsel::threads::map[] = { -1 }
evsel::attr::inherit  = 0

모든 CPU에 자체 ring buffer가 있고, 실행 중인 모든 thread를 감시합니다. sample은 event가 발생한 CPU의 ring buffer에 기록됩니다.

Figure 6. System-wide buffer
CPU예시 실행sample 저장 위치
CPU0T1, T2, T1Ring buffer 0
CPU1T1Ring buffer 1
CPU2T1, T3Ring buffer 2
CPU3T1Ring buffer 3

CPU마다 모든 thread의 실행을 수집합니다.

2.2.4 System wide mode
^^^^^^^^^^^^^^^^^^^^^^

By using option ``–a`` or ``––all–cpus``, perf collects samples on all CPUs
for all tasks, we call it as the system wide mode, the command is::

        perf record -a test_program

Similar to the per-CPU mode, the perf event doesn't bind to any PID, and
it maps to all CPUs in the system::

   evsel::cpus::map[]    = { 0 .. _SC_NPROCESSORS_ONLN-1 }
   evsel::threads::map[] = { -1 }
   evsel::attr::inherit  = 0

In the system wide mode, every CPU has its own ring buffer, all threads
are monitored during the running state and the samples are recorded into
the ring buffer belonging to the CPU which the events occurred on.

::

              T1                      T2                 T1
            +----+              +-----------+          +----+
    CPU0    |xxxx|              |xxxxxxxxxxx|          |xxxx|
            +----+--------------+-----------+----------+----+-------->
              |                       |                  |
              v                       v                  v
            +-----------------------------------------------------+
            |                  Ring buffer 0                      |
            +-----------------------------------------------------+

                   T1
                 +-----+
    CPU1         |xxxxx|
            -----+-----+--------------------------------------------->
                    |
                    v
            +-----------------------------------------------------+
            |                  Ring buffer 1                      |
            +-----------------------------------------------------+

                                        T1              T3
                                      +----+        +-------+
    CPU2                              |xxxx|        |xxxxxxx|
            --------------------------+----+--------+-------+-------->
                                        |               |
                                        v               v
            +-----------------------------------------------------+
            |                  Ring buffer 2                      |
            +-----------------------------------------------------+

                              T1
                       +--------------+
    CPU3               |xxxxxxxxxxxxxx|
            -----------+--------------+------------------------------>
                              |
                              v
            +-----------------------------------------------------+
            |                  Ring buffer 3                      |
            +-----------------------------------------------------+

            T1: Thread 1; T2: Thread 2; T3: Thread 3
            x: Thread is in running state

                Figure 6. Ring buffer for system wide mode

2.3 Buffer 접근

382-387

여러 모드에서 ring buffer가 어떻게 할당되는지 살펴보았으므로, 이제 커널 생산자와 사용자 공간 소비자가 buffer에 접근하는 방법을 설명합니다.

2.3 Accessing buffer
--------------------

Based on the understanding of how the ring buffer is allocated in
various modes, this section explains access the ring buffer.

2.3.1 생산자·소비자 모델

388-436

Linux 커널의 PMU event는 ring buffer에 저장할 sample을 생산합니다. 사용자 공간의 perf 명령은 buffer에서 데이터를 읽어 소비하고, 사후 분석을 위해 최종적으로 파일에 저장합니다. 전형적인 생산자·소비자 모델입니다.

perf 프로세스는 PMU event를 poll하며 들어오는 event가 없으면 잠듭니다. 커널과 사용자 공간 사이의 잦은 전환을 막기 위해 kernel event core는 `perf_buffer::watermark`에 저장된 watermark를 사용합니다. sample 기록 후 사용한 buffer 크기가 watermark를 넘으면 perf 프로세스를 깨워 sample을 읽게 합니다.

Figure 7. Ring buffer 쓰기와 읽기
Kernel event core writes samples and advances data_headUsed space exceeds perf_buffer::watermarkring_buffer_wakeup() wakes tasks on associated event wait queuesPerf reads records and advances data_tailPerf stores samples for statistics or the perf data file

watermark 기반 알림이 kernel producer와 perf consumer를 연결합니다.

여러 event가 같은 ring buffer를 공유할 수 있으므로 kernel event core는 buffer와 연결된 모든 event를 순회하며 각 event를 기다리는 태스크를 깨웁니다. 이 동작은 `ring_buffer_wakeup()`이 수행합니다.

깨어난 perf 프로세스는 ring buffer를 하나씩 확인하고 sample이 있는 buffer를 읽어 통계를 내거나 data file에 저장합니다. perf 프로세스 자체는 어떤 CPU에서도 실행될 수 있으므로 여러 CPU가 ring buffer에 동시에 접근할 수 있고 경쟁 조건이 생깁니다. 해결 방식은 메모리 동기화 절에서 설명합니다.

2.3.1 Producer-consumer model
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In the Linux kernel, the PMU events can produce samples which are stored
into the ring buffer; the perf command in user space consumes the
samples by reading out data from the ring buffer and finally saves the
data into the file for post analysis.  It’s a typical producer-consumer
model for using the ring buffer.

The perf process polls on the PMU events and sleeps when no events are
incoming.  To prevent frequent exchanges between the kernel and user
space, the kernel event core layer introduces a watermark, which is
stored in the ``perf_buffer::watermark``.  When a sample is recorded into
the ring buffer, and if the used buffer exceeds the watermark, the
kernel wakes up the perf process to read samples from the ring buffer.

::

                       Perf
                       / | Read samples
             Polling  /  `--------------|               Ring buffer
                     v                  v    ;---------------------v
    +----------------+     +---------+---------+   +-------------------+
    |Event wait queue|     |data_head|data_tail|   |***|***|   |   |***|
    +----------------+     +---------+---------+   +-------------------+
             ^                  ^ `------------------------^
             | Wake up tasks    | Store samples
          +-----------------------------+
          |  Kernel event core layer    |
          +-----------------------------+

              * : the data is filled by the writer.

                Figure 7. Writing and reading the ring buffer

When the kernel event core layer notifies the user space, because
multiple events might share the same ring buffer for recording samples,
the core layer iterates every event associated with the ring buffer and
wakes up tasks waiting on the event.  This is fulfilled by the kernel
function ``ring_buffer_wakeup()``.

After the perf process is woken up, it starts to check the ring buffers
one by one, if it finds any ring buffer containing samples it will read
out the samples for statistics or saving into the data file.  Given the
perf process is able to run on any CPU, this leads to the ring buffer
potentially being accessed from multiple CPUs simultaneously, which
causes race conditions.  The race condition handling is described in the
section :ref:`memory_synchronization`.

2.3.2 Ring buffer 속성

437-494

커널은 ring buffer의 forward와 backward 두 쓰기 방향을 지원합니다. forward는 buffer 시작부터 sample을 저장하고, backward는 buffer 끝에서 역방향으로 저장합니다. perf 도구가 쓰기 방향을 결정합니다.

도구는 buffer를 read-write 또는 read-only 모드로 사용자 공간에 mapping할 수 있습니다.

read-write buffer는 `PROT_READ | PROT_WRITE`로 mapping됩니다. perf는 쓰기 권한으로 `data_tail`을 갱신해 데이터 시작 위치를 표시하고, 현재 데이터 끝인 `data_head`와 함께 읽을 범위를 계산합니다.

read-only buffer에서는 커널만 `data_head`를 계속 갱신하며, 사용자 공간은 `PROT_READ` 속성 때문에 `data_tail`에 접근할 수 없습니다.

쓰기 방향과 mapping 조합
MappingForwardBackward
read-writeNon-overwrite ring buffer사용하지 않음
read-only사용하지 않음Overwritable ring buffer

perf는 네 조합 중 두 가지를 실제 buffer 유형으로 사용합니다.

non-overwrite ring buffer는 read-write mapping과 forward 쓰기를 사용합니다. 시작부터 쓰고 넘치면 순환합니다. 소비자가 생산자를 따라가지 못하면 데이터를 잃을 수 있으며, 커널은 손실 record 수를 보관했다가 공간이 생기면 다음에 `PERF_RECORD_LOST`를 생성합니다.

overwritable ring buffer는 read-only mapping과 backward 쓰기를 사용합니다. 끝에서부터 데이터를 저장하고 `data_head`가 현재 데이터 위치를 유지하므로 perf는 읽기 시작점과 buffer 끝을 알 수 있어 `data_tail`이 필요 없습니다. 이 모드에서는 `PERF_RECORD_LOST`를 생성하지 않습니다.

2.3.2 Properties of the ring buffers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Linux kernel supports two write directions for the ring buffer: forward and
backward.  The forward writing saves samples from the beginning of the ring
buffer, the backward writing stores data from the end of the ring buffer with
the reversed direction.  The perf tool determines the writing direction.

Additionally, the tool can map buffers in either read-write mode or read-only
mode to the user space.

The ring buffer in the read-write mode is mapped with the property
``PROT_READ | PROT_WRITE``.  With the write permission, the perf tool
updates the ``data_tail`` to indicate the data start position.  Combining
with the head pointer ``data_head``, which works as the end position of
the current data, the perf tool can easily know where read out the data
from.

Alternatively, in the read-only mode, only the kernel keeps to update
the ``data_head`` while the user space cannot access the ``data_tail`` due
to the mapping property ``PROT_READ``.

As a result, the matrix below illustrates the various combinations of
direction and mapping characteristics.  The perf tool employs two of these
combinations to support buffer types: the non-overwrite buffer and the
overwritable buffer.

.. list-table::
   :widths: 1 1 1
   :header-rows: 1

   * - Mapping mode
     - Forward
     - Backward
   * - read-write
     - Non-overwrite ring buffer
     - Not used
   * - read-only
     - Not used
     - Overwritable ring buffer

The non-overwrite ring buffer uses the read-write mapping with forward
writing.  It starts to save data from the beginning of the ring buffer
and wrap around when overflow, which is used with the read-write mode in
the normal ring buffer.  When the consumer doesn't keep up with the
producer, it would lose some data, the kernel keeps how many records it
lost and generates the ``PERF_RECORD_LOST`` records in the next time
when it finds a space in the ring buffer.

The overwritable ring buffer uses the backward writing with the
read-only mode.  It saves the data from the end of the ring buffer and
the ``data_head`` keeps the position of current data, the perf always
knows where it starts to read and until the end of the ring buffer, thus
it don't need the ``data_tail``.  In this mode, it will not generate the
``PERF_RECORD_LOST`` records.

.. _writing_samples_into_buffer:

2.3.3 Buffer에 sample 쓰기

495-513

sample을 얻어 ring buffer에 저장할 때 커널은 sample type에 따라 필드를 준비하고, `perf_output_handle` 구조체에 buffer 쓰기 정보를 구성합니다. 마지막으로 sample을 출력하고 user page의 head를 갱신해 perf 도구가 최신 값을 볼 수 있게 합니다.

`perf_output_handle`은 buffer 관련 정보를 추적하는 임시 context입니다. 서로 다른 event가 buffer에 동시에 쓸 수 있게 하는 장점이 있습니다. 예를 들어 software event와 hardware PMU event를 함께 활성화하면 각각의 `perf_output_handle` 인스턴스가 독립 context가 되어 자기 record를 채울 메모리 공간을 따로 예약합니다.

Sample 기록 순서
Prepare fields from the sample typeCreate a perf_output_handle contextReserve record space in the ring bufferPopulate sample dataPublish the new data_head to user space

예약과 공개를 분리해 동시 writer가 각자 공간을 확보합니다.

2.3.3 Writing samples into buffer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When a sample is taken and saved into the ring buffer, the kernel
prepares sample fields based on the sample type; then it prepares the
info for writing ring buffer which is stored in the structure
``perf_output_handle``.  In the end, the kernel outputs the sample into
the ring buffer and updates the head pointer in the user page so the
perf tool can see the latest value.

The structure ``perf_output_handle`` serves as a temporary context for
tracking the information related to the buffer.  The advantages of it is
that it enables concurrent writing to the buffer by different events.
For example, a software event and a hardware PMU event both are enabled
for profiling, two instances of ``perf_output_handle`` serve as separate
contexts for the software event and the hardware event respectively.
This allows each event to reserve its own memory space for populating
the record data.

2.3.4 Buffer에서 sample 읽기

514-529

사용자 공간 perf 도구는 `perf_event_mmap_page`로 buffer head와 tail을 처리합니다. `perf_mmap` 구조체는 ring buffer의 시작·끝 주소를 포함한 context를 추적하며, mask 값으로 overflow 뒤에도 circular buffer 포인터를 계산할 수 있습니다.

커널과 대응해 perf 도구는 먼저 기록된 데이터를 ring buffer에서 읽고, 그 다음 tail 포인터 `perf_event_mmap_page::data_tail`을 갱신합니다.

2.3.4 Reading samples from buffer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In the user space, the perf tool utilizes the ``perf_event_mmap_page``
structure to handle the head and tail of the buffer.  It also uses
``perf_mmap`` structure to keep track of a context for the ring buffer, this
context includes information about the buffer's starting and ending
addresses.  Additionally, the mask value can be utilized to compute the
circular buffer pointer even for an overflow.

Similar to the kernel, the perf tool in the user space first reads out
the recorded data from the ring buffer, and then updates the buffer's
tail pointer ``perf_event_mmap_page::data_tail``.

.. _memory_synchronization:

2.3.5 메모리 동기화

530-586

완화된 메모리 모델을 사용하는 현대 CPU는 메모리 접근 순서를 자동으로 보장하지 않습니다. ring buffer와 `perf_event_mmap_page`를 순서가 뒤바뀐 채 접근할 수 있으므로 perf는 memory barrier로 필요한 데이터 의존성과 접근 순서를 강제합니다.

Kernel                          User space

if (LOAD ->data_tail) {         LOAD ->data_head
                 (A)            smp_rmb()        (C)
  STORE $data                   LOAD $data
  smp_wmb()      (B)            smp_mb()         (D)
  STORE ->data_head             STORE ->data_tail
}
A~D 메모리 순서 보장
표시위치보장
Akernel의 `data_tail` 확인control dependency로 tail 확인보다 sample 채우기가 뒤에 오도록 보장
Bsample 저장과 `data_head` 갱신 사이write barrier로 record가 먼저 기록되도록 보장
Cuser의 `data_head`와 sample 읽기 사이B와 짝을 이루는 read barrier로 head를 먼저 읽도록 보장
Dsample 읽기와 `data_tail` 쓰기 사이A와 짝을 이루는 full barrier로 소비 후 해제 통지를 보장

kernel writer와 user-space reader의 barrier가 서로 짝을 이룹니다.

A는 `perf_event_mmap_page::data_tail` 포인터 확인과 ring buffer sample 기록 사이의 control dependency입니다.

D는 A와 짝을 이룹니다. perf 도구가 sample을 먼저 소비한 뒤 `data_tail`을 써서 해당 데이터 구간을 해제했다고 커널에 알리며, read 뒤 write이므로 full memory barrier입니다.

B는 두 write 사이의 barrier로 sample 기록이 head 갱신보다 먼저 일어나게 합니다. C는 B와 짝인 read barrier로 head를 가져온 뒤 sample을 읽게 합니다.

커널의 `perf_output_put_handle()`과 사용자 공간의 `ring_buffer_read_head()`, `ring_buffer_write_tail()` helper가 이 알고리즘과 barrier를 구현합니다.

일부 아키텍처는 한 방향 투과 장벽인 load-acquire와 store-release를 지원합니다. 성능 비용이 더 낮으므로 C와 D를 각각 `smp_load_acquire()`와 `smp_store_release()`로 최적화할 수 있습니다.

아키텍처 메모리 모델이 load-acquire와 store-release를 지원하지 않으면 전통적인 barrier로 돌아갑니다. 이 경우 `smp_load_acquire()`는 `READ_ONCE()`와 `smp_mb()`를 감싸지만 `smp_mb()` 비용이 크므로 `ring_buffer_read_head()`는 이를 호출하지 않고 `READ_ONCE()`와 `smp_rmb()`를 사용합니다.

2.3.5 Memory synchronization
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The modern CPUs with relaxed memory model cannot promise the memory
ordering, this means it’s possible to access the ring buffer and the
``perf_event_mmap_page`` structure out of order.  To assure the specific
sequence for memory accessing perf ring buffer, memory barriers are
used to assure the data dependency.  The rationale for the memory
synchronization is as below::

  Kernel                          User space

  if (LOAD ->data_tail) {         LOAD ->data_head
                   (A)            smp_rmb()        (C)
    STORE $data                   LOAD $data
    smp_wmb()      (B)            smp_mb()         (D)
    STORE ->data_head             STORE ->data_tail
  }

The comments in tools/include/linux/ring_buffer.h gives nice description
for why and how to use memory barriers, here we will just provide an
alternative explanation:

(A) is a control dependency so that CPU assures order between checking
pointer ``perf_event_mmap_page::data_tail`` and filling sample into ring
buffer;

(D) pairs with (A).  (D) separates the ring buffer data reading from
writing the pointer ``data_tail``, perf tool first consumes samples and then
tells the kernel that the data chunk has been released.  Since a reading
operation is followed by a writing operation, thus (D) is a full memory
barrier.

(B) is a writing barrier in the middle of two writing operations, which
makes sure that recording a sample must be prior to updating the head
pointer.

(C) pairs with (B).  (C) is a read memory barrier to ensure the head
pointer is fetched before reading samples.

To implement the above algorithm, the ``perf_output_put_handle()`` function
in the kernel and two helpers ``ring_buffer_read_head()`` and
``ring_buffer_write_tail()`` in the user space are introduced, they rely
on memory barriers as described above to ensure the data dependency.

Some architectures support one-way permeable barrier with load-acquire
and store-release operations, these barriers are more relaxed with less
performance penalty, so (C) and (D) can be optimized to use barriers
``smp_load_acquire()`` and ``smp_store_release()`` respectively.

If an architecture doesn’t support load-acquire and store-release in its
memory model, it will roll back to the old fashion of memory barrier
operations.  In this case, ``smp_load_acquire()`` encapsulates
``READ_ONCE()`` + ``smp_mb()``, since ``smp_mb()`` is costly,
``ring_buffer_read_head()`` doesn't invoke ``smp_load_acquire()`` and it uses
the barriers ``READ_ONCE()`` + ``smp_rmb()`` instead.

3. AUX ring buffer 메커니즘

587-596

이 장은 AUX ring buffer 구현을 설명합니다. 먼저 일반 ring buffer와 AUX buffer의 연결을 다루고, 이어서 두 buffer의 협력 방식과 AUX buffer가 sampling에 추가한 기능을 살펴봅니다.

3. The mechanism of AUX ring buffer
===================================

In this chapter, we will explain the implementation of the AUX ring
buffer.  In the first part it will discuss the connection between the
AUX ring buffer and the regular ring buffer, then the second part will
examine how the AUX ring buffer co-works with the regular ring buffer,
as well as the additional features introduced by the AUX ring buffer for
the sampling mechanism.

3.1 AUX와 일반 ring buffer의 관계

597-718

AUX ring buffer는 일반 ring buffer를 보조합니다. 일반 buffer는 주로 event sample을 저장하고 각 event 형식은 union `perf_event` 정의를 따릅니다. AUX buffer는 하드웨어 trace data를 기록하며 형식은 하드웨어 IP에 따라 달라집니다.

AUX buffer의 장점은 커널 대신 하드웨어가 직접 쓴다는 것입니다. 일반 profile sample은 일반 ring buffer에 쓸 때 interrupt를 일으킵니다. 실행 추적은 매우 많은 sample이 필요해 같은 interrupt 방식을 쓰면 감당하기 어렵습니다. AUX buffer는 커널과 더 분리된 메모리 영역을 하드웨어 추적기가 직접 쓰게 합니다.

AUX ring buffer도 일반 buffer와 같은 관리 알고리즘을 재사용합니다. `perf_event_mmap_page`에는 AUX head와 tail인 `aux_head`, `aux_tail` 필드가 추가됩니다.

초기화할 때 perf 도구는 mmap된 일반 ring buffer와 별도로 `auxtrace_mmap__mmap()`에서 0이 아닌 file offset으로 AUX buffer를 두 번째 mmap합니다. 커널의 `rb_alloc_aux()`가 페이지를 할당하고, 일반 buffer처럼 page fault 처리 때 VMA mapping을 지연 수행합니다.

AUX event와 AUX trace data는 서로 다른 것입니다. 다음 명령은 PMU의 `cycles` event와 Arm CoreSight의 AUX event `cs_etm`을 활성화합니다.

perf record -a -e cycles -e cs_etm// -- sleep 2

두 event record는 모두 일반 ring buffer에 저장되지만 CoreSight의 AUX trace data는 AUX ring buffer에 저장됩니다.

모드별 일반·AUX buffer 쌍
모드할당 단위수집 범위
defaultCPU마다 일반 1개 + AUX 1개대상 프로그램만
system-wideCPU마다 일반 1개 + AUX 1개시스템의 모든 프로그램
per-thread세션 전체에 일반 1개 + AUX 1개대상 thread
per-CPU`-C`로 선택한 CPU마다 두 buffer선택 CPU의 활동

두 종류의 buffer는 함께 할당됩니다.

Figure 8. System-wide AUX 배치
CPU일반 event record하드웨어 trace data
CPU0Ring buffer 0AUX Ring buffer 0
CPU1Ring buffer 1AUX Ring buffer 1
CPU2Ring buffer 2AUX Ring buffer 2
CPU3Ring buffer 3AUX Ring buffer 3

각 CPU의 event sample과 hardware trace data가 전용 buffer 쌍에 들어갑니다.

3.1 The relationship between AUX and regular ring buffers
---------------------------------------------------------

Generally, the AUX ring buffer is an auxiliary for the regular ring
buffer.  The regular ring buffer is primarily used to store the event
samples and every event format complies with the definition in the
union ``perf_event``; the AUX ring buffer is for recording the hardware
trace data and the trace data format is hardware IP dependent.

The general use and advantage of the AUX ring buffer is that it is
written directly by hardware rather than by the kernel.  For example,
regular profile samples that write to the regular ring buffer cause an
interrupt.  Tracing execution requires a high number of samples and
using interrupts would be overwhelming for the regular ring buffer
mechanism.  Having an AUX buffer allows for a region of memory more
decoupled from the kernel and written to directly by hardware tracing.

The AUX ring buffer reuses the same algorithm with the regular ring
buffer for the buffer management.  The control structure
``perf_event_mmap_page`` extends the new fields ``aux_head`` and ``aux_tail``
for the head and tail pointers of the AUX ring buffer.

During the initialisation phase, besides the mmap()-ed regular ring
buffer, the perf tool invokes a second syscall in the
``auxtrace_mmap__mmap()`` function for the mmap of the AUX buffer with
non-zero file offset; ``rb_alloc_aux()`` in the kernel allocates pages
correspondingly, these pages will be deferred to map into VMA when
handling the page fault, which is the same lazy mechanism with the
regular ring buffer.

AUX events and AUX trace data are two different things.  Let's see an
example::

        perf record -a -e cycles -e cs_etm// -- sleep 2

The above command enables two events: one is the event *cycles* from PMU
and another is the AUX event *cs_etm* from Arm CoreSight, both are saved
into the regular ring buffer while the CoreSight's AUX trace data is
stored in the AUX ring buffer.

As a result, we can see the regular ring buffer and the AUX ring buffer
are allocated in pairs.  The perf in default mode allocates the regular
ring buffer and the AUX ring buffer per CPU-wise, which is the same as
the system wide mode, however, the default mode records samples only for
the profiled program, whereas the latter mode profiles for all programs
in the system.  For per-thread mode, the perf tool allocates only one
regular ring buffer and one AUX ring buffer for the whole session.  For
the per-CPU mode, the perf allocates two kinds of ring buffers for
selected CPUs specified by the option ``-C``.

The below figure demonstrates the buffers' layout in the system wide
mode; if there are any activities on one CPU, the AUX event samples and
the hardware trace data will be recorded into the dedicated buffers for
the CPU.

::

              T1                      T2                 T1
            +----+              +-----------+          +----+
    CPU0    |xxxx|              |xxxxxxxxxxx|          |xxxx|
            +----+--------------+-----------+----------+----+-------->
              |                       |                  |
              v                       v                  v
            +-----------------------------------------------------+
            |                  Ring buffer 0                      |
            +-----------------------------------------------------+
              |                       |                  |
              v                       v                  v
            +-----------------------------------------------------+
            |               AUX Ring buffer 0                     |
            +-----------------------------------------------------+

                   T1
                 +-----+
    CPU1         |xxxxx|
            -----+-----+--------------------------------------------->
                    |
                    v
            +-----------------------------------------------------+
            |                  Ring buffer 1                      |
            +-----------------------------------------------------+
                    |
                    v
            +-----------------------------------------------------+
            |               AUX Ring buffer 1                     |
            +-----------------------------------------------------+

                                        T1              T3
                                      +----+        +-------+
    CPU2                              |xxxx|        |xxxxxxx|
            --------------------------+----+--------+-------+-------->
                                        |               |
                                        v               v
            +-----------------------------------------------------+
            |                  Ring buffer 2                      |
            +-----------------------------------------------------+
                                        |               |
                                        v               v
            +-----------------------------------------------------+
            |               AUX Ring buffer 2                     |
            +-----------------------------------------------------+

                              T1
                       +--------------+
    CPU3               |xxxxxxxxxxxxxx|
            -----------+--------------+------------------------------>
                              |
                              v
            +-----------------------------------------------------+
            |                  Ring buffer 3                      |
            +-----------------------------------------------------+
                              |
                              v
            +-----------------------------------------------------+
            |               AUX Ring buffer 3                     |
            +-----------------------------------------------------+

            T1: Thread 1; T2: Thread 2; T3: Thread 3
            x: Thread is in running state

                Figure 8. AUX ring buffer for system wide mode

3.2 AUX event

719-760

일반 ring buffer의 `perf_output_begin()`과 `perf_output_end()`에 대응해 `perf_aux_output_begin()`과 `perf_aux_output_end()`이 AUX buffer의 hardware trace data 처리를 담당합니다.

하드웨어가 AUX ring buffer에 trace data를 저장하면 PMU driver는 `pmu::stop()` callback으로 추적을 중지합니다. AUX buffer에도 앞서 설명한 메모리 동기화가 필요합니다. 특히 trace data가 외부에 보인 뒤 head를 갱신하도록 하는 write barrier B는 AUX buffer를 관리하는 PMU driver가 구현해야 합니다.

그 뒤 `pmu::stop()`은 안전하게 `perf_aux_output_end()`를 호출해 두 작업을 마칩니다.

perf_aux_output_end()의 두 결과
결과내용
`PERF_RECORD_AUX` 생성AUX ring buffer에 저장된 hardware trace data 구간의 시작 주소와 크기를 일반 ring buffer에 기록
`perf_buffer::aux_head` 갱신`size`가 나타내는 하드웨어 소비 바이트 수를 반영해 최신 AUX buffer 사용량 공개

일반 buffer의 메타데이터와 AUX buffer의 사용량을 함께 갱신합니다.

마지막에 PMU driver가 하드웨어 추적을 다시 시작합니다. 일시 중지 동안 trace data가 손실되어 decoding 단계에 불연속이 생깁니다.

`PERF_RECORD_AUX`는 커널이 처리하는 AUX event이지만 perf file에 AUX trace data를 저장하기 위한 정보는 부족합니다. perf 도구는 AUX buffer의 데이터를 perf data file로 복사할 때 `PERF_RECORD_AUXTRACE` event를 합성합니다. 이것은 kernel ABI가 아니라 perf 도구가 저장된 AUX 구간을 설명하기 위해 정의한 형식입니다.

이후 perf는 `PERF_RECORD_AUXTRACE`를 바탕으로 perf file에서 AUX trace data를 읽고, `PERF_RECORD_AUX`와 시간 순서를 연계해 데이터 구간을 decode합니다.

3.2 AUX events
--------------

Similar to ``perf_output_begin()`` and ``perf_output_end()``'s working for the
regular ring buffer, ``perf_aux_output_begin()`` and ``perf_aux_output_end()``
serve for the AUX ring buffer for processing the hardware trace data.

Once the hardware trace data is stored into the AUX ring buffer, the PMU
driver will stop hardware tracing by calling the ``pmu::stop()`` callback.
Similar to the regular ring buffer, the AUX ring buffer needs to apply
the memory synchronization mechanism as discussed in the section
:ref:`memory_synchronization`.  Since the AUX ring buffer is managed by the
PMU driver, the barrier (B), which is a writing barrier to ensure the trace
data is externally visible prior to updating the head pointer, is asked
to be implemented in the PMU driver.

Then ``pmu::stop()`` can safely call the ``perf_aux_output_end()`` function to
finish two things:

- It fills an event ``PERF_RECORD_AUX`` into the regular ring buffer, this
  event delivers the information of the start address and data size for a
  chunk of hardware trace data has been stored into the AUX ring buffer;

- Since the hardware trace driver has stored new trace data into the AUX
  ring buffer, the argument *size* indicates how many bytes have been
  consumed by the hardware tracing, thus ``perf_aux_output_end()`` updates the
  header pointer ``perf_buffer::aux_head`` to reflect the latest buffer usage.

At the end, the PMU driver will restart hardware tracing.  During this
temporary suspending period, it will lose hardware trace data, which
will introduce a discontinuity during decoding phase.

The event ``PERF_RECORD_AUX`` presents an AUX event which is handled in the
kernel, but it lacks the information for saving the AUX trace data in
the perf file.  When the perf tool copies the trace data from AUX ring
buffer to the perf data file, it synthesizes a ``PERF_RECORD_AUXTRACE``
event which is not a kernel ABI, it's defined by the perf tool to describe
which portion of data in the AUX ring buffer is saved.  Afterwards, the perf
tool reads out the AUX trace data from the perf file based on the
``PERF_RECORD_AUXTRACE`` events, and the ``PERF_RECORD_AUX`` event is used to
decode a chunk of data by correlating with time order.

3.3 Snapshot 모드

761-830

perf의 AUX ring buffer snapshot 모드는 사용자가 관심 있는 특정 시점의 AUX trace data만 기록합니다. 다음 예시는 Arm CoreSight로 1초 간격 snapshot을 얻습니다.

perf record -e cs_etm//u -S -a program &
PERFPID=$!
while true; do
    kill -USR2 $PERFPID
    sleep 1
done
Snapshot 주 흐름
Before snapshot, AUX ring buffer runs freely without recording AUX events or trace data to the perf fileUSR2 triggers auxtrace_record::snapshot_start() and hardware tracing is deactivatedDriver populates AUX data and writes PERF_RECORD_AUX to the regular ring bufferrecord__read_auxtrace_snapshot() copies the AUX snapshot into the perf data fileauxtrace_record::snapshot_finish() restarts the PMU AUX event

free-run 추적을 잠시 멈추고 AUX 데이터를 파일에 보존한 뒤 다시 시작합니다.

snapshot 모드에서 perf는 `perf_event_mmap_page::aux_head`만 접근하고 `aux_tail`은 건드리지 않습니다. free-run 중 AUX ring buffer가 overflow할 수 있어 tail이 유용하지 않기 때문입니다.

대신 `auxtrace_record::find_snapshot()` callback이 AUX ring buffer의 wrap-around 여부를 판단하고, trace data 크기 계산에 사용할 AUX head를 보정합니다.

buffer는 per-thread, per-CPU, system-wide로 배치될 수 있으며 snapshot은 어느 모드에도 적용할 수 있습니다.

Figure 9. System-wide snapshot
CPUAUX buffersnapshot 경계
CPU0AUX Ring buffer 0buffer 0의 aux_head
CPU1AUX Ring buffer 1buffer 1의 aux_head
CPU2AUX Ring buffer 2buffer 2의 aux_head
CPU3AUX Ring buffer 3buffer 3의 aux_head

snapshot 시점의 각 CPU별 `aux_head`까지를 독립적으로 고정해 읽습니다.

3.3 Snapshot mode
-----------------

Perf supports snapshot mode for AUX ring buffer, in this mode, users
only record AUX trace data at a specific time point which users are
interested in.  E.g. below gives an example of how to take snapshots
with 1 second interval with Arm CoreSight::

  perf record -e cs_etm//u -S -a program &
  PERFPID=$!
  while true; do
      kill -USR2 $PERFPID
      sleep 1
  done

The main flow for snapshot mode is:

- Before a snapshot is taken, the AUX ring buffer acts in free run mode.
  During free run mode the perf doesn't record any of the AUX events and
  trace data;

- Once the perf tool receives the *USR2* signal, it triggers the callback
  function ``auxtrace_record::snapshot_start()`` to deactivate hardware
  tracing.  The kernel driver then populates the AUX ring buffer with the
  hardware trace data, and the event ``PERF_RECORD_AUX`` is stored in the
  regular ring buffer;

- Then perf tool takes a snapshot, ``record__read_auxtrace_snapshot()``
  reads out the hardware trace data from the AUX ring buffer and saves it
  into perf data file;

- After the snapshot is finished, ``auxtrace_record::snapshot_finish()``
  restarts the PMU event for AUX tracing.

The perf only accesses the head pointer ``perf_event_mmap_page::aux_head``
in snapshot mode and doesn’t touch tail pointer ``aux_tail``, this is
because the AUX ring buffer can overflow in free run mode, the tail
pointer is useless in this case.  Alternatively, the callback
``auxtrace_record::find_snapshot()`` is introduced for making the decision
of whether the AUX ring buffer has been wrapped around or not, at the
end it fixes up the AUX buffer's head which are used to calculate the
trace data size.

As we know, the buffers' deployment can be per-thread mode, per-CPU
mode, or system wide mode, and the snapshot can be applied to any of
these modes.  Below is an example of taking snapshot with system wide
mode.

::

                                         Snapshot is taken
                                                 |
                                                 v
                        +------------------------+
                        |  AUX Ring buffer 0     | <- aux_head
                        +------------------------+
                                                 v
                +--------------------------------+
                |          AUX Ring buffer 1     | <- aux_head
                +--------------------------------+
                                                 v
    +--------------------------------------------+
    |                      AUX Ring buffer 2     | <- aux_head
    +--------------------------------------------+
                                                 v
         +---------------------------------------+
         |                 AUX Ring buffer 3     | <- aux_head
         +---------------------------------------+

                Figure 9. Snapshot with system wide mode