Skip to main content

user_driver/
vfio.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Support for accessing a MANA device via VFIO on Linux.
5
6#![cfg(target_os = "linux")]
7#![cfg(feature = "vfio")]
8
9use crate::DeviceBacking;
10use crate::DeviceRegisterIo;
11use crate::DmaClient;
12use crate::interrupt::DeviceInterrupt;
13use crate::interrupt::DeviceInterruptSource;
14use anyhow::Context;
15use futures::FutureExt;
16use futures_concurrency::future::Race;
17use inspect::Inspect;
18use inspect_counters::SharedCounter;
19use nix::errno::Errno;
20use pal_async::task::Spawn;
21use pal_async::task::Task;
22use pal_async::wait::PolledWait;
23use pal_event::Event;
24use std::os::fd::AsFd;
25use std::os::unix::fs::FileExt;
26use std::path::Path;
27use std::sync::Arc;
28use std::sync::atomic::AtomicU32;
29use std::sync::atomic::Ordering::Relaxed;
30use std::time::Duration;
31use uevent::UeventListener;
32use vfio_bindings::bindings::vfio::VFIO_PCI_CONFIG_REGION_INDEX;
33use vfio_sys::IommuType;
34use vfio_sys::IrqInfo;
35use vmcore::vm_task::VmTaskDriver;
36use vmcore::vm_task::VmTaskDriverSource;
37use zerocopy::FromBytes;
38use zerocopy::Immutable;
39use zerocopy::IntoBytes;
40use zerocopy::KnownLayout;
41
42#[derive(Clone)]
43pub enum VfioDmaClients {
44    PersistentOnly(Arc<dyn DmaClient>),
45    EphemeralOnly(Arc<dyn DmaClient>),
46    Split {
47        persistent: Arc<dyn DmaClient>,
48        ephemeral: Arc<dyn DmaClient>,
49    },
50}
51
52/// A device backend accessed via VFIO.
53#[derive(Inspect)]
54pub struct VfioDevice {
55    pci_id: Arc<str>,
56    #[inspect(skip)]
57    _container: vfio_sys::Container,
58    #[inspect(skip)]
59    _group: vfio_sys::Group,
60    #[inspect(skip)]
61    device: Arc<vfio_sys::Device>,
62    #[inspect(skip)]
63    msix_info: IrqInfo,
64    #[inspect(skip)]
65    driver_source: VmTaskDriverSource,
66    #[inspect(iter_by_index)]
67    interrupts: Vec<Option<InterruptState>>,
68    #[inspect(skip)]
69    config_space: vfio_sys::RegionInfo,
70    #[inspect(skip)]
71    dma_clients: VfioDmaClients,
72}
73
74#[derive(Inspect)]
75struct InterruptState {
76    #[inspect(skip)]
77    interrupt: DeviceInterrupt,
78    target_cpu: Arc<AtomicU32>,
79    #[inspect(skip)]
80    _task: Task<()>,
81}
82
83impl Drop for VfioDevice {
84    fn drop(&mut self) {
85        // Just for tracing ...
86        tracing::trace!(pci_id = ?self.pci_id, "dropping vfio device");
87    }
88}
89
90impl VfioDevice {
91    /// Creates a new VFIO-backed device for the PCI device with `pci_id`.
92    pub async fn new(
93        driver_source: &VmTaskDriverSource,
94        pci_id: impl AsRef<str>,
95        dma_clients: VfioDmaClients,
96    ) -> anyhow::Result<Self> {
97        Self::restore(driver_source, pci_id, false, dma_clients).await
98    }
99
100    /// Creates a new VFIO-backed device for the PCI device with `pci_id`.
101    /// or creates a device from the saved state if provided.
102    pub async fn restore(
103        driver_source: &VmTaskDriverSource,
104        pci_id: impl AsRef<str>,
105        keepalive: bool,
106        dma_clients: VfioDmaClients,
107    ) -> anyhow::Result<Self> {
108        let pci_id = pci_id.as_ref();
109        let path = Path::new("/sys/bus/pci/devices").join(pci_id);
110
111        // The vfio device attaches asynchronously after the PCI device is added,
112        // so make sure that it has completed by checking for the vfio-dev subpath.
113        let vmbus_device =
114            std::fs::read_link(&path).context("failed to read link for pci device")?;
115        let instance_path = Path::new("/sys").join(vmbus_device.strip_prefix("../../..")?);
116        let vfio_arrived_path = instance_path.join("vfio-dev");
117        let uevent_listener = UeventListener::new(&driver_source.simple())?;
118        let wait_for_vfio_device =
119            uevent_listener.wait_for_matching_child(&vfio_arrived_path, async |_, _| Some(()));
120        let mut ctx = mesh::CancelContext::new().with_timeout(Duration::from_secs(1));
121        // Ignore any errors and always attempt to open.
122        let _ = ctx.until_cancelled(wait_for_vfio_device).await;
123
124        tracing::info!(pci_id, keepalive, "device arrived");
125        vfio_sys::print_relevant_params();
126
127        let driver = driver_source.simple();
128        let retry = vfio_sys::VfioRetry::new(&driver, pci_id);
129
130        let is_not_found = |e: &anyhow::Error| {
131            e.chain().any(|cause| {
132                cause
133                    .downcast_ref::<std::io::Error>()
134                    .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::NotFound)
135            })
136        };
137        let is_enodev = |e: &anyhow::Error| {
138            e.chain().any(|cause| {
139                cause
140                    .downcast_ref::<Errno>()
141                    .is_some_and(|e| *e == Errno::ENODEV)
142            })
143        };
144
145        let container = vfio_sys::Container::new()?;
146        let group_id = retry
147            .retry(
148                || vfio_sys::Group::find_group_for_device(&path),
149                &is_not_found,
150                "find_group_for_device",
151            )
152            .await?;
153        let group = retry
154            .retry(
155                || vfio_sys::Group::open_noiommu(group_id),
156                &is_not_found,
157                "open_noiommu",
158            )
159            .await?;
160        group.set_container(&container)?;
161        if !group.status()?.viable() {
162            anyhow::bail!("group is not viable");
163        }
164
165        container.set_iommu(IommuType::NoIommu)?;
166        if keepalive {
167            retry
168                .retry(
169                    || group.set_keep_alive(pci_id),
170                    &is_enodev,
171                    "set_keep_alive",
172                )
173                .await?;
174        }
175        tracing::debug!(pci_id, "about to open device");
176        let device = retry
177            .retry(|| group.open_device(pci_id), &is_enodev, "open_device")
178            .await?;
179        let msix_info = device.irq_info(vfio_bindings::bindings::vfio::VFIO_PCI_MSIX_IRQ_INDEX)?;
180        if msix_info.flags.noresize() {
181            anyhow::bail!("unsupported: kernel does not support dynamic msix allocation");
182        }
183
184        let config_space = device.region_info(VFIO_PCI_CONFIG_REGION_INDEX)?;
185        let this = Self {
186            pci_id: pci_id.into(),
187            _container: container,
188            _group: group,
189            device: Arc::new(device),
190            msix_info,
191            config_space,
192            driver_source: driver_source.clone(),
193            interrupts: Vec::new(),
194            dma_clients,
195        };
196
197        tracing::debug!(pci_id, "enabling device...");
198        // Ensure bus master enable and memory space enable are set, and that
199        // INTx is disabled.
200        this.enable_device()
201            .with_context(|| format!("failed to enable device {pci_id}"))?;
202        Ok(this)
203    }
204
205    fn enable_device(&self) -> anyhow::Result<()> {
206        let offset = pci_core::spec::cfg_space::HeaderType00::STATUS_COMMAND.0;
207        let status_command = self.read_config(offset)?;
208        let command = pci_core::spec::cfg_space::Command::from(status_command as u16);
209
210        let command = command
211            .with_bus_master(true)
212            .with_intx_disable(true)
213            .with_mmio_enabled(true);
214
215        let status_command = (status_command & 0xffff0000) | u16::from(command) as u32;
216        self.write_config(offset, status_command)?;
217        Ok(())
218    }
219
220    pub fn read_config(&self, offset: u16) -> anyhow::Result<u32> {
221        if offset as u64 > self.config_space.size - 4 {
222            anyhow::bail!("invalid config offset");
223        }
224
225        let mut buf = [0u8; 4];
226        self.device
227            .as_ref()
228            .as_ref()
229            .read_at(&mut buf, self.config_space.offset + offset as u64)
230            .context("failed to read config")?;
231
232        Ok(u32::from_ne_bytes(buf))
233    }
234
235    pub fn write_config(&self, offset: u16, data: u32) -> anyhow::Result<()> {
236        if offset as u64 > self.config_space.size - 4 {
237            anyhow::bail!("invalid config offset");
238        }
239
240        tracing::trace!(pci_id = ?self.pci_id, offset, data, "writing config");
241        let buf = data.to_ne_bytes();
242        self.device
243            .as_ref()
244            .as_ref()
245            .write_at(&buf, self.config_space.offset + offset as u64)
246            .context("failed to write config")?;
247
248        Ok(())
249    }
250
251    /// Maps PCI BAR[n] to VA space.
252    fn map_bar(&self, n: u8) -> anyhow::Result<MappedRegionWithFallback> {
253        if n >= 6 {
254            anyhow::bail!("invalid bar");
255        }
256        let info = self.device.region_info(n.into())?;
257        let mapping = self.device.map(info.offset, info.size as usize, true)?;
258        trycopy::initialize_try_copy();
259        Ok(MappedRegionWithFallback {
260            device: self.device.clone(),
261            mapping,
262            len: info.size as usize,
263            offset: info.offset,
264            read_fallback: SharedCounter::new(),
265            write_fallback: SharedCounter::new(),
266        })
267    }
268}
269
270/// A mapped region that falls back to read/write if the memory mapped access
271/// fails.
272///
273/// This should only happen for CVM, and only when the MMIO is emulated by the
274/// host.
275#[derive(Inspect)]
276pub struct MappedRegionWithFallback {
277    #[inspect(skip)]
278    device: Arc<vfio_sys::Device>,
279    #[inspect(skip)]
280    mapping: vfio_sys::MappedRegion,
281    offset: u64,
282    len: usize,
283    read_fallback: SharedCounter,
284    write_fallback: SharedCounter,
285}
286
287impl DeviceBacking for VfioDevice {
288    type Registers = MappedRegionWithFallback;
289
290    fn id(&self) -> &str {
291        &self.pci_id
292    }
293
294    fn map_bar(&mut self, n: u8) -> anyhow::Result<Self::Registers> {
295        (*self).map_bar(n)
296    }
297
298    fn dma_client(&self) -> Arc<dyn DmaClient> {
299        // Default to the only present client, or if both are available default to the
300        // persistent client.
301        match &self.dma_clients {
302            VfioDmaClients::EphemeralOnly(client) => client.clone(),
303            VfioDmaClients::PersistentOnly(client) => client.clone(),
304            VfioDmaClients::Split {
305                persistent,
306                ephemeral: _,
307            } => persistent.clone(),
308        }
309    }
310
311    fn dma_client_for(&self, pool: crate::DmaPool) -> anyhow::Result<Arc<dyn DmaClient>> {
312        match &self.dma_clients {
313            VfioDmaClients::PersistentOnly(client) => match pool {
314                crate::DmaPool::Persistent => Ok(client.clone()),
315                crate::DmaPool::Ephemeral => {
316                    anyhow::bail!(
317                        "ephemeral dma pool requested but only persistent client available"
318                    )
319                }
320            },
321            VfioDmaClients::EphemeralOnly(client) => match pool {
322                crate::DmaPool::Ephemeral => Ok(client.clone()),
323                crate::DmaPool::Persistent => {
324                    anyhow::bail!(
325                        "persistent dma pool requested but only ephemeral client available"
326                    )
327                }
328            },
329            VfioDmaClients::Split {
330                persistent,
331                ephemeral,
332            } => match pool {
333                crate::DmaPool::Persistent => Ok(persistent.clone()),
334                crate::DmaPool::Ephemeral => Ok(ephemeral.clone()),
335            },
336        }
337    }
338
339    fn max_interrupt_count(&self) -> u32 {
340        self.msix_info.count
341    }
342
343    fn map_interrupt(&mut self, msix: u32, cpu: u32) -> anyhow::Result<DeviceInterrupt> {
344        if msix >= self.msix_info.count {
345            anyhow::bail!("invalid msix index");
346        }
347        if self.interrupts.len() <= msix as usize {
348            self.interrupts.resize_with(msix as usize + 1, || None);
349        }
350
351        let interrupt = &mut self.interrupts[msix as usize];
352        if let Some(interrupt) = interrupt {
353            // The interrupt has been mapped before. Just retarget it to the new
354            // CPU on the next interrupt, if needed.
355            if interrupt.target_cpu.load(Relaxed) != cpu {
356                interrupt.target_cpu.store(cpu, Relaxed);
357            }
358            return Ok(interrupt.interrupt.clone());
359        }
360
361        let new_interrupt = {
362            let name = format!("vfio-interrupt-{pci_id}-{msix}", pci_id = self.pci_id);
363            let driver = self
364                .driver_source
365                .builder()
366                .run_on_target(true)
367                .target_vp(cpu)
368                .build(&name);
369
370            let event =
371                PolledWait::new(&driver, Event::new()).context("failed to allocate polled wait")?;
372
373            let source = DeviceInterruptSource::new();
374            self.device
375                .map_msix(msix, [event.get().as_fd()])
376                .context("failed to map msix")?;
377
378            // The interrupt's CPU affinity will be set by the task when it
379            // starts. This can block the thread briefly, so it's better to do
380            // it on the target CPU.
381            let irq = vfio_sys::find_msix_irq(&self.pci_id, msix)
382                .context("failed to find irq for msix")?;
383
384            let target_cpu = Arc::new(AtomicU32::new(cpu));
385
386            let interrupt = source.new_target();
387
388            let task = driver.spawn(
389                name,
390                InterruptTask {
391                    driver: driver.clone(),
392                    target_cpu: target_cpu.clone(),
393                    pci_id: self.pci_id.clone(),
394                    msix,
395                    irq,
396                    event,
397                    source,
398                }
399                .run(),
400            );
401
402            InterruptState {
403                interrupt,
404                target_cpu,
405                _task: task,
406            }
407        };
408
409        Ok(interrupt.insert(new_interrupt).interrupt.clone())
410    }
411
412    fn unmap_all_interrupts(&mut self) -> anyhow::Result<()> {
413        if self.interrupts.iter().all(|i| i.is_none()) {
414            return Ok(());
415        }
416
417        self.device
418            .unmap_msix()
419            .context("failed to unmap all msix vectors")?;
420
421        // Clear local bookkeeping so re-mapping works correctly later.
422        self.interrupts.clear();
423
424        Ok(())
425    }
426}
427
428struct InterruptTask {
429    driver: VmTaskDriver,
430    target_cpu: Arc<AtomicU32>,
431    pci_id: Arc<str>,
432    msix: u32,
433    irq: u32,
434    event: PolledWait<Event>,
435    source: DeviceInterruptSource,
436}
437
438impl InterruptTask {
439    async fn run(mut self) {
440        let mut current_cpu = !0;
441        loop {
442            let next_cpu = self.target_cpu.load(Relaxed);
443            let r = if next_cpu == current_cpu {
444                self.event.wait().await
445            } else {
446                self.driver.retarget_vp(next_cpu);
447                // Wait until the target CPU is ready before updating affinity,
448                // since otherwise the CPU may not be online.
449                enum Event {
450                    TargetVpReady(()),
451                    Interrupt(std::io::Result<()>),
452                }
453                match (
454                    self.driver.wait_target_vp_ready().map(Event::TargetVpReady),
455                    self.event.wait().map(Event::Interrupt),
456                )
457                    .race()
458                    .await
459                {
460                    Event::TargetVpReady(()) => {
461                        if let Err(err) = set_irq_affinity(self.irq, next_cpu) {
462                            // This should only occur due to extreme low resources.
463                            // However, it is not a fatal error--it will just result in
464                            // worse performance--so do not panic.
465                            tracing::error!(
466                                pci_id = self.pci_id.as_ref(),
467                                msix = self.msix,
468                                irq = self.irq,
469                                error = &err as &dyn std::error::Error,
470                                "failed to set irq affinity"
471                            );
472                        }
473                        current_cpu = next_cpu;
474                        continue;
475                    }
476                    Event::Interrupt(r) => {
477                        // An interrupt arrived while waiting for the VP to be
478                        // ready. Signal and loop around to try again.
479                        r
480                    }
481                }
482            };
483
484            r.expect("wait cannot fail on eventfd");
485            self.source.signal();
486        }
487    }
488}
489
490fn set_irq_affinity(irq: u32, cpu: u32) -> std::io::Result<()> {
491    fs_err::write(
492        format!("/proc/irq/{}/smp_affinity_list", irq),
493        cpu.to_string(),
494    )
495}
496
497impl DeviceRegisterIo for vfio_sys::MappedRegion {
498    fn len(&self) -> usize {
499        self.len()
500    }
501
502    fn read_u32(&self, offset: usize) -> u32 {
503        self.read_u32(offset)
504    }
505
506    fn read_u64(&self, offset: usize) -> u64 {
507        self.read_u64(offset)
508    }
509
510    fn write_u32(&self, offset: usize, data: u32) {
511        self.write_u32(offset, data)
512    }
513
514    fn write_u64(&self, offset: usize, data: u64) {
515        self.write_u64(offset, data)
516    }
517}
518
519impl MappedRegionWithFallback {
520    fn mapping<T>(&self, offset: usize) -> *mut T {
521        assert!(
522            offset <= self.mapping.len() - size_of::<T>() && offset.is_multiple_of(align_of::<T>())
523        );
524        if cfg!(feature = "mmio_simulate_fallback") {
525            return std::ptr::NonNull::dangling().as_ptr();
526        }
527        // SAFETY: the offset is validated to be in bounds.
528        unsafe { self.mapping.as_ptr().byte_add(offset).cast() }
529    }
530
531    fn read_from_mapping<T: IntoBytes + FromBytes + Immutable + KnownLayout>(
532        &self,
533        offset: usize,
534    ) -> Result<T, trycopy::MemoryError> {
535        // SAFETY: the offset is validated to be in bounds and aligned.
536        unsafe { trycopy::try_read_volatile(self.mapping::<T>(offset)) }
537    }
538
539    fn write_to_mapping<T: IntoBytes + FromBytes + Immutable + KnownLayout>(
540        &self,
541        offset: usize,
542        data: T,
543    ) -> Result<(), trycopy::MemoryError> {
544        // SAFETY: the offset is validated to be in bounds and aligned.
545        unsafe { trycopy::try_write_volatile(self.mapping::<T>(offset), &data) }
546    }
547
548    fn read_from_file(&self, offset: usize, buf: &mut [u8]) {
549        tracing::trace!(offset, n = buf.len(), "read");
550        self.read_fallback.increment();
551        let n = self
552            .device
553            .as_ref()
554            .as_ref()
555            .read_at(buf, self.offset + offset as u64)
556            .expect("valid mapping");
557        assert_eq!(n, buf.len());
558    }
559
560    fn write_to_file(&self, offset: usize, buf: &[u8]) {
561        tracing::trace!(offset, n = buf.len(), "write");
562        self.write_fallback.increment();
563        let n = self
564            .device
565            .as_ref()
566            .as_ref()
567            .write_at(buf, self.offset + offset as u64)
568            .expect("valid mapping");
569        assert_eq!(n, buf.len());
570    }
571}
572
573impl DeviceRegisterIo for MappedRegionWithFallback {
574    fn len(&self) -> usize {
575        self.len
576    }
577
578    fn read_u32(&self, offset: usize) -> u32 {
579        self.read_from_mapping(offset).unwrap_or_else(|_| {
580            let mut buf = [0u8; 4];
581            self.read_from_file(offset, &mut buf);
582            u32::from_ne_bytes(buf)
583        })
584    }
585
586    fn read_u64(&self, offset: usize) -> u64 {
587        self.read_from_mapping(offset).unwrap_or_else(|_| {
588            let mut buf = [0u8; 8];
589            self.read_from_file(offset, &mut buf);
590            u64::from_ne_bytes(buf)
591        })
592    }
593
594    fn write_u32(&self, offset: usize, data: u32) {
595        self.write_to_mapping(offset, data).unwrap_or_else(|_| {
596            self.write_to_file(offset, &data.to_ne_bytes());
597        })
598    }
599
600    fn write_u64(&self, offset: usize, data: u64) {
601        self.write_to_mapping(offset, data).unwrap_or_else(|_| {
602            self.write_to_file(offset, &data.to_ne_bytes());
603        })
604    }
605}
606
607#[derive(Clone, Copy, Debug)]
608pub enum PciDeviceResetMethod {
609    NoReset,
610    Acpi,
611    Flr,
612    AfFlr,
613    Pm,
614    Bus,
615}
616
617pub fn vfio_set_device_reset_method(
618    pci_id: impl AsRef<str>,
619    method: PciDeviceResetMethod,
620) -> std::io::Result<()> {
621    let reset_method = match method {
622        PciDeviceResetMethod::NoReset => "\0".as_bytes(),
623        PciDeviceResetMethod::Acpi => "acpi\0".as_bytes(),
624        PciDeviceResetMethod::Flr => "flr\0".as_bytes(),
625        PciDeviceResetMethod::AfFlr => "af_flr\0".as_bytes(),
626        PciDeviceResetMethod::Pm => "pm\0".as_bytes(),
627        PciDeviceResetMethod::Bus => "bus\0".as_bytes(),
628    };
629
630    let path: std::path::PathBuf = ["/sys/bus/pci/devices", pci_id.as_ref(), "reset_method"]
631        .iter()
632        .collect();
633    fs_err::write(path, reset_method)?;
634    Ok(())
635}