Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add interrupt traits and a KVM based implementation #11

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ version = "0.1.0"
authors = ["Samuel Ortiz <[email protected]>"]
repository = "https://github.com/rust-vmm/vm-device"
license = "Apache-2.0"
edition = "2018"

[dependencies]
libc = ">=0.2.39"
kvm-bindings = { version = ">=0.1.1, <1.0", optional = true }
kvm-ioctls = { git = "https://github.com/rust-vmm/kvm-ioctls.git", branch = "master", optional = true }
Comment on lines +11 to +12
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not particularly happy with adding dependencies on kvm related wrappers here. Even though you specify them as optional, their meta-data would still be pulled even if you don't use them. Furthermore, it makes the vm-device a very coupled crate. If there is a way to decouple this, I would prefer to not have these dependencies.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It depends on the granularity for rust-vmm crates. We may have separate interface definition and implementation crates.
My suggestion is that:

  1. integrate interface and implementation within the same crate if there's a majority implementation existing. Vm-memory and interrupt falls into this case.
  2. separate interface definition and implementations if there are multiple possible implementations. VmDevice(DeviceIo) falls into this case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we split this PR in two? One PR that adds the interface so people can experiment with it and one PR for actual implementation?

vmm-sys-util = ">=0.2.0, <1.0"

vm-memory = { git = "https://github.com/rust-vmm/vm-memory" }

[features]
kvm_irq = ["kvm-ioctls", "kvm-bindings"]
legacy_irq = []
msi_irq = []
pci_msi_irq = ["msi_irq"]
2 changes: 1 addition & 1 deletion coverage_config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"coverage_score": 75.8,
"coverage_score": 74.3,
"exclude_path": "",
"crate_features": ""
}
226 changes: 226 additions & 0 deletions src/interrupt/kvm/legacy_irq.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
// Copyright (C) 2019 Alibaba Cloud. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Manage virtual device's legacy interrupts based on Linux KVM framework.
//!
//! On x86 platforms, legacy interrupts are those managed by the Master PIC, the slave PIC and
//! IOAPICs.

use super::*;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use kvm_bindings::{KVM_IRQCHIP_IOAPIC, KVM_IRQCHIP_PIC_MASTER, KVM_IRQCHIP_PIC_SLAVE};
use std::sync::atomic::{AtomicUsize, Ordering};

/// Maximum number of legacy interrupts supported.
pub const MAX_LEGACY_IRQS: u32 = 24;

pub(super) struct LegacyIrq {
base: u32,
vmfd: Arc<VmFd>,
irqfd: EventFd,
status: AtomicUsize,
}

impl LegacyIrq {
#[allow(clippy::new_ret_no_self)]
pub(super) fn new(
base: InterruptIndex,
count: InterruptIndex,
vmfd: Arc<VmFd>,
_routes: Arc<KvmIrqRouting>,
) -> Result<Self> {
if count != 1 {
return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
}

if base >= MAX_LEGACY_IRQS {
return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
}

Ok(LegacyIrq {
base,
vmfd,
irqfd: EventFd::new(0)?,
status: AtomicUsize::new(0),
})
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn add_legacy_entry(
gsi: u32,
chip: u32,
pin: u32,
routes: &mut HashMap<u64, kvm_irq_routing_entry>,
) -> Result<()> {
let mut entry = kvm_irq_routing_entry {
gsi,
type_: KVM_IRQ_ROUTING_IRQCHIP,
..Default::default()
};
// Safe because we are initializing all fields of the `irqchip` struct.
unsafe {
entry.u.irqchip.irqchip = chip;
entry.u.irqchip.pin = pin;
}
routes.insert(hash_key(&entry), entry);

Ok(())
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
/// Build routings for IRQs connected to the master PIC, the slave PIC or the first IOAPIC.
pub(super) fn initialize_legacy(
routes: &mut HashMap<u64, kvm_irq_routing_entry>,
) -> Result<()> {
// Build routings for the master PIC
for i in 0..8 {
if i != 2 {
Self::add_legacy_entry(i, KVM_IRQCHIP_PIC_MASTER, i, routes)?;
}
}

// Build routings for the slave PIC
for i in 8..16 {
Self::add_legacy_entry(i, KVM_IRQCHIP_PIC_SLAVE, i - 8, routes)?;
}

// Build routings for the first IOAPIC
for i in 0..MAX_LEGACY_IRQS {
if i == 0 {
Self::add_legacy_entry(i, KVM_IRQCHIP_IOAPIC, 2, routes)?;
} else if i != 2 {
Self::add_legacy_entry(i, KVM_IRQCHIP_IOAPIC, i, routes)?;
};
}

Ok(())
}

#[cfg(any(target_arch = "aarch", target_arch = "aarch64"))]
pub(super) fn initialize_legacy(
_routes: &mut HashMap<u64, kvm_irq_routing_entry>,
) -> Result<()> {
//TODO
Ok(())
}
}

impl InterruptSourceGroup for LegacyIrq {
fn interrupt_type(&self) -> InterruptSourceType {
InterruptSourceType::LegacyIrq
}

fn len(&self) -> u32 {
1
}

fn base(&self) -> u32 {
self.base
}

fn irqfd(&self, index: InterruptIndex) -> Option<&EventFd> {
if index != 0 {
None
} else {
Some(&self.irqfd)
}
}

fn flags(&self, index: InterruptIndex) -> u32 {
if index == 0 {
self.status.load(Ordering::SeqCst) as u32
} else {
0
}
}

fn enable(&self, configs: &[InterruptSourceConfig]) -> Result<()> {
if configs.len() != 1 {
return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
}
// The IRQ routings for legacy IRQs have been configured during
// KvmIrqManager::initialize(), so only need to register irqfd to the KVM driver.
self.vmfd.register_irqfd(&self.irqfd, self.base)
}

fn disable(&self) -> Result<()> {
self.vmfd.unregister_irqfd(&self.irqfd, self.base)
}

fn update(&self, index: InterruptIndex, _config: &InterruptSourceConfig) -> Result<()> {
// For legacy interrupts, the routing configuration is managed by the PIC/IOAPIC interrupt
// controller drivers, so nothing to do here.
if index != 0 {
return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
}
Ok(())
}

fn trigger(&self, index: InterruptIndex, flags: u32) -> Result<()> {
if index != 0 {
return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
}
// Set interrupt status bits before writing to the irqfd.
self.status.fetch_or(flags as usize, Ordering::SeqCst);
self.irqfd.write(1)
}

fn ack(&self, index: InterruptIndex, flags: u32) -> Result<()> {
if index != 0 {
return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
}
// Clear interrupt status bits.
self.status.fetch_and(!(flags as usize), Ordering::SeqCst);
Ok(())
}
}

#[cfg(test)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
mod test {
use super::*;
use kvm_ioctls::{Kvm, VmFd};

fn create_vm_fd() -> VmFd {
let kvm = Kvm::new().unwrap();
kvm.create_vm().unwrap()
}

#[test]
#[allow(unreachable_patterns)]
fn test_legacy_interrupt_group() {
let vmfd = Arc::new(create_vm_fd());
let rounting = Arc::new(KvmIrqRouting::new(vmfd.clone()));
let base = 0;
let count = 1;
let group = LegacyIrq::new(base, count, vmfd.clone(), rounting.clone()).unwrap();

let mut legacy_fds = Vec::with_capacity(1);
legacy_fds.push(InterruptSourceConfig::LegacyIrq(LegacyIrqSourceConfig {}));

match group.interrupt_type() {
InterruptSourceType::LegacyIrq => {}
_ => {
panic!();
}
}
assert_eq!(group.len(), 1);
assert_eq!(group.base(), base);
assert!(group.enable(&legacy_fds).is_ok());
assert!(group.irqfd(0).unwrap().write(1).is_ok());
assert!(group.trigger(0, 0x168).is_ok());
assert!(group.ack(0, 0x168).is_ok());
assert!(group.trigger(1, 0x168).is_err());
assert!(group.ack(1, 0x168).is_err());
assert!(group
.update(
0,
&InterruptSourceConfig::LegacyIrq(LegacyIrqSourceConfig {})
)
.is_ok());
assert!(group.disable().is_ok());

assert!(LegacyIrq::new(base, 2, vmfd.clone(), rounting.clone()).is_err());
assert!(LegacyIrq::new(110, 1, vmfd.clone(), rounting.clone()).is_err());
}
}
Loading