.. 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. Introduction=============== The ring buffer is a fundamental mechanism for data transfer. perf usesring buffers to transfer event data from kernel to user space, anotherkind of ring buffer which is so called auxiliary (AUX) ring buffer alsoplays an important role for hardware tracing with Intel PT, ArmCoreSight, etc. The ring buffer implementation is critical but it's also a verychallenging work. On the one hand, the kernel and perf tool in the userspace use the ring buffer to exchange data and stores data into datafile, thus the ring buffer needs to transfer data with high throughput;on the other hand, the ring buffer management should avoid significantoverload to distract profiling results. This documentation dives into the details for perf ring buffer with twoparts: firstly it explains the perf ring buffer implementation, then thesecond part discusses the AUX ring buffer mechanism. 2. Ring buffer implementation============================= 2.1 Basic algorithm------------------- That said, a typical ring buffer is managed by a head pointer and a tailpointer; the head pointer is manipulated by a writer and the tailpointer 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 implementationthere are two key data structures held together in a set of consecutivepages, the control structure and then the ring buffer itself. The pagewith the control structure in is known as the "user page". Being heldin continuous virtual addresses simplifies locating the ring bufferaddress, it is in the pages after the page with the user page. The control structure is named as ``perf_event_mmap_page``, it contains ahead pointer ``data_head`` and a tail pointer ``data_tail``. When thekernel starts to fill records into the ring buffer, it updates the headpointer to reserve the memory so later it can safely store events intothe 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 consumingdata from the ring buffer. Yet another case is for the user page'sread-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 sizewith option ``-m`` or ``--mmap-pages=``, the given size will be rounded upto a power of two that is a multiple of a page size. Though the kernelallocates at once for all memory pages, it's deferred to map the pagesto 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 userspace in the perf tool, a data abort exception for page fault is takenand the kernel uses this occasion to map the page into process VMA(see ``perf_mmap_fault()``), thus the perf tool can continue to accessthe page after returning from the exception. 2.2 Ring buffer for different tracing modes------------------------------------------- The perf profiles programs with different modes: default mode, per threadmode, per cpu mode, and system wide mode. This section describes thesemodes and how the ring buffer meets requirements for them. At last wewill review the race conditions caused by these modes. 2.2.1 Default mode^^^^^^^^^^^^^^^^^^ Usually we execute ``perf record`` command followed by a profiling programname, like below command:: perf record test_program This command doesn't specify any options for CPU and thread modes, theperf tool applies the default mode on the perf event. It maps all theCPUs in the system and the profiled program's PID on the perf event, andit enables inheritance mode on the event so that child tasks inheritsthe 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 ringbuffers. As shown below, the perf tool allocates individual ring bufferfor each CPU, but it only enables events for the profiled program ratherthan for all threads in the system. The *T1* thread represents thethread context of the 'test_program', whereas *T2* and *T3* are irrelevantthreads in the system. The perf samples are exclusively collected forthe *T1* thread and stored in the ring buffer associated with the CPU onwhich 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 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 theprofiled 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 beenabled; and if the thread is scheduled out from the CPU, the events onthe CPU will be disabled. When the thread is migrated from one CPU toanother, the events are to be disabled on the previous CPU and enabledon 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 theprofiled thread *T1*. The ring buffer is dedicated for thread *T1*, if thethread *T1* is running, the perf events will be recorded into the ringbuffer; when the thread is sleeping, all associated events will bedisabled, thus no trace data will be recorded into the ring buffer. 2.2.3 Per-CPU mode^^^^^^^^^^^^^^^^^^ The option ``-C`` is used to collect samples on the list of CPUs, forexample 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 anyPID. 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 CPU0and CPU2, and be terminated until test_program exits. Even there have tasksrunning on CPU1 and CPU3, since the ring buffer is absent for them, anyactivities on these two CPUs will be ignored. A usage case is to combine theoptions 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 whenthe 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 mode^^^^^^^^^^^^^^^^^^^^^^ By using option ``–a`` or ``––all–cpus``, perf collects samples on all CPUsfor 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, andit 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 threadsare monitored during the running state and the samples are recorded intothe 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 Accessing buffer-------------------- Based on the understanding of how the ring buffer is allocated invarious modes, this section explains access the ring buffer. 2.3.1 Producer-consumer model^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the Linux kernel, the PMU events can produce samples which are storedinto the ring buffer; the perf command in user space consumes thesamples by reading out data from the ring buffer and finally saves thedata into the file for post analysis. It’s a typical producer-consumermodel for using the ring buffer. The perf process polls on the PMU events and sleeps when no events areincoming. To prevent frequent exchanges between the kernel and userspace, the kernel event core layer introduces a watermark, which isstored in the ``perf_buffer::watermark``. When a sample is recorded intothe ring buffer, and if the used buffer exceeds the watermark, thekernel 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, becausemultiple events might share the same ring buffer for recording samples,the core layer iterates every event associated with the ring buffer andwakes up tasks waiting on the event. This is fulfilled by the kernelfunction ``ring_buffer_wakeup()``. After the perf process is woken up, it starts to check the ring buffersone by one, if it finds any ring buffer containing samples it will readout the samples for statistics or saving into the data file. Given theperf process is able to run on any CPU, this leads to the ring bufferpotentially being accessed from multiple CPUs simultaneously, whichcauses race conditions. The race condition handling is described in thesection :ref:`memory_synchronization`. 2.3.2 Properties of the ring buffers^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Linux kernel supports two write directions for the ring buffer: forward andbackward. The forward writing saves samples from the beginning of the ringbuffer, the backward writing stores data from the end of the ring buffer withthe reversed direction. The perf tool determines the writing direction. Additionally, the tool can map buffers in either read-write mode or read-onlymode 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 toolupdates the ``data_tail`` to indicate the data start position. Combiningwith the head pointer ``data_head``, which works as the end position ofthe current data, the perf tool can easily know where read out the datafrom. Alternatively, in the read-only mode, only the kernel keeps to updatethe ``data_head`` while the user space cannot access the ``data_tail`` dueto the mapping property ``PROT_READ``. As a result, the matrix below illustrates the various combinations ofdirection and mapping characteristics. The perf tool employs two of thesecombinations to support buffer types: the non-overwrite buffer and theoverwritable 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 forwardwriting. It starts to save data from the beginning of the ring bufferand wrap around when overflow, which is used with the read-write mode inthe normal ring buffer. When the consumer doesn't keep up with theproducer, it would lose some data, the kernel keeps how many records itlost and generates the ``PERF_RECORD_LOST`` records in the next timewhen it finds a space in the ring buffer. The overwritable ring buffer uses the backward writing with theread-only mode. It saves the data from the end of the ring buffer andthe ``data_head`` keeps the position of current data, the perf alwaysknows where it starts to read and until the end of the ring buffer, thusit 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 Writing samples into buffer^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When a sample is taken and saved into the ring buffer, the kernelprepares sample fields based on the sample type; then it prepares theinfo for writing ring buffer which is stored in the structureLines 1–500 of 830. Load more
.. 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. 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. 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 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 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 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 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 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 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 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 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 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