Skip to main content

mana_driver/
queues.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Types to access work, completion, and event queues.
5
6use crate::save_restore::CqEqSavedState;
7use crate::save_restore::DoorbellSavedState;
8use crate::save_restore::WqSavedState;
9use gdma_defs::CLIENT_OOB_8;
10use gdma_defs::CLIENT_OOB_24;
11use gdma_defs::CLIENT_OOB_32;
12use gdma_defs::CqEqDoorbellValue;
13use gdma_defs::Cqe;
14use gdma_defs::DB_CQ;
15use gdma_defs::DB_EQ;
16use gdma_defs::DB_RQ;
17use gdma_defs::DB_SQ;
18use gdma_defs::Eqe;
19use gdma_defs::GdmaQueueType;
20use gdma_defs::OWNER_BITS;
21use gdma_defs::OWNER_MASK;
22use gdma_defs::Sge;
23use gdma_defs::WQE_ALIGNMENT;
24use gdma_defs::WqDoorbellValue;
25use gdma_defs::WqeHeader;
26use gdma_defs::WqeParams;
27use inspect::Inspect;
28use std::marker::PhantomData;
29use std::sync::Arc;
30use std::sync::atomic::Ordering::Acquire;
31use user_driver::memory::MemoryBlock;
32use zerocopy::FromBytes;
33use zerocopy::Immutable;
34use zerocopy::IntoBytes;
35use zerocopy::KnownLayout;
36
37/// An interface to write a doorbell value to signal the device.
38pub trait Doorbell: Send + Sync {
39    /// Returns the maximum page number.
40    fn page_count(&self) -> u32;
41    /// Write a doorbell value at page `page`, offset `address`.
42    fn write(&self, page: u32, address: u32, value: u64);
43    /// Save the doorbell state.
44    fn save(&self, doorbell_id: Option<u64>) -> DoorbellSavedState;
45}
46
47struct NullDoorbell;
48
49impl Doorbell for NullDoorbell {
50    fn page_count(&self) -> u32 {
51        0
52    }
53
54    fn write(&self, _page: u32, _address: u32, _value: u64) {}
55
56    fn save(&self, _doorbell_id: Option<u64>) -> DoorbellSavedState {
57        DoorbellSavedState {
58            doorbell_id: 0,
59            page_count: 0,
60        }
61    }
62}
63
64/// A single GDMA doorbell page.
65#[derive(Clone)]
66pub struct DoorbellPage {
67    doorbell: Arc<dyn Doorbell>,
68    doorbell_id: u32,
69}
70
71impl DoorbellPage {
72    pub(crate) fn null() -> Self {
73        Self {
74            doorbell: Arc::new(NullDoorbell),
75            doorbell_id: 0,
76        }
77    }
78
79    /// Returns a doorbell page at `doorbell_id` the doorbell region.
80    pub fn new(doorbell: Arc<dyn Doorbell>, doorbell_id: u32) -> anyhow::Result<Self> {
81        let page_count = doorbell.page_count();
82        if doorbell_id >= page_count {
83            anyhow::bail!(
84                "doorbell id {} exceeds page count {}",
85                doorbell_id,
86                page_count
87            );
88        }
89        Ok(Self {
90            doorbell,
91            doorbell_id,
92        })
93    }
94
95    /// Writes a doorbell value.
96    pub fn write(&self, address: u32, value: u64) {
97        assert!(address < 4096);
98        self.doorbell.write(self.doorbell_id, address, value);
99    }
100}
101
102/// An event queue.
103#[derive(Inspect)]
104pub struct CqEq<T> {
105    #[inspect(skip)]
106    doorbell: DoorbellPage,
107    #[inspect(skip)]
108    doorbell_addr: u32,
109    #[inspect(skip)]
110    queue_type: GdmaQueueType,
111    #[inspect(skip)]
112    mem: MemoryBlock,
113    id: u32,
114    #[inspect(hex)]
115    next: u32,
116    #[inspect(hex)]
117    size: u32,
118    #[inspect(skip)]
119    shift: u32,
120    _phantom: PhantomData<fn() -> T>,
121}
122
123impl CqEq<Cqe> {
124    /// Creates a new completion queue.
125    pub fn new_cq(mem: MemoryBlock, doorbell: DoorbellPage, id: u32) -> Self {
126        Self::new(GdmaQueueType::GDMA_CQ, DB_CQ, mem, doorbell, id)
127    }
128
129    /// Restores an existing completion queue.
130    pub fn restore_cq(mem: MemoryBlock, state: CqEqSavedState, doorbell: DoorbellPage) -> Self {
131        Self::restore(GdmaQueueType::GDMA_CQ, mem, doorbell, state)
132    }
133}
134
135impl CqEq<Eqe> {
136    /// Creates a new event queue.
137    pub fn new_eq(mem: MemoryBlock, doorbell: DoorbellPage, id: u32) -> Self {
138        Self::new(GdmaQueueType::GDMA_EQ, DB_EQ, mem, doorbell, id)
139    }
140
141    /// Restores an existing event queue.
142    pub fn restore_eq(mem: MemoryBlock, state: CqEqSavedState, doorbell: DoorbellPage) -> Self {
143        Self::restore(GdmaQueueType::GDMA_EQ, mem, doorbell, state)
144    }
145}
146
147impl<T: IntoBytes + FromBytes + Immutable + KnownLayout> CqEq<T> {
148    /// Creates a new queue.
149    fn new(
150        queue_type: GdmaQueueType,
151        doorbell_addr: u32,
152        mem: MemoryBlock,
153        doorbell: DoorbellPage,
154        id: u32,
155    ) -> Self {
156        let size = mem.len();
157        assert!(size.is_power_of_two());
158        Self {
159            doorbell,
160            doorbell_addr,
161            queue_type,
162            mem,
163            id,
164            next: size as u32,
165            size: size as u32,
166            shift: size.trailing_zeros(),
167            _phantom: PhantomData,
168        }
169    }
170
171    /// Save the state of the queue for restoration after servicing.
172    pub fn save(&self) -> CqEqSavedState {
173        CqEqSavedState {
174            doorbell: DoorbellSavedState {
175                doorbell_id: self.doorbell.doorbell_id as u64,
176                page_count: self.doorbell.doorbell.page_count(),
177            },
178            doorbell_addr: self.doorbell_addr,
179            id: self.id,
180            next: self.next,
181            size: self.size,
182            shift: self.shift,
183        }
184    }
185
186    /// Restore a queue from saved state.
187    pub fn restore(
188        queue_type: GdmaQueueType,
189        mem: MemoryBlock,
190        doorbell: DoorbellPage,
191        state: CqEqSavedState,
192    ) -> Self {
193        Self {
194            doorbell,
195            doorbell_addr: state.doorbell_addr,
196            queue_type,
197            mem,
198            id: state.id,
199            next: state.next,
200            size: state.size,
201            shift: state.shift,
202            _phantom: PhantomData,
203        }
204    }
205
206    /// Updates the queue ID.
207    pub(crate) fn set_id(&mut self, id: u32) {
208        self.id = id;
209    }
210
211    /// Updates the doorbell page.
212    pub(crate) fn set_doorbell(&mut self, page: DoorbellPage) {
213        self.doorbell = page;
214    }
215
216    /// Gets the queue ID.
217    pub fn id(&self) -> u32 {
218        self.id
219    }
220
221    fn read_next<U: FromBytes + Immutable + KnownLayout>(&self, offset: u32) -> U {
222        assert!((offset as usize & (size_of::<T>() - 1)) + size_of::<U>() <= size_of::<T>());
223        self.mem
224            .read_obj((self.next.wrapping_add(offset) & (self.size - 1)) as usize)
225    }
226
227    /// Pops an event queue entry.
228    pub fn pop(&mut self) -> Option<T> {
229        // Perform an acquire load to ensure that the read of the queue entry is
230        // not reordered before the read of the owner count.
231        let b = self.mem.as_slice()
232            [(self.next.wrapping_add(size_of::<T>() as u32 - 1) & (self.size - 1)) as usize]
233            .load(Acquire);
234        let owner_count = b >> 5;
235        let cur_owner_count = (self.next >> self.shift) as u8;
236        if owner_count == (cur_owner_count.wrapping_sub(1)) & OWNER_MASK as u8 {
237            None
238        } else if owner_count == cur_owner_count & OWNER_MASK as u8 {
239            let qe = self.read_next::<T>(0);
240            self.next = self.next.wrapping_add(size_of_val(&qe) as u32);
241            Some(qe)
242        } else {
243            tracing::error!(next = self.next, owner_count, queue_type = ?self.queue_type, id = self.id, "eq/cq wrapped");
244            None
245        }
246    }
247
248    fn flush(&mut self, arm: bool) {
249        let tail = self.next & ((self.size << OWNER_BITS) - 1);
250        let value = CqEqDoorbellValue::new()
251            .with_arm(arm)
252            .with_id(self.id)
253            .with_tail(tail / size_of::<T>() as u32);
254        tracing::trace!(queue_type = ?self.queue_type, id = self.id, ?value, "cq/eq doorbell write");
255        self.doorbell.write(self.doorbell_addr, value.into());
256    }
257
258    /// Arms the event queue so that an interrupt will be delivered next time an
259    /// event arrives.
260    pub fn arm(&mut self) {
261        self.flush(true);
262    }
263
264    /// Ack's the queue. Interrupt will not be delivered until it is armed.
265    pub fn ack(&mut self) {
266        self.flush(false);
267    }
268
269    /// Reports next value for diagnostics
270    pub fn get_next(&mut self) -> u32 {
271        self.next
272    }
273}
274
275/// A completion queue.
276pub type Cq = CqEq<Cqe>;
277
278/// An event queue.
279pub type Eq = CqEq<Eqe>;
280
281/// A work queue (send or receive).
282#[derive(Inspect)]
283pub struct Wq {
284    #[inspect(skip)]
285    doorbell: DoorbellPage,
286    #[inspect(skip)]
287    queue_type: GdmaQueueType,
288    #[inspect(skip)]
289    doorbell_addr: u32,
290    #[inspect(skip)]
291    mem: MemoryBlock,
292    id: u32,
293    #[inspect(hex)]
294    head: u32,
295    #[inspect(hex)]
296    tail: u32,
297    #[inspect(hex, rename = "size", with = "|x| x + 1")]
298    mask: u32,
299    #[inspect(rename = "uncommited")]
300    uncommitted_count: u32,
301}
302
303/// An error indicating the queue is full.
304#[derive(Debug)]
305pub struct QueueFull;
306
307impl Wq {
308    /// Creates a new send work queue.
309    pub fn new_sq(mem: MemoryBlock, doorbell: DoorbellPage, id: u32) -> Self {
310        Self::new(GdmaQueueType::GDMA_SQ, DB_SQ, mem, doorbell, id)
311    }
312
313    /// Creates a new receive work queue.
314    pub fn new_rq(mem: MemoryBlock, doorbell: DoorbellPage, id: u32) -> Self {
315        Self::new(GdmaQueueType::GDMA_RQ, DB_RQ, mem, doorbell, id)
316    }
317
318    /// Creates a new work queue.
319    fn new(
320        queue_type: GdmaQueueType,
321        doorbell_addr: u32,
322        mem: MemoryBlock,
323        doorbell: DoorbellPage,
324        id: u32,
325    ) -> Self {
326        let size = mem.len() as u32;
327        assert!(size.is_power_of_two());
328        Self {
329            doorbell,
330            queue_type,
331            doorbell_addr,
332            mem,
333            id,
334            head: size,
335            tail: 0,
336            mask: size - 1,
337            uncommitted_count: 0,
338        }
339    }
340
341    /// Save the state of the Wq for restoration after servicing
342    pub fn save(&self) -> WqSavedState {
343        WqSavedState {
344            doorbell: DoorbellSavedState {
345                doorbell_id: self.doorbell.doorbell_id as u64,
346                page_count: self.doorbell.doorbell.page_count(),
347            },
348            doorbell_addr: self.doorbell_addr,
349            id: self.id,
350            head: self.head,
351            tail: self.tail,
352            mask: self.mask,
353        }
354    }
355
356    /// Restores an existing receive work queue.
357    pub fn restore_rq(
358        mem: MemoryBlock,
359        state: WqSavedState,
360        doorbell: DoorbellPage,
361    ) -> anyhow::Result<Self> {
362        Ok(Self {
363            doorbell,
364            doorbell_addr: state.doorbell_addr,
365            queue_type: GdmaQueueType::GDMA_RQ,
366            mem,
367            id: state.id,
368            head: state.head,
369            tail: state.tail,
370            mask: state.mask,
371            uncommitted_count: 0,
372        })
373    }
374
375    /// Restores an existing send work queue.
376    pub fn restore_sq(
377        mem: MemoryBlock,
378        state: WqSavedState,
379        doorbell: DoorbellPage,
380    ) -> anyhow::Result<Self> {
381        Ok(Self {
382            doorbell,
383            doorbell_addr: state.doorbell_addr,
384            queue_type: GdmaQueueType::GDMA_SQ,
385            mem,
386            id: state.id,
387            head: state.head,
388            tail: state.tail,
389            mask: state.mask,
390            uncommitted_count: 0,
391        })
392    }
393
394    /// Returns the queue ID.
395    pub fn id(&self) -> u32 {
396        self.id
397    }
398
399    /// Advances the head, indicating that `n` more bytes are available in the ring.
400    pub fn advance_head(&mut self, n: u32) {
401        assert!(n.is_multiple_of(WQE_ALIGNMENT as u32));
402        self.head = self.head.wrapping_add(n);
403    }
404
405    fn get_offset_in_buffer_in_bytes(&self, offset: u32) -> usize {
406        (offset as usize * WQE_ALIGNMENT) & self.mask as usize
407    }
408
409    /// Reads from the offset, the first `n` bytes.
410    pub fn read(&mut self, offset: u32, n: usize) -> Vec<u8> {
411        let mut buf = vec![0; n];
412        let offset_in_buffer = self.get_offset_in_buffer_in_bytes(offset);
413        self.mem.read_at(offset_in_buffer, &mut buf);
414        buf
415    }
416
417    fn write_tail(&self, offset: u32, data: &[u8]) {
418        debug_assert!(
419            offset as usize % WQE_ALIGNMENT + data.len() <= WQE_ALIGNMENT,
420            "can't write more than one queue segment at a time to avoid wrapping"
421        );
422        self.mem
423            .write_at((self.tail.wrapping_add(offset) & self.mask) as usize, data);
424    }
425
426    /// Returns the number of bytes available in the ring.
427    pub fn available(&self) -> u32 {
428        self.head.wrapping_sub(self.tail)
429    }
430
431    /// Pushes a new work queue entry with an inline out-of-band buffer and
432    /// external data via a scatter-gather list.
433    pub fn push<I: IntoIterator<Item = Sge>>(
434        &mut self,
435        oob: impl IntoBytes + Immutable + KnownLayout,
436        sgl: I,
437    ) -> Result<u32, QueueFull> {
438        let mut builder = self.wqe_builder(oob);
439        for sge in sgl {
440            builder.push_sge(sge);
441        }
442        builder.finish()
443    }
444
445    /// Begins building a work queue entry with an inline out-of-band buffer.
446    pub fn wqe_builder(&mut self, oob: impl IntoBytes + Immutable + KnownLayout) -> WqeBuilder<'_> {
447        WqeBuilder::new(self, oob)
448    }
449
450    /// Commits all written entries by updating the doorbell value observed by
451    /// the device.
452    pub fn commit(&mut self) {
453        // N.B. the tail is not masked to the queue size.
454        let mut value = WqDoorbellValue::new().with_id(self.id).with_tail(self.tail);
455        if self.queue_type == GdmaQueueType::GDMA_RQ {
456            // If this overflows, it's probably for a device type (like bnic)
457            // that ignores it.
458            value.set_num_rwqe(self.uncommitted_count as u8);
459        }
460        tracing::trace!(queue_type = ?self.queue_type, id = self.id, ?value, "wq doorbell write");
461        self.doorbell.write(self.doorbell_addr, value.into());
462        self.uncommitted_count = 0;
463    }
464
465    /// Reports tail value for diagnostics
466    pub fn get_tail(&mut self) -> u32 {
467        self.tail
468    }
469}
470
471/// A builder for a work queue entry.
472pub struct WqeBuilder<'a> {
473    wq: &'a mut Wq,
474    len: u32,
475    max: u32,
476    hdr: WqeHeader,
477}
478
479impl<'a> WqeBuilder<'a> {
480    fn new(wq: &'a mut Wq, oob: impl IntoBytes + Immutable + KnownLayout) -> Self {
481        let oob_size = match size_of_val(&oob) {
482            0 | 8 => CLIENT_OOB_8,
483            24 => CLIENT_OOB_24,
484            32 => CLIENT_OOB_32,
485            _ => panic!("invalid oob size"),
486        };
487        let max = wq.available();
488        let len =
489            (size_of::<WqeHeader>() + size_of_val(&oob)).next_multiple_of(size_of::<Sge>()) as u32;
490
491        // Save the header to write later.
492        let hdr = WqeHeader {
493            reserved: [0; 3],
494            last_vbytes: 0,
495            params: WqeParams::new().with_inline_client_oob_size(oob_size),
496        };
497
498        // Write the out-of-band data.
499        if len <= max {
500            match size_of_val(&oob) {
501                0 => {}
502                8 | 24 => {
503                    wq.write_tail(8, oob.as_bytes());
504                }
505                32 => {
506                    wq.write_tail(8, &oob.as_bytes()[..24]);
507                    wq.write_tail(32, &oob.as_bytes()[24..]);
508                }
509                _ => unreachable!(),
510            }
511        }
512
513        Self { wq, len, max, hdr }
514    }
515
516    /// Sets that client out-of-band data is provided in the first scatter-gather
517    /// entry, with the specified `last_vbytes` value.
518    pub fn set_client_oob_in_sgl(&mut self, last_vbytes: u8) {
519        self.hdr.last_vbytes = last_vbytes;
520        self.hdr.params.set_client_oob_in_sgl(true);
521    }
522
523    /// Sets the `gd_client_unit_data` field in the header.
524    pub fn set_gd_client_unit_data(&mut self, value: u16) {
525        self.hdr.params.set_gd_client_unit_data(value);
526    }
527
528    /// Appends a scatter-gather entry to the work queue entry.
529    pub fn push_sge(&mut self, sge: Sge) {
530        let offset = self.len;
531        self.len += size_of_val(&sge) as u32;
532        if self.len <= self.max {
533            self.wq.write_tail(offset, sge.as_bytes());
534        }
535        self.hdr
536            .params
537            .set_num_sgl_entries(self.hdr.params.num_sgl_entries() + 1);
538    }
539
540    /// Returns the number of scatter-gather entries added so far.
541    pub fn sge_count(&self) -> u8 {
542        self.hdr.params.num_sgl_entries()
543    }
544
545    /// Finishes building the work queue entry and writes it to the queue,
546    /// updating the tail and returning the total length of the entry.
547    ///
548    /// Call [`Wq::commit`] to notify the device of the new entry.
549    pub fn finish(self) -> Result<u32, QueueFull> {
550        let aligned_len = self.len.next_multiple_of(WQE_ALIGNMENT as u32);
551        if aligned_len > self.max {
552            return Err(QueueFull);
553        }
554        self.wq.write_tail(0, self.hdr.as_bytes());
555        self.wq.tail = self.wq.tail.wrapping_add(aligned_len);
556        self.wq.uncommitted_count += 1;
557        Ok(aligned_len)
558    }
559}