xarxa-driver 0.2.0

Driver trait for the `xarxa` network stack.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Owned packet buffers.
//!
//! A [`DriverBuf`] is a packet buffer on its way to or from a device: one
//! buffer, owned by whoever holds it.
//!
//! Buffers come from the network stack's pool. A driver gets the buffers it
//! receives frames into from the stack, with
//! [`Driver::rx_give`](crate::Driver::rx_give). Dropping a buffer gives it back
//! to the pool it came from.

use core::fmt;
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;

use crate::meta::PacketMeta;

/// The bookkeeping of one [`DriverBuf`]: where its storage is, its headroom and
/// length, its metadata, and how to free it.
///
/// Only pool implementations deal with this type. They keep one for each buffer,
/// fill it in, and pass it to [`DriverBuf::from_raw`].
pub struct RawDriverBuf {
    /// Called with this `RawDriverBuf` when the buffer is dropped. It gives the buffer
    /// back to its pool.
    pub free: unsafe fn(NonNull<RawDriverBuf>),
    /// The address of the pool the buffer belongs to. The pool can use it to find
    /// itself in `free`. [`DriverBuf::pool`] returns it.
    pub pool: *const (),
    /// Start of the storage.
    pub data: NonNull<u8>,
    /// Size of the storage at `data`, in bytes.
    pub capacity: usize,
    /// Offset of the first valid byte within the storage.
    pub headroom: usize,
    /// Number of valid bytes.
    pub len: usize,
    /// Per-packet metadata. Zero-sized unless a `packetmeta-*` feature is enabled.
    pub meta: PacketMeta,
}

/// An owned network packet buffer, on its way to or from a device.
///
/// ```text
/// | headroom | data (len) | tailroom |
/// ```
///
/// Dropping it gives it back to the pool it came from.
///
/// A driver must not keep one for long, unless it sits in its receive ring.
/// A buffer from [`Driver::transmit`](crate::Driver::transmit) must be sent and
/// dropped, dropped, or handed back to the network stack, in bounded time,
/// without waiting for the network or the application. The network stack keeps
/// buffers free for what has to go out, and counts on getting them back.
pub struct DriverBuf {
    raw: NonNull<RawDriverBuf>,
}

// SAFETY: a `DriverBuf` is the unique owner of its `RawDriverBuf` and storage, like a
// `Box` of them. Its `free` can be called from any thread (see `from_raw`).
unsafe impl Send for DriverBuf {}
unsafe impl Sync for DriverBuf {}

impl DriverBuf {
    /// Make a buffer out of a `RawDriverBuf` a pool filled in.
    ///
    /// For pool implementations. Dropping the buffer calls `raw.free` with `raw`.
    ///
    /// A fresh buffer usually has zero `headroom` and `len`, and default `meta`.
    ///
    /// # Safety
    ///
    /// - `raw` must be initialized, and valid for reads and writes until
    ///   `free` is called.
    /// - Its `data` must be valid for reads and writes of `capacity` bytes until
    ///   then. Those bytes must be initialized.
    /// - Its `headroom + len` must be at most `capacity`.
    /// - Nothing else may access `raw` or the storage until `free` is
    ///   called.
    /// - `free` must be safe to call once with `raw`, from any thread, after
    ///   the buffer is dropped.
    pub unsafe fn from_raw(raw: NonNull<RawDriverBuf>) -> Self {
        Self { raw }
    }

    #[inline]
    fn raw(&self) -> &RawDriverBuf {
        // SAFETY: we own the `RawDriverBuf` for as long as `self` exists.
        unsafe { self.raw.as_ref() }
    }

    #[inline]
    fn raw_mut(&mut self) -> &mut RawDriverBuf {
        // SAFETY: we own the `RawDriverBuf` for as long as `self` exists, and `&mut self`
        // makes this the only reference.
        unsafe { self.raw.as_mut() }
    }

    /// The whole storage, ignoring headroom and length.
    #[inline]
    fn storage(&self) -> &[u8] {
        let raw = self.raw();
        // SAFETY: `data` is valid and initialized for `capacity` bytes, and only
        // this buffer accesses it.
        unsafe { core::slice::from_raw_parts(raw.data.as_ptr(), raw.capacity) }
    }

    /// The address of the pool the buffer belongs to.
    ///
    /// Two buffers with the same address come from the same pool.
    pub fn pool(&self) -> *const () {
        self.raw().pool
    }

    /// The packet's metadata.
    ///
    /// On a received packet this is what the driver attached to it. On a packet being
    /// sent it is what the application attached, and what the driver will see in
    /// [`Driver::transmit`](crate::Driver::transmit). It travels with the
    /// buffer through the whole stack, unaffected by header pushes and pulls.
    pub fn meta(&self) -> PacketMeta {
        self.raw().meta
    }

    /// Mutable reference to the packet's metadata.
    pub fn meta_mut(&mut self) -> &mut PacketMeta {
        &mut self.raw_mut().meta
    }

    /// Replace the packet's metadata.
    pub fn set_meta(&mut self, meta: PacketMeta) {
        self.raw_mut().meta = meta;
    }

    /// Total storage capacity of the buffer, in bytes.
    pub fn capacity(&self) -> usize {
        self.raw().capacity
    }

    /// Amount of free space in front of the payload.
    pub fn headroom(&self) -> usize {
        self.raw().headroom
    }

    /// Length of the payload.
    pub fn len(&self) -> usize {
        self.raw().len
    }

    /// Whether the payload is empty.
    pub fn is_empty(&self) -> bool {
        self.raw().len == 0
    }

    /// Amount of free space behind the payload.
    pub fn tailroom(&self) -> usize {
        self.capacity() - self.headroom() - self.len()
    }

    /// Empty the buffer, with `headroom` bytes of room in front of the payload.
    ///
    /// Use it on a new buffer, before writing a payload.
    ///
    /// # Panics
    /// Panics if `headroom > capacity`.
    pub fn reserve(&mut self, headroom: usize) {
        assert!(headroom <= self.capacity());
        let raw = self.raw_mut();
        raw.headroom = headroom;
        raw.len = 0;
    }

    /// Grow the payload at the front by `n` bytes, taking them from the headroom.
    ///
    /// # Panics
    /// Panics if `n > headroom`.
    pub fn push_front(&mut self, n: usize) {
        assert!(n <= self.headroom());
        let raw = self.raw_mut();
        raw.headroom -= n;
        raw.len += n;
    }

    /// Shrink the payload at the front by `n` bytes, returning them to the headroom.
    ///
    /// # Panics
    /// Panics if `n > len`.
    pub fn pull_front(&mut self, n: usize) {
        assert!(n <= self.len());
        let raw = self.raw_mut();
        raw.headroom += n;
        raw.len -= n;
    }

    /// Make room for `headroom` bytes in front of the payload, moving the payload
    /// back if there isn't enough already.
    ///
    /// Returns `false` if the buffer can't fit `headroom` plus the payload, leaving
    /// it unchanged.
    pub fn ensure_headroom(&mut self, headroom: usize) -> bool {
        if self.headroom() >= headroom {
            return true;
        }
        let len = self.len();
        if headroom + len > self.capacity() {
            return false;
        }
        let old = self.headroom();
        self.storage_mut().copy_within(old..old + len, headroom);
        self.raw_mut().headroom = headroom;
        true
    }

    /// Set the payload length, growing or shrinking it at the back.
    ///
    /// This does not clear newly exposed bytes.
    ///
    /// # Panics
    /// Panics if `headroom + len > capacity`.
    pub fn set_len(&mut self, len: usize) {
        assert!(self.headroom() + len <= self.capacity());
        self.raw_mut().len = len;
    }

    /// The whole underlying storage, ignoring headroom and length.
    ///
    /// Its alignment is up to the pool the buffer came from.
    pub fn storage_mut(&mut self) -> &mut [u8] {
        let raw = self.raw_mut();
        // SAFETY: `data` is valid and initialized for `capacity` bytes, and only
        // this buffer accesses it. `&mut self` makes this the only reference.
        unsafe { core::slice::from_raw_parts_mut(raw.data.as_ptr(), raw.capacity) }
    }
}

impl Drop for DriverBuf {
    #[inline(never)] // helps code size
    fn drop(&mut self) {
        let free = self.raw().free;
        // SAFETY: `from_raw` was given this `RawDriverBuf`, and the buffer is never used
        // again.
        unsafe { free(self.raw) }
    }
}

impl Deref for DriverBuf {
    type Target = [u8];
    fn deref(&self) -> &Self::Target {
        let raw = self.raw();
        let start = raw.headroom;
        let len = raw.len;
        // SAFETY: `headroom + len <= capacity`, which every method that changes
        // either of them checks.
        unsafe { self.storage().get_unchecked(start..start + len) }
    }
}

impl DerefMut for DriverBuf {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let raw = self.raw();
        let start = raw.headroom;
        let len = raw.len;
        // SAFETY: `headroom + len <= capacity`, which every method that changes
        // either of them checks.
        unsafe { self.storage_mut().get_unchecked_mut(start..start + len) }
    }
}

impl fmt::Debug for DriverBuf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DriverBuf")
            .field("headroom", &self.headroom())
            .field("len", &self.len())
            .finish()
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for DriverBuf {
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(f, "DriverBuf {{ headroom: {}, len: {} }}", self.headroom(), self.len());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::mem::MaybeUninit;
    use std::boxed::Box;
    use std::sync::Mutex;

    const SIZE: usize = 256;

    /// A pool of heap buffers, freed on drop. Counts what is out.
    struct TestPool {
        out: Mutex<usize>,
    }

    /// One heap buffer. The `RawDriverBuf` comes first, so a pointer to it is a pointer
    /// to the whole thing.
    #[repr(C)]
    struct TestBuf {
        raw: MaybeUninit<RawDriverBuf>,
        data: [u8; SIZE],
    }

    impl TestPool {
        fn alloc(&'static self) -> Option<DriverBuf> {
            *self.out.lock().unwrap() += 1;
            let buf = Box::leak(Box::new(TestBuf {
                raw: MaybeUninit::uninit(),
                data: [0xa5; SIZE],
            }));
            let raw = buf.raw.write(RawDriverBuf {
                free,
                pool: (self as *const TestPool).cast(),
                data: NonNull::from(&mut buf.data).cast(),
                capacity: SIZE,
                headroom: 0,
                len: 0,
                meta: PacketMeta::default(),
            });
            // SAFETY: the allocation is fresh and only given to this buffer.
            // `free` gets back the `RawDriverBuf` of a `TestBuf`.
            Some(unsafe { DriverBuf::from_raw(NonNull::from(raw)) })
        }
    }

    unsafe fn free(raw: NonNull<RawDriverBuf>) {
        // SAFETY: the `RawDriverBuf` is the first field of a `TestBuf` from `Box::leak`,
        // and its pool is a `&'static TestPool`.
        unsafe {
            let pool = &*raw.as_ref().pool.cast::<TestPool>();
            drop(Box::from_raw(raw.cast::<TestBuf>().as_ptr()));
            *pool.out.lock().unwrap() -= 1;
        }
    }

    fn pool() -> &'static TestPool {
        Box::leak(Box::new(TestPool { out: Mutex::new(0) }))
    }

    #[test]
    fn push_pull() {
        let mut buf = pool().alloc().unwrap();
        assert_eq!(buf.len(), 0);
        assert_eq!(buf.headroom(), 0);
        assert_eq!(buf.capacity(), SIZE);
        assert_eq!(buf.tailroom(), SIZE);

        buf.reserve(42);
        assert_eq!(buf.headroom(), 42);
        buf.set_len(100);
        assert_eq!(buf.len(), 100);
        assert_eq!(buf.tailroom(), SIZE - 142);
        buf.fill(0xaa);

        buf.push_front(20);
        assert_eq!(buf.headroom(), 22);
        assert_eq!(buf.len(), 120);
        assert_eq!(buf[20], 0xaa);

        buf.pull_front(20);
        assert_eq!(buf.headroom(), 42);
        assert_eq!(buf.len(), 100);
        assert_eq!(buf[0], 0xaa);
    }

    #[test]
    fn ensure_headroom() {
        let mut buf = pool().alloc().unwrap();
        buf.reserve(10);
        buf.set_len(4);
        buf.copy_from_slice(&[1, 2, 3, 4]);

        // Already enough: nothing moves.
        assert!(buf.ensure_headroom(4));
        assert_eq!(buf.headroom(), 10);
        assert_eq!(&*buf, &[1, 2, 3, 4]);

        // Not enough: the payload moves back, unchanged.
        assert!(buf.ensure_headroom(20));
        assert_eq!(buf.headroom(), 20);
        assert_eq!(buf.len(), 4);
        assert_eq!(&*buf, &[1, 2, 3, 4]);

        // The headroom overlapping the payload is fine, it's a move not a copy.
        assert!(buf.ensure_headroom(22));
        assert_eq!(&*buf, &[1, 2, 3, 4]);

        // Doesn't fit: the buffer is left alone.
        assert!(!buf.ensure_headroom(SIZE - 3));
        assert_eq!(buf.headroom(), 22);
        assert_eq!(&*buf, &[1, 2, 3, 4]);
        assert!(buf.ensure_headroom(SIZE - 4));
        assert_eq!(&*buf, &[1, 2, 3, 4]);
    }

    #[test]
    #[should_panic]
    fn push_beyond_headroom() {
        let mut buf = pool().alloc().unwrap();
        buf.push_front(1);
    }

    /// Dropping a buffer gives it back to the pool it came from.
    #[test]
    fn drop_releases_to_its_pool() {
        let a = pool();
        let b = pool();
        let buf_a = a.alloc().unwrap();
        let buf_b = b.alloc().unwrap();
        assert_eq!(*a.out.lock().unwrap(), 1);
        assert_eq!(*b.out.lock().unwrap(), 1);
        drop(buf_a);
        assert_eq!(*a.out.lock().unwrap(), 0);
        assert_eq!(*b.out.lock().unwrap(), 1);
        drop(buf_b);
        assert_eq!(*b.out.lock().unwrap(), 0);
    }

    /// Metadata rides along with the buffer, untouched by the header pushes and pulls
    /// the packet goes through on its way up or down the stack.
    #[cfg(feature = "packetmeta-id")]
    #[test]
    fn meta_travels_with_the_buffer() {
        let mut buf = pool().alloc().unwrap();
        assert_eq!(buf.meta(), PacketMeta::default());

        buf.meta_mut().id = 0xdead_beef;
        buf.reserve(20);
        buf.set_len(10);
        buf.push_front(20);
        buf.pull_front(4);
        assert_eq!(buf.meta().id, 0xdead_beef);

        buf.set_meta(PacketMeta::default());
        assert_eq!(buf.meta().id, 0);
    }
}