ch32_hal/dma/ringbuffer.rs
1#![cfg_attr(gpdma, allow(unused))]
2
3use core::future::poll_fn;
4use core::ops::Range;
5use core::sync::atomic::{compiler_fence, Ordering};
6use core::task::{Poll, Waker};
7
8use super::word::Word;
9
10/// A "read-only" ring-buffer to be used together with the DMA controller which
11/// writes in a circular way, "uncontrolled" to the buffer.
12///
13/// A snapshot of the ring buffer state can be attained by setting the `ndtr` field
14/// to the current register value. `ndtr` describes the current position of the DMA
15/// write.
16///
17/// # Buffer layout
18///
19/// ```text
20/// Without wraparound: With wraparound:
21///
22/// + buf +--- NDTR ---+ + buf +---------- NDTR ----------+
23/// | | | | | |
24/// v v v v v v
25/// +-----------------------------------------+ +-----------------------------------------+
26/// |oooooooooooXXXXXXXXXXXXXXXXoooooooooooooo| |XXXXXXXXXXXXXooooooooooooXXXXXXXXXXXXXXXX|
27/// +-----------------------------------------+ +-----------------------------------------+
28/// ^ ^ ^ ^ ^ ^
29/// | | | | | |
30/// +- start --+ | +- end ------+ |
31/// | | | |
32/// +- end --------------------+ +- start ----------------+
33/// ```
34pub struct ReadableDmaRingBuffer<'a, W: Word> {
35 pub(crate) dma_buf: &'a mut [W],
36 start: usize,
37}
38
39#[derive(Debug, PartialEq)]
40#[cfg_attr(feature = "defmt", derive(defmt::Format))]
41pub struct OverrunError;
42
43pub trait DmaCtrl {
44 /// Get the NDTR register value, i.e. the space left in the underlying
45 /// buffer until the dma writer wraps.
46 fn get_remaining_transfers(&self) -> usize;
47
48 /// Get the transfer completed counter.
49 /// This counter is incremented by the dma controller when NDTR is reloaded,
50 /// i.e. when the writing wraps.
51 fn get_complete_count(&self) -> usize;
52
53 /// Reset the transfer completed counter to 0 and return the value just prior to the reset.
54 fn reset_complete_count(&mut self) -> usize;
55
56 /// Set the waker for a running poll_fn
57 fn set_waker(&mut self, waker: &Waker);
58}
59
60impl<'a, W: Word> ReadableDmaRingBuffer<'a, W> {
61 pub fn new(dma_buf: &'a mut [W]) -> Self {
62 Self { dma_buf, start: 0 }
63 }
64
65 /// Reset the ring buffer to its initial state
66 pub fn clear(&mut self, dma: &mut impl DmaCtrl) {
67 self.start = 0;
68 dma.reset_complete_count();
69 }
70
71 /// The capacity of the ringbuffer
72 pub const fn cap(&self) -> usize {
73 self.dma_buf.len()
74 }
75
76 /// The current position of the ringbuffer
77 fn pos(&self, dma: &mut impl DmaCtrl) -> usize {
78 self.cap() - dma.get_remaining_transfers()
79 }
80
81 /// Read an exact number of elements from the ringbuffer.
82 ///
83 /// Returns the remaining number of elements available for immediate reading.
84 /// OverrunError is returned if the portion to be read was overwritten by the DMA controller.
85 ///
86 /// Async/Wake Behavior:
87 /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point,
88 /// and when it wraps around. This means that when called with a buffer of length 'M', when this
89 /// ring buffer was created with a buffer of size 'N':
90 /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source.
91 /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning.
92 pub async fn read_exact(&mut self, dma: &mut impl DmaCtrl, buffer: &mut [W]) -> Result<usize, OverrunError> {
93 let mut read_data = 0;
94 let buffer_len = buffer.len();
95
96 poll_fn(|cx| {
97 dma.set_waker(cx.waker());
98
99 compiler_fence(Ordering::SeqCst);
100
101 match self.read(dma, &mut buffer[read_data..buffer_len]) {
102 Ok((len, remaining)) => {
103 read_data += len;
104 if read_data == buffer_len {
105 Poll::Ready(Ok(remaining))
106 } else {
107 Poll::Pending
108 }
109 }
110 Err(e) => Poll::Ready(Err(e)),
111 }
112 })
113 .await
114 }
115
116 /// Read elements from the ring buffer
117 /// Return a tuple of the length read and the length remaining in the buffer
118 /// If not all of the elements were read, then there will be some elements in the buffer remaining
119 /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read
120 /// OverrunError is returned if the portion to be read was overwritten by the DMA controller.
121 pub fn read(&mut self, dma: &mut impl DmaCtrl, buf: &mut [W]) -> Result<(usize, usize), OverrunError> {
122 /*
123 This algorithm is optimistic: we assume we haven't overrun more than a full buffer and then check
124 after we've done our work to see we have. This is because on stm32, an interrupt is not guaranteed
125 to fire in the same clock cycle that a register is read, so checking get_complete_count early does
126 not yield relevant information.
127
128 Therefore, the only variable we really need to know is ndtr. If the dma has overrun by more than a full
129 buffer, we will do a bit more work than we have to, but algorithms should not be optimized for error
130 conditions.
131
132 After we've done our work, we confirm that we haven't overrun more than a full buffer, and also that
133 the dma has not overrun within the data we could have copied. We check the data we could have copied
134 rather than the data we actually copied because it costs nothing and confirms an error condition
135 earlier.
136 */
137 let end = self.pos(dma);
138 if self.start == end && dma.get_complete_count() == 0 {
139 // No elements are available in the buffer
140 Ok((0, self.cap()))
141 } else if self.start < end {
142 // The available, unread portion in the ring buffer DOES NOT wrap
143 // Copy out the elements from the dma buffer
144 let len = self.copy_to(buf, self.start..end);
145
146 compiler_fence(Ordering::SeqCst);
147
148 /*
149 first, check if the dma has wrapped at all if it's after end
150 or more than once if it's before start
151
152 this is in a critical section to try to reduce mushy behavior.
153 it's not ideal but it's the best we can do
154
155 then, get the current position of of the dma write and check
156 if it's inside data we could have copied
157 */
158 let (pos, complete_count) = critical_section::with(|_| (self.pos(dma), dma.get_complete_count()));
159 if (pos >= self.start && pos < end) || (complete_count > 0 && pos >= end) || complete_count > 1 {
160 Err(OverrunError)
161 } else {
162 self.start = (self.start + len) % self.cap();
163
164 Ok((len, self.cap() - self.start))
165 }
166 } else if self.start + buf.len() < self.cap() {
167 // The available, unread portion in the ring buffer DOES wrap
168 // The DMA writer has wrapped since we last read and is currently
169 // writing (or the next byte added will be) in the beginning of the ring buffer.
170
171 // The provided read buffer is not large enough to include all elements from the tail of the dma buffer.
172
173 // Copy out from the dma buffer
174 let len = self.copy_to(buf, self.start..self.cap());
175
176 compiler_fence(Ordering::SeqCst);
177
178 /*
179 first, check if the dma has wrapped around more than once
180
181 then, get the current position of of the dma write and check
182 if it's inside data we could have copied
183 */
184 let pos = self.pos(dma);
185 if pos > self.start || pos < end || dma.get_complete_count() > 1 {
186 Err(OverrunError)
187 } else {
188 self.start = (self.start + len) % self.cap();
189
190 Ok((len, self.start + end))
191 }
192 } else {
193 // The available, unread portion in the ring buffer DOES wrap
194 // The DMA writer has wrapped since we last read and is currently
195 // writing (or the next byte added will be) in the beginning of the ring buffer.
196
197 // The provided read buffer is large enough to include all elements from the tail of the dma buffer,
198 // so the next read will not have any unread tail elements in the ring buffer.
199
200 // Copy out from the dma buffer
201 let tail = self.copy_to(buf, self.start..self.cap());
202 let head = self.copy_to(&mut buf[tail..], 0..end);
203
204 compiler_fence(Ordering::SeqCst);
205
206 /*
207 first, check if the dma has wrapped around more than once
208
209 then, get the current position of of the dma write and check
210 if it's inside data we could have copied
211 */
212 let pos = self.pos(dma);
213 if pos > self.start || pos < end || dma.reset_complete_count() > 1 {
214 Err(OverrunError)
215 } else {
216 self.start = head;
217 Ok((tail + head, self.cap() - self.start))
218 }
219 }
220 }
221 /// Copy from the dma buffer at `data_range` into `buf`
222 fn copy_to(&mut self, buf: &mut [W], data_range: Range<usize>) -> usize {
223 // Limit the number of elements that can be copied
224 let length = usize::min(data_range.len(), buf.len());
225
226 // Copy from dma buffer into read buffer
227 // We need to do it like this instead of a simple copy_from_slice() because
228 // reading from a part of memory that may be simultaneously written to is unsafe
229 unsafe {
230 let dma_buf = self.dma_buf.as_ptr();
231
232 for i in 0..length {
233 buf[i] = core::ptr::read_volatile(dma_buf.offset((data_range.start + i) as isize));
234 }
235 }
236
237 length
238 }
239}
240
241pub struct WritableDmaRingBuffer<'a, W: Word> {
242 pub(crate) dma_buf: &'a mut [W],
243 end: usize,
244}
245
246impl<'a, W: Word> WritableDmaRingBuffer<'a, W> {
247 pub fn new(dma_buf: &'a mut [W]) -> Self {
248 Self { dma_buf, end: 0 }
249 }
250
251 /// Reset the ring buffer to its initial state
252 pub fn clear(&mut self, dma: &mut impl DmaCtrl) {
253 self.end = 0;
254 dma.reset_complete_count();
255 }
256
257 /// The capacity of the ringbuffer
258 pub const fn cap(&self) -> usize {
259 self.dma_buf.len()
260 }
261
262 /// The current position of the ringbuffer
263 fn pos(&self, dma: &mut impl DmaCtrl) -> usize {
264 self.cap() - dma.get_remaining_transfers()
265 }
266
267 /// Write elements directly to the buffer. This must be done before the DMA is started
268 /// or after the buffer has been cleared using `clear()`.
269 pub fn write_immediate(&mut self, buffer: &[W]) -> Result<(usize, usize), OverrunError> {
270 if self.end != 0 {
271 return Err(OverrunError);
272 }
273 let written = self.copy_from(buffer, 0..self.cap());
274 self.end = written % self.cap();
275 Ok((written, self.cap() - written))
276 }
277
278 /// Write an exact number of elements to the ringbuffer.
279 pub async fn write_exact(&mut self, dma: &mut impl DmaCtrl, buffer: &[W]) -> Result<usize, OverrunError> {
280 let mut written_data = 0;
281 let buffer_len = buffer.len();
282
283 poll_fn(|cx| {
284 dma.set_waker(cx.waker());
285
286 compiler_fence(Ordering::SeqCst);
287
288 match self.write(dma, &buffer[written_data..buffer_len]) {
289 Ok((len, remaining)) => {
290 written_data += len;
291 if written_data == buffer_len {
292 Poll::Ready(Ok(remaining))
293 } else {
294 Poll::Pending
295 }
296 }
297 Err(e) => Poll::Ready(Err(e)),
298 }
299 })
300 .await
301 }
302
303 /// Write elements from the ring buffer
304 /// Return a tuple of the length written and the capacity remaining to be written in the buffer
305 pub fn write(&mut self, dma: &mut impl DmaCtrl, buf: &[W]) -> Result<(usize, usize), OverrunError> {
306 let start = self.pos(dma);
307 if start > self.end {
308 // The occupied portion in the ring buffer DOES wrap
309 let len = self.copy_from(buf, self.end..start);
310
311 compiler_fence(Ordering::SeqCst);
312
313 // Confirm that the DMA is not inside data we could have written
314 let (pos, complete_count) = critical_section::with(|_| (self.pos(dma), dma.get_complete_count()));
315 if (pos >= self.end && pos < start) || (complete_count > 0 && pos >= start) || complete_count > 1 {
316 Err(OverrunError)
317 } else {
318 self.end = (self.end + len) % self.cap();
319
320 Ok((len, self.cap() - (start - self.end)))
321 }
322 } else if start == self.end && dma.get_complete_count() == 0 {
323 Ok((0, 0))
324 } else if start <= self.end && self.end + buf.len() < self.cap() {
325 // The occupied portion in the ring buffer DOES NOT wrap
326 // and copying elements into the buffer WILL NOT cause it to
327
328 // Copy into the dma buffer
329 let len = self.copy_from(buf, self.end..self.cap());
330
331 compiler_fence(Ordering::SeqCst);
332
333 // Confirm that the DMA is not inside data we could have written
334 let pos = self.pos(dma);
335 if pos > self.end || pos < start || dma.get_complete_count() > 1 {
336 Err(OverrunError)
337 } else {
338 self.end = (self.end + len) % self.cap();
339
340 Ok((len, self.cap() - (self.end - start)))
341 }
342 } else {
343 // The occupied portion in the ring buffer DOES NOT wrap
344 // and copying elements into the buffer WILL cause it to
345
346 let tail = self.copy_from(buf, self.end..self.cap());
347 let head = self.copy_from(&buf[tail..], 0..start);
348
349 compiler_fence(Ordering::SeqCst);
350
351 // Confirm that the DMA is not inside data we could have written
352 let pos = self.pos(dma);
353 if pos > self.end || pos < start || dma.reset_complete_count() > 1 {
354 Err(OverrunError)
355 } else {
356 self.end = head;
357
358 Ok((tail + head, self.cap() - (start - self.end)))
359 }
360 }
361 }
362 /// Copy into the dma buffer at `data_range` from `buf`
363 fn copy_from(&mut self, buf: &[W], data_range: Range<usize>) -> usize {
364 // Limit the number of elements that can be copied
365 let length = usize::min(data_range.len(), buf.len());
366
367 // Copy into dma buffer from read buffer
368 // We need to do it like this instead of a simple copy_from_slice() because
369 // reading from a part of memory that may be simultaneously written to is unsafe
370 unsafe {
371 let dma_buf = self.dma_buf.as_mut_ptr();
372
373 for i in 0..length {
374 core::ptr::write_volatile(dma_buf.offset((data_range.start + i) as isize), buf[i]);
375 }
376 }
377
378 length
379 }
380}