Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. pw_kernel_tracing/buffer.rs

pw_kernel_tracing/
buffer.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use core::cell::UnsafeCell;
16use core::sync::atomic::Ordering;
17
18use crate::{EventType, Record};
19
20/// A single entry in the trace buffer.
21#[allow(dead_code)]
22#[repr(C)]
23struct RecordEntry([u32; 4]);
24impl RecordEntry {
25    pub const fn new() -> Self {
26        Self([0u32; 4])
27    }
28}
29
30/// A circular buffer for storing trace records.
31///
32/// The buffer uses atomic operations to manage a write position, allowing multiple
33/// producers to write concurrently without locking.
34///
35/// # Type Parameters
36/// * `AtomicUsize`: The atomic type used for the position counter (e.g., `pw_atomic::AtomicUsize`).
37/// * `NUM_ENTRIES`: The number of entries in the buffer.
38pub struct Buffer<AtomicUsize: pw_atomic::AtomicUsize, const NUM_ENTRIES: usize> {
39    records: UnsafeCell<[RecordEntry; NUM_ENTRIES]>,
40    pos: AtomicUsize,
41}
42
43/// Safety: The buffer is safe to share across threads because:
44/// 1. `pos` is an `AtomicUsize` which handles concurrent updates safely.
45/// 2. `records` is accessed via `UnsafeCell`, but the protocol for writing ensures
46///    that each slot is effectively owned by a single writer at a time (barring wraparound collisions).
47unsafe impl<AtomicUsize: pw_atomic::AtomicUsize, const NUM_ENTRIES: usize> Sync
48    for Buffer<AtomicUsize, NUM_ENTRIES>
49{
50}
51
52impl<AtomicUsize: pw_atomic::AtomicUsize, const NUM_ENTRIES: usize>
53    Buffer<AtomicUsize, NUM_ENTRIES>
54{
55    /// Creates a new, empty buffer.
56    #[must_use]
57    pub const fn new() -> Self {
58        Self {
59            records: UnsafeCell::new([const { RecordEntry::new() }; NUM_ENTRIES]),
60            pos: AtomicUsize::ZERO,
61        }
62    }
63
64    /// Returns the total size of the buffer in bytes.
65    pub const fn buffer_len(&self) -> usize {
66        NUM_ENTRIES * core::mem::size_of::<RecordEntry>()
67    }
68
69    /// Returns a raw pointer to the underlying buffer storage.
70    ///
71    /// # Safety
72    /// This provides direct access to the raw buffer storage. The caller must ensure
73    /// that they do not violate any safety guarantees, especially if reading while
74    /// other threads are writing.
75    pub const unsafe fn buffer(&self) -> *const () {
76        self.records.get() as *const ()
77    }
78
79    /// Adds a record to the buffer.
80    ///
81    /// This method reserves a slot in the circular buffer using atomic operations
82    /// and writes the record data.
83    ///
84    /// # Arguments
85    /// * `time_stamp`: The timestamp of the event.
86    /// * `event_type`: The type of event.
87    /// * `event_data`: The raw payload of the event.
88    ///
89    /// # Example
90    /// ```
91    /// use pw_kernel_tracing::{Buffer, EventType, ContextSwitchEvent};
92    /// use core::sync::atomic::AtomicUsize;
93    ///
94    /// let buffer = Buffer::<AtomicUsize, 4>::new();
95    /// let event = ContextSwitchEvent {
96    ///     old_thread_id: 1,
97    ///     new_thread_id: 2,
98    ///     old_thread_state: 3,
99    /// };
100    /// buffer.add_record(0x1234, EventType::ContextSwitch, event.encode());
101    /// ```
102    pub fn add_record(&self, time_stamp: u32, event_type: EventType, event_data: [u32; 3]) {
103        let pos = loop {
104            let pos = self.pos.load(Ordering::SeqCst);
105            let next_pos = (pos + 1) % NUM_ENTRIES;
106            if self
107                .pos
108                .compare_exchange(pos, next_pos, Ordering::SeqCst, Ordering::SeqCst)
109                .is_ok()
110            {
111                break pos;
112            }
113        };
114
115        let record = Record {
116            event_type,
117            time_stamp,
118            event_data,
119        };
120
121        // Safety:
122        // * The offset into the records array is guaranteed to be in bounds
123        //   because it is bounds checked above.
124        // * "Reasonable" exclusive access can be assumed because entries written
125        //   as soon as their storage is reserved. This makes the likelihood of
126        //   the trace buffer wrapping before the entry is re-written extremely
127        //   low.
128        // * In the unlikely event that the buffer wraps and an entry is corrupted,
129        //   the reader of the trace buffer is expected to handle the corrupted
130        //   entry.
131
132        unsafe {
133            let entry = self.records.get().cast::<RecordEntry>().add(pos);
134            *entry = RecordEntry(record.encode());
135        }
136    }
137}
138
139// These tests require an implementation of core::atomic.
140#[cfg(all(test, feature = "builtin_atomics"))]
141mod tests {
142    use core::sync::atomic::AtomicUsize as StdAtomicUsize;
143
144    use unittest::test;
145
146    use super::*;
147    // Helper to access private records for testing
148    impl<AtomicUsize: pw_atomic::AtomicUsize, const NUM_ENTRIES: usize>
149        Buffer<AtomicUsize, NUM_ENTRIES>
150    {
151        fn get_record_entry(&self, index: usize) -> &RecordEntry {
152            unsafe { &(*self.records.get())[index] }
153        }
154    }
155
156    #[test]
157    fn add_record_writes_to_buffer() -> unittest::Result<()> {
158        let buffer = Buffer::<StdAtomicUsize, 4>::new();
159
160        buffer.add_record(0x123456, EventType::ContextSwitch, [1, 2, 3]);
161
162        let entry = buffer.get_record_entry(0);
163        let header = entry.0[0];
164        let timestamp = header & 0x03ff_ffff;
165        let event_type_val = (header >> 26) & 0x3f;
166
167        unittest::assert_eq!(timestamp, 0x123456);
168        unittest::assert_eq!(event_type_val, EventType::ContextSwitch as u32);
169        unittest::assert_eq!(entry.0[1], 1);
170        unittest::assert_eq!(entry.0[2], 2);
171        unittest::assert_eq!(entry.0[3], 3);
172
173        Ok(())
174    }
175
176    #[test]
177    fn buffer_wraps_around() -> unittest::Result<()> {
178        let buffer = Buffer::<StdAtomicUsize, 2>::new();
179
180        buffer.add_record(0x100, EventType::ContextSwitch, [1, 1, 1]);
181        buffer.add_record(0x200, EventType::ContextSwitch, [2, 2, 2]);
182        buffer.add_record(0x300, EventType::ContextSwitch, [3, 3, 3]); // Should overwrite index 0
183
184        // Check index 0 (should be [3,3,3])
185        let entry0 = buffer.get_record_entry(0);
186        unittest::assert_eq!(entry0.0[1], 3);
187
188        // Check index 1 (should be [2,2,2])
189        let entry1 = buffer.get_record_entry(1);
190        unittest::assert_eq!(entry1.0[1], 2);
191
192        Ok(())
193    }
194
195    #[test]
196    fn buffer_allocates_slots_correctly() -> unittest::Result<()> {
197        let buffer = Buffer::<StdAtomicUsize, 4>::new();
198
199        // internal position should be 0
200        unittest::assert_eq!(buffer.pos.load(Ordering::SeqCst), 0);
201
202        buffer.add_record(0x0, EventType::ContextSwitch, [0; 3]);
203        // internal position should be 1
204        unittest::assert_eq!(buffer.pos.load(Ordering::SeqCst), 1);
205
206        buffer.add_record(0x1, EventType::ContextSwitch, [0; 3]);
207        buffer.add_record(0x2, EventType::ContextSwitch, [0; 3]);
208        buffer.add_record(0x3, EventType::ContextSwitch, [0; 3]);
209        // Should wrap to 0
210        unittest::assert_eq!(buffer.pos.load(Ordering::SeqCst), 0);
211
212        Ok(())
213    }
214}