devices/virtio/
virtio_mmio_device.rs

1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::collections::BTreeMap;
6
7use acpi_tables::aml;
8use acpi_tables::aml::Aml;
9use anyhow::anyhow;
10use anyhow::Context;
11use base::error;
12use base::pagesize;
13use base::warn;
14use base::AsRawDescriptors;
15use base::Event;
16use base::RawDescriptor;
17use base::Result;
18use hypervisor::Datamatch;
19use resources::AllocOptions;
20use resources::SystemAllocator;
21use virtio_sys::virtio_config::VIRTIO_CONFIG_S_ACKNOWLEDGE;
22use virtio_sys::virtio_config::VIRTIO_CONFIG_S_DRIVER;
23use virtio_sys::virtio_config::VIRTIO_CONFIG_S_DRIVER_OK;
24use virtio_sys::virtio_config::VIRTIO_CONFIG_S_FAILED;
25use virtio_sys::virtio_config::VIRTIO_CONFIG_S_FEATURES_OK;
26use virtio_sys::virtio_config::VIRTIO_CONFIG_S_NEEDS_RESET;
27use virtio_sys::virtio_mmio::*;
28use vm_control::DeviceId;
29use vm_control::PlatformDeviceId;
30use vm_memory::GuestMemory;
31
32use super::*;
33use crate::BusAccessInfo;
34use crate::BusDevice;
35use crate::BusDeviceObj;
36use crate::IrqEdgeEvent;
37use crate::Suspendable;
38
39const VIRT_MAGIC: u32 = 0x74726976; /* 'virt' */
40const VIRT_VERSION: u8 = 2;
41const VIRT_VENDOR: u32 = 0x4D565243; /* 'CRVM' */
42const VIRTIO_MMIO_REGION_SZ: u64 = 0x200;
43
44/// Implements the
45/// [MMIO](http://docs.oasis-open.org/virtio/virtio/v1.0/cs04/virtio-v1.0-cs04.html#x1-1090002)
46/// transport for virtio devices.
47pub struct VirtioMmioDevice {
48    device: Box<dyn VirtioDevice>,
49    device_activated: bool,
50
51    interrupt: Option<Interrupt>,
52    interrupt_evt: Option<IrqEdgeEvent>,
53    async_intr_status: bool,
54    queues: Vec<QueueConfig>,
55    queue_evts: Vec<Event>,
56    mem: GuestMemory,
57    device_feature_select: u32,
58    driver_feature_select: u32,
59    queue_select: u16,
60    driver_status: u8,
61    mmio_base: u64,
62    irq_num: u32,
63    config_generation: u32,
64}
65
66impl VirtioMmioDevice {
67    /// Constructs a new MMIO transport for the given virtio device.
68    pub fn new(
69        mem: GuestMemory,
70        device: Box<dyn VirtioDevice>,
71        async_intr_status: bool,
72    ) -> Result<Self> {
73        let mut queue_evts = Vec::new();
74        for _ in device.queue_max_sizes() {
75            queue_evts.push(Event::new()?)
76        }
77        let queues = device
78            .queue_max_sizes()
79            .iter()
80            .map(|&s| QueueConfig::new(s, device.features()))
81            .collect();
82
83        Ok(VirtioMmioDevice {
84            device,
85            device_activated: false,
86            interrupt: None,
87            interrupt_evt: None,
88            async_intr_status,
89            queues,
90            queue_evts,
91            mem,
92            device_feature_select: 0,
93            driver_feature_select: 0,
94            queue_select: 0,
95            driver_status: 0,
96            mmio_base: 0,
97            irq_num: 0,
98            config_generation: 0,
99        })
100    }
101    pub fn ioevents(&self) -> Vec<(&Event, u64, Datamatch)> {
102        self.queue_evts
103            .iter()
104            .enumerate()
105            .map(|(i, event)| {
106                (
107                    event,
108                    self.mmio_base + VIRTIO_MMIO_QUEUE_NOTIFY as u64,
109                    Datamatch::U32(Some(i.try_into().unwrap())),
110                )
111            })
112            .collect()
113    }
114
115    fn is_driver_ready(&self) -> bool {
116        let ready_bits = (VIRTIO_CONFIG_S_ACKNOWLEDGE
117            | VIRTIO_CONFIG_S_DRIVER
118            | VIRTIO_CONFIG_S_DRIVER_OK
119            | VIRTIO_CONFIG_S_FEATURES_OK) as u8;
120        self.driver_status == ready_bits && self.driver_status & VIRTIO_CONFIG_S_FAILED as u8 == 0
121    }
122
123    /// Determines if the driver has requested the device reset itself
124    fn is_reset_requested(&self) -> bool {
125        self.driver_status == DEVICE_RESET as u8
126    }
127
128    fn device_type(&self) -> u32 {
129        self.device.device_type().into()
130    }
131
132    /// Activates the underlying `VirtioDevice`. `assign_irq` has to be called first.
133    fn activate(&mut self) -> anyhow::Result<()> {
134        let interrupt_evt = if let Some(ref evt) = self.interrupt_evt {
135            evt.try_clone()
136                .with_context(|| format!("{} failed to clone interrupt_evt", self.debug_label()))?
137        } else {
138            return Err(anyhow!("{} interrupt_evt is none", self.debug_label()));
139        };
140
141        let mem = self.mem.clone();
142        let interrupt = Interrupt::new_mmio(interrupt_evt, self.async_intr_status);
143        self.interrupt = Some(interrupt.clone());
144
145        // Use ready queues and their events.
146        let queues = match self
147            .queues
148            .iter_mut()
149            .zip(self.queue_evts.iter())
150            .enumerate()
151            .filter(|(_, (q, _))| q.ready())
152            .map(|(queue_index, (queue, evt))| {
153                let queue_evt = evt.try_clone().context("failed to clone queue_evt")?;
154                Ok((
155                    queue_index,
156                    queue
157                        .activate(&mem, queue_evt, interrupt.clone())
158                        .context("failed to activate queue")?,
159                ))
160            })
161            .collect::<anyhow::Result<BTreeMap<usize, Queue>>>()
162        {
163            Ok(queues) => queues,
164            Err(e) => {
165                error!("{} failed to activate queues: {:#}", self.debug_label(), e);
166                self.driver_status |= VIRTIO_CONFIG_S_NEEDS_RESET as u8;
167                interrupt.signal_config_changed();
168                return Ok(());
169            }
170        };
171
172        if let Err(e) = self.device.activate(mem, interrupt.clone(), queues) {
173            error!("{} activate failed: {:#}", self.debug_label(), e);
174            self.driver_status |= VIRTIO_CONFIG_S_NEEDS_RESET as u8;
175            interrupt.signal_config_changed();
176        } else {
177            self.device_activated = true;
178        }
179
180        Ok(())
181    }
182
183    fn read_mmio(&self, info: BusAccessInfo, data: &mut [u8]) {
184        if data.len() != std::mem::size_of::<u32>() {
185            warn!(
186                "{}: unsupported read length {}, only support 4 bytes read",
187                self.debug_label(),
188                data.len()
189            );
190            return;
191        }
192
193        if info.offset >= VIRTIO_MMIO_CONFIG as u64 {
194            self.device
195                .read_config(info.offset - VIRTIO_MMIO_CONFIG as u64, data);
196            return;
197        }
198
199        let val = match info.offset as u32 {
200            VIRTIO_MMIO_MAGIC_VALUE => VIRT_MAGIC,
201            VIRTIO_MMIO_VERSION => VIRT_VERSION.into(), // legacy is not supported
202            VIRTIO_MMIO_DEVICE_ID => self.device_type(),
203            VIRTIO_MMIO_VENDOR_ID => VIRT_VENDOR,
204            VIRTIO_MMIO_DEVICE_FEATURES => {
205                // Only 64 bits of features (2 pages) are defined for now, so limit
206                // device_feature_select to avoid shifting by 64 or more bits.
207                if self.device_feature_select < 2 {
208                    (self.device.features() >> (self.device_feature_select * 32)) as u32
209                } else {
210                    0
211                }
212            }
213            VIRTIO_MMIO_QUEUE_NUM_MAX => self.with_queue(|q| q.max_size()).unwrap_or(0).into(),
214            VIRTIO_MMIO_QUEUE_PFN => {
215                warn!(
216                    "{}: read from legacy register {}, in non-legacy mode",
217                    self.debug_label(),
218                    info.offset,
219                );
220                0
221            }
222            VIRTIO_MMIO_QUEUE_READY => self.with_queue(|q| q.ready()).unwrap_or(false).into(),
223            VIRTIO_MMIO_INTERRUPT_STATUS => {
224                if let Some(interrupt) = &self.interrupt {
225                    interrupt.read_interrupt_status().into()
226                } else {
227                    0
228                }
229            }
230            VIRTIO_MMIO_STATUS => self.driver_status.into(),
231            VIRTIO_MMIO_CONFIG_GENERATION => self.config_generation,
232            _ => {
233                warn!("{}: unsupported read address {}", self.debug_label(), info);
234                return;
235            }
236        };
237
238        let val_arr = val.to_le_bytes();
239        data.copy_from_slice(&val_arr);
240    }
241
242    fn write_mmio(&mut self, info: BusAccessInfo, data: &[u8]) {
243        if data.len() != std::mem::size_of::<u32>() {
244            warn!(
245                "{}: unsupported write length {}, only support 4 bytes write",
246                self.debug_label(),
247                data.len()
248            );
249            return;
250        }
251
252        if info.offset >= VIRTIO_MMIO_CONFIG as u64 {
253            self.device
254                .write_config(info.offset - VIRTIO_MMIO_CONFIG as u64, data);
255            return;
256        }
257
258        // This unwrap cannot fail since data.len() is checked.
259        let val = u32::from_le_bytes(data.try_into().unwrap());
260        let was_reset_requested = self.is_reset_requested();
261
262        macro_rules! hi {
263            ($q:expr, $get:ident, $set:ident, $x:expr) => {
264                $q.$set(($q.$get() & 0xffffffff) | (($x as u64) << 32))
265            };
266        }
267        macro_rules! lo {
268            ($q:expr, $get:ident, $set:ident, $x:expr) => {
269                $q.$set(($q.$get() & !0xffffffff) | ($x as u64))
270            };
271        }
272
273        match info.offset as u32 {
274            VIRTIO_MMIO_DEVICE_FEATURES_SEL => self.device_feature_select = val,
275            VIRTIO_MMIO_DRIVER_FEATURES_SEL => self.driver_feature_select = val,
276            VIRTIO_MMIO_DRIVER_FEATURES => {
277                // Only 64 bits of features (2 pages) are defined for now, so limit
278                // device_feature_select to avoid shifting by 64 or more bits.
279                if self.driver_feature_select < 2 {
280                    let features: u64 = (val as u64) << (self.driver_feature_select * 32);
281                    self.device.ack_features(features);
282                    for queue in self.queues.iter_mut() {
283                        queue.ack_features(features);
284                    }
285                } else {
286                    // The guest might try to write features outside of the first
287                    // 64-bit in a second 64-bit (validly), but these should be zero
288                    if val != 0 {
289                        warn!(
290                            "invalid ack_features (page {}, value 0x{:x})",
291                            self.driver_feature_select, val
292                        );
293                    }
294                }
295            }
296            VIRTIO_MMIO_GUEST_PAGE_SIZE => warn!(
297                "{}: write to legacy register {}, in non-legacy mode",
298                self.debug_label(),
299                info.offset,
300            ),
301            VIRTIO_MMIO_QUEUE_SEL => self.queue_select = val as u16,
302            VIRTIO_MMIO_QUEUE_NUM => self.with_queue_mut(|q| q.set_size(val as u16)),
303            VIRTIO_MMIO_QUEUE_ALIGN => warn!(
304                "{}: write to legacy register {}, in non-legacy mode",
305                self.debug_label(),
306                info.offset,
307            ),
308            VIRTIO_MMIO_QUEUE_PFN => warn!(
309                "{}: write to legacy register {}, in non-legacy mode",
310                self.debug_label(),
311                info.offset,
312            ),
313            VIRTIO_MMIO_QUEUE_READY => self.with_queue_mut(|q| q.set_ready(val == 1)),
314            VIRTIO_MMIO_QUEUE_NOTIFY => {} // Handled with ioevents.
315            VIRTIO_MMIO_INTERRUPT_ACK => {
316                if let Some(interrupt) = &self.interrupt {
317                    interrupt.clear_interrupt_status_bits(val as u8)
318                }
319            }
320            VIRTIO_MMIO_STATUS => self.driver_status = val as u8,
321            VIRTIO_MMIO_QUEUE_DESC_LOW => {
322                self.with_queue_mut(|q| lo!(q, desc_table, set_desc_table, val))
323            }
324            VIRTIO_MMIO_QUEUE_DESC_HIGH => {
325                self.with_queue_mut(|q| hi!(q, desc_table, set_desc_table, val))
326            }
327            VIRTIO_MMIO_QUEUE_AVAIL_LOW => {
328                self.with_queue_mut(|q| lo!(q, avail_ring, set_avail_ring, val))
329            }
330            VIRTIO_MMIO_QUEUE_AVAIL_HIGH => {
331                self.with_queue_mut(|q| hi!(q, avail_ring, set_avail_ring, val))
332            }
333            VIRTIO_MMIO_QUEUE_USED_LOW => {
334                self.with_queue_mut(|q| lo!(q, used_ring, set_used_ring, val))
335            }
336            VIRTIO_MMIO_QUEUE_USED_HIGH => {
337                self.with_queue_mut(|q| hi!(q, used_ring, set_used_ring, val))
338            }
339            _ => {
340                warn!("{}: unsupported write address {}", self.debug_label(), info);
341                return;
342            }
343        };
344
345        if !self.device_activated && self.is_driver_ready() {
346            if let Err(e) = self.activate() {
347                error!("failed to activate device: {:#}", e);
348            }
349        }
350
351        // Device has been reset by the driver. Only reset on the transition to 0 or to retry a
352        // failed device reset.
353        if self.is_reset_requested() && (!was_reset_requested || self.device_activated) {
354            let result = if self.device_activated {
355                self.device.reset()
356            } else {
357                Ok(())
358            };
359            if let Err(e) = result {
360                error!("failed to reset {} device: {:#}", self.debug_label(), e);
361            } else {
362                self.device_activated = false;
363                // reset queues
364                self.queues.iter_mut().for_each(QueueConfig::reset);
365                // select queue 0 by default
366                self.queue_select = 0;
367                // reset interrupt
368                self.interrupt = None;
369            }
370        }
371    }
372
373    fn with_queue<U, F>(&self, f: F) -> Option<U>
374    where
375        F: FnOnce(&QueueConfig) -> U,
376    {
377        self.queues.get(self.queue_select as usize).map(f)
378    }
379
380    fn with_queue_mut<F>(&mut self, f: F)
381    where
382        F: FnOnce(&mut QueueConfig),
383    {
384        if let Some(queue) = self.queues.get_mut(self.queue_select as usize) {
385            f(queue);
386        }
387    }
388
389    pub fn allocate_regions(
390        &mut self,
391        resources: &mut SystemAllocator,
392    ) -> std::result::Result<Vec<(u64, u64)>, resources::Error> {
393        let mut ranges = Vec::new();
394        let alloc_id = resources.get_anon_alloc();
395        let start_addr = resources.allocate_mmio(
396            VIRTIO_MMIO_REGION_SZ,
397            alloc_id,
398            "virtio_mmio".to_string(),
399            AllocOptions::new().align(pagesize() as u64),
400        )?;
401        self.mmio_base = start_addr;
402        ranges.push((start_addr, VIRTIO_MMIO_REGION_SZ));
403        Ok(ranges)
404    }
405
406    pub fn assign_irq(&mut self, irq_evt: &IrqEdgeEvent, irq_num: u32) {
407        self.interrupt_evt = Some(irq_evt.try_clone().unwrap());
408        self.irq_num = irq_num;
409    }
410
411    pub fn keep_rds(&self) -> Vec<RawDescriptor> {
412        let mut rds = self.device.keep_rds();
413        if let Some(interrupt_evt) = &self.interrupt_evt {
414            rds.extend(interrupt_evt.as_raw_descriptors());
415        }
416        rds
417    }
418
419    fn on_device_sandboxed(&mut self) {
420        self.device.on_device_sandboxed();
421    }
422}
423
424impl Aml for VirtioMmioDevice {
425    fn to_aml_bytes(&self, bytes: &mut Vec<u8>) {
426        aml::Device::new(
427            "VIOM".into(),
428            vec![
429                &aml::Name::new("_HID".into(), &"LNRO0005"),
430                &aml::Name::new(
431                    "_CRS".into(),
432                    &aml::ResourceTemplate::new(vec![
433                        &aml::AddressSpace::new_memory(
434                            aml::AddressSpaceCachable::NotCacheable,
435                            true,
436                            self.mmio_base,
437                            self.mmio_base + VIRTIO_MMIO_REGION_SZ - 1,
438                        ),
439                        &aml::Interrupt::new(true, true, false, false, self.irq_num),
440                    ]),
441                ),
442            ],
443        )
444        .to_aml_bytes(bytes);
445    }
446}
447
448impl BusDeviceObj for VirtioMmioDevice {}
449
450impl BusDevice for VirtioMmioDevice {
451    fn debug_label(&self) -> String {
452        format!("mmio{}", self.device.debug_label())
453    }
454
455    fn device_id(&self) -> DeviceId {
456        PlatformDeviceId::VirtioMmio.into()
457    }
458
459    fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) {
460        self.read_mmio(info, data)
461    }
462
463    fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
464        self.write_mmio(info, data)
465    }
466
467    fn on_sandboxed(&mut self) {
468        self.on_device_sandboxed();
469    }
470}
471
472// TODO: Mimic the Suspendable impl in ViritoPciDevice when/if someone wants it.
473impl Suspendable for VirtioMmioDevice {}
474
475#[cfg(test)]
476mod tests {
477    use base::RawDescriptor;
478    use virtio_sys::virtio_config::VIRTIO_F_RING_PACKED;
479    use vm_memory::GuestAddress;
480
481    use super::*;
482
483    /// A device with one queue. If `fail_activate` is set, the next activation fails.
484    struct TestDevice {
485        fail_activate: bool,
486    }
487
488    impl VirtioDevice for TestDevice {
489        fn keep_rds(&self) -> Vec<RawDescriptor> {
490            Vec::new()
491        }
492
493        fn device_type(&self) -> DeviceType {
494            DeviceType::Block
495        }
496
497        fn features(&self) -> u64 {
498            1 << VIRTIO_F_RING_PACKED
499        }
500
501        fn queue_max_sizes(&self) -> &[u16] {
502            &[16]
503        }
504
505        fn activate(
506            &mut self,
507            _mem: GuestMemory,
508            _interrupt: Interrupt,
509            _queues: BTreeMap<usize, Queue>,
510        ) -> anyhow::Result<()> {
511            if std::mem::take(&mut self.fail_activate) {
512                anyhow::bail!("test activation failure");
513            }
514            Ok(())
515        }
516    }
517
518    #[test]
519    fn reset_after_device_activation_failure() {
520        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
521        let mut device = VirtioMmioDevice::new(
522            mem,
523            Box::new(TestDevice {
524                fail_activate: true,
525            }),
526            false,
527        )
528        .unwrap();
529        device.interrupt_evt = Some(IrqEdgeEvent::new().unwrap());
530        let status = BusAccessInfo {
531            offset: VIRTIO_MMIO_STATUS as u64,
532            address: 0,
533            id: 0,
534        };
535        let ready = VIRTIO_CONFIG_S_ACKNOWLEDGE
536            | VIRTIO_CONFIG_S_DRIVER
537            | VIRTIO_CONFIG_S_FEATURES_OK
538            | VIRTIO_CONFIG_S_DRIVER_OK;
539        let configure_queue = |device: &mut VirtioMmioDevice| {
540            device.queues[0].set_desc_table(GuestAddress(0));
541            device.queues[0].set_avail_ring(GuestAddress(0x200));
542            device.queues[0].set_used_ring(GuestAddress(0x400));
543            device.queues[0].set_ready(true);
544        };
545
546        // The queue activates but the device fails to.
547        configure_queue(&mut device);
548        device.write_mmio(status, &ready.to_le_bytes());
549        assert!(!device.device_activated);
550        assert_ne!(device.driver_status & VIRTIO_CONFIG_S_NEEDS_RESET as u8, 0);
551
552        // Reset must clear the queue even though the device never activated.
553        device.write_mmio(status, &0u32.to_le_bytes());
554        assert!(!device.queues[0].ready());
555        assert!(device.interrupt.is_none());
556
557        // The driver can configure the queue again and activate the device.
558        configure_queue(&mut device);
559        device.write_mmio(status, &ready.to_le_bytes());
560        assert!(device.device_activated);
561        assert_eq!(device.driver_status, ready as u8);
562    }
563
564    #[test]
565    fn reset_after_queue_activation_failure() {
566        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
567        let mut device = VirtioMmioDevice::new(
568            mem,
569            Box::new(TestDevice {
570                fail_activate: false,
571            }),
572            false,
573        )
574        .unwrap();
575        device.interrupt_evt = Some(IrqEdgeEvent::new().unwrap());
576        let status = BusAccessInfo {
577            offset: VIRTIO_MMIO_STATUS as u64,
578            address: 0,
579            id: 0,
580        };
581        let ready = VIRTIO_CONFIG_S_ACKNOWLEDGE
582            | VIRTIO_CONFIG_S_DRIVER
583            | VIRTIO_CONFIG_S_FEATURES_OK
584            | VIRTIO_CONFIG_S_DRIVER_OK;
585        let configure_queue = |device: &mut VirtioMmioDevice, desc_table| {
586            device.queues[0].ack_features(1 << VIRTIO_F_RING_PACKED);
587            device.queues[0].set_desc_table(GuestAddress(desc_table));
588            device.queues[0].set_avail_ring(GuestAddress(0x200));
589            device.queues[0].set_used_ring(GuestAddress(0x400));
590            device.queues[0].set_ready(true);
591        };
592
593        // The driver enables a packed queue with a descriptor table outside RAM.
594        configure_queue(&mut device, 0x1000);
595        device.write_mmio(status, &ready.to_le_bytes());
596        assert!(!device.device_activated);
597        assert_ne!(device.driver_status & VIRTIO_CONFIG_S_NEEDS_RESET as u8, 0);
598
599        // Reset must clear the queue even though the device never activated.
600        device.write_mmio(status, &0u32.to_le_bytes());
601        assert!(!device.queues[0].ready());
602        assert!(device.interrupt.is_none());
603
604        // The driver can configure valid rings and activate the device again.
605        configure_queue(&mut device, 0);
606        device.write_mmio(status, &ready.to_le_bytes());
607        assert!(device.device_activated);
608        assert_eq!(device.driver_status, ready as u8);
609    }
610
611    #[test]
612    fn writes_while_reset_do_not_reset_queues() {
613        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
614        let mut device = VirtioMmioDevice::new(
615            mem,
616            Box::new(TestDevice {
617                fail_activate: false,
618            }),
619            false,
620        )
621        .unwrap();
622        let desc_low = BusAccessInfo {
623            offset: VIRTIO_MMIO_QUEUE_DESC_LOW as u64,
624            address: 0,
625            id: 0,
626        };
627
628        // The status is already 0, so this is not a reset request.
629        device.write_mmio(desc_low, &0x200u32.to_le_bytes());
630        assert_eq!(device.queues[0].desc_table(), GuestAddress(0x200));
631    }
632}