diff --git a/src/arch/riscv64/cpu.rs b/src/arch/riscv64/cpu.rs index 220629927..4d4f97785 100644 --- a/src/arch/riscv64/cpu.rs +++ b/src/arch/riscv64/cpu.rs @@ -23,7 +23,6 @@ use crate::{ addr::PHYS_VIRT_OFFSET, mm::PARKING_MEMORY_SET, GuestPhysAddr, HostPhysAddr, MemFlags, MemoryRegion, VirtAddr, PARKING_INST_PAGE, }, - zone::find_zone, }; use core::ptr::addr_of; @@ -306,12 +305,3 @@ pub fn store_cpu_pointer_to_reg(pointer: usize) { // println!("Stored CPU pointer to CSR_SSCRATCH: {:#x}", pointer); return; } - -pub fn get_target_cpu(_irq: usize, zone_id: usize) -> usize { - find_zone(zone_id) - .unwrap() - .read() - .cpu_set() - .first_cpu() - .unwrap() -} diff --git a/src/arch/riscv64/hypercall.rs b/src/arch/riscv64/hypercall.rs index 4228211c3..fa106251c 100644 --- a/src/arch/riscv64/hypercall.rs +++ b/src/arch/riscv64/hypercall.rs @@ -15,7 +15,6 @@ // ForeverYolo <2572131118@qq.com> use crate::config::CONFIG_MAGIC_VERSION; -use crate::device::virtio_trampoline::MAX_DEVS; use crate::hypercall::HyperCall; use crate::hypercall::HyperCallResult; @@ -29,10 +28,6 @@ impl<'a> HyperCall<'a> { HyperCallResult::Ok(0) } - pub fn wait_for_interrupt(&mut self, _irq_list: &mut [u64; MAX_DEVS + 1]) { - trace!("wait_for_interrupt is not need for RISC-V"); - } - pub fn hv_zone_config_check(&self, magic_version: *mut u64) -> HyperCallResult { unsafe { *magic_version = CONFIG_MAGIC_VERSION as _; diff --git a/src/arch/x86_64/cpu.rs b/src/arch/x86_64/cpu.rs index da576bf0e..7fc15b5c3 100644 --- a/src/arch/x86_64/cpu.rs +++ b/src/arch/x86_64/cpu.rs @@ -742,7 +742,3 @@ pub fn store_cpu_pointer_to_reg(pointer: usize) { // println!("x86_64 doesn't support store cpu pointer to reg, pointer: {:#x}", pointer); return; } - -pub fn get_target_cpu(irq: usize, zone_id: usize) -> usize { - ioapic::get_irq_cpu(irq, zone_id) -} diff --git a/src/arch/x86_64/hypercall.rs b/src/arch/x86_64/hypercall.rs index 8a8953002..6beabfdf2 100644 --- a/src/arch/x86_64/hypercall.rs +++ b/src/arch/x86_64/hypercall.rs @@ -17,7 +17,6 @@ use crate::{ config::CONFIG_MAGIC_VERSION, cpu_data::this_zone, - device::virtio_trampoline::MAX_DEVS, hypercall::{HyperCall, HyperCallResult}, zone::{Zone, ZoneInfo}, }; @@ -41,10 +40,6 @@ impl<'a> HyperCall<'a> { HyperCallResult::Ok(0) } - pub fn wait_for_interrupt(&mut self, irq_list: &mut [u64; MAX_DEVS + 1]) { - trace!("wait_for_interrupt is not need for x86_64"); - } - pub fn hv_get_real_pa(&mut self, config_addr: u64) -> u64 { unsafe { this_zone() diff --git a/src/arch/x86_64/ipi.rs b/src/arch/x86_64/ipi.rs index 7afb81c4a..92b7058d3 100644 --- a/src/arch/x86_64/ipi.rs +++ b/src/arch/x86_64/ipi.rs @@ -16,12 +16,12 @@ use crate::{ arch::{ - acpi::{get_apic_id, get_cpu_id}, + acpi::{get_apic_id, try_get_cpu_id}, cpu::this_cpu_id, idt::IdtVector, }, cpu_data::{this_cpu_data, this_zone, CpuSet}, - device::irqchip::inject_vector, + device::irqchip::post_guest_vector, error::HvResult, event, hypercall::SGI_IPI_ID, @@ -88,7 +88,7 @@ pub fn send_ipi(value: u64) -> HvResult { let vector = value.get_bits(0..=7) as u8; let delivery_mode: u8 = value.get_bits(8..=10) as u8; let dest_shorthand = value.get_bits(18..=19) as u8; - let dest = get_cpu_id(value.get_bits(32..=39) as usize); + let dest_apic_id = value.get_bits(32..=39) as usize; let cnt = value.get_bits(40..=63) as u32; let mut cpu_set = this_zone().cpu_set(); @@ -97,7 +97,14 @@ pub fn send_ipi(value: u64) -> HvResult { match dest_shorthand { IpiDestShorthand::NO_SHORTHAND => { - dest_set.set_bit(dest); + // The guest picks the APIC ID; only CPUs of its own zone are valid. + match try_get_cpu_id(dest_apic_id).filter(|dest| cpu_set.contains_cpu(*dest)) { + Some(dest) => dest_set.set_bit(dest), + None => warn!( + "drop IPI from CPU{} to APIC ID {:#x} outside its zone", + cpu_id, dest_apic_id + ), + } } IpiDestShorthand::SELF => { dest_set.set_bit(cpu_id); @@ -116,10 +123,10 @@ pub fn send_ipi(value: u64) -> HvResult { match delivery_mode { IpiDeliveryMode::FIXED => { // info!("dest: {:x}, vector: {:x}", dest, vector); - inject_vector(dest, vector, None, false, false); + post_guest_vector(dest, vector, None, false, false); } IpiDeliveryMode::NMI => { - inject_vector(dest, 2, None, false, false); + post_guest_vector(dest, 2, None, false, false); } IpiDeliveryMode::INIT => {} IpiDeliveryMode::START_UP => { diff --git a/src/arch/x86_64/trap.rs b/src/arch/x86_64/trap.rs index 5cec70c2e..9a251a2d2 100644 --- a/src/arch/x86_64/trap.rs +++ b/src/arch/x86_64/trap.rs @@ -30,8 +30,8 @@ use crate::{ cpu_data::{this_cpu_data, this_zone}, device::{ irqchip::{ - inject_vector, pic::{ioapic::irqs, lapic::VirtLocalApic}, + post_guest_vector, }, uart::{virt_console_io_read, virt_console_io_write, UartReg}, }, @@ -140,7 +140,7 @@ fn handle_irq(vector: u8, path: IrqPath) { IdtVector::APIC_SPURIOUS_VECTOR | IdtVector::APIC_ERROR_VECTOR if !is_timer => {} _ => { if vector >= 0x20 && this_cpu_data().vcpu.state.is_running() { - inject_vector(this_cpu_id(), vector, None, false, false); + post_guest_vector(this_cpu_id(), vector, None, false, false); } } } diff --git a/src/arch/x86_64/vcpu.rs b/src/arch/x86_64/vcpu.rs index 84a528a02..c6fc2ce84 100644 --- a/src/arch/x86_64/vcpu.rs +++ b/src/arch/x86_64/vcpu.rs @@ -20,7 +20,7 @@ pub const GUEST_IRQ_NR: usize = 256; pub const GUEST_LINES: &[usize] = &[]; // Architecture-private vCPU state placeholder. -// Guest interrupts still go through `PENDING_VECTORS` via `inject_vector()`. +// Guest interrupts still go through `PENDING_VECTORS` via `post_guest_vector()`. pub struct ArchVcpu; impl ArchVcpu { diff --git a/src/device/irqchip/aia/mod.rs b/src/device/irqchip/aia/mod.rs index dbd721c78..1c4d98069 100644 --- a/src/device/irqchip/aia/mod.rs +++ b/src/device/irqchip/aia/mod.rs @@ -36,26 +36,26 @@ use crate::platform::{ BOARD_APLIC_INTERRUPTS_NUM, IMSIC_GUEST_INDEX, IMSIC_GUEST_NUM, IMSIC_S_BASE, }; use crate::root_zone_config; -use crate::zone::Zone; +use crate::zone::{find_zone, this_zone_id, IrqLifecycleGuard, IrqPostGuard, Zone}; +use alloc::sync::Arc; pub use aplic::*; use heapless::FnvIndexMap; pub use imsic::*; -use spin::Once; +use spin::{Mutex, Once}; pub use vaplic::*; pub use vimsic::*; // Physical APLIC pub static APLIC: Once = Once::new(); // The MAX_ZONE_NUM should be the power of 2. -static mut VAPLIC_MAP: Option> = None; +static VAPLIC_MAP: Mutex, MAX_ZONE_NUM>> = + Mutex::new(FnvIndexMap::new()); /// Per-zone IOMMU MSI page table (one 4 KiB frame, 16-byte PTEs; invalid entries are all-zero). -static mut MSI_PT_MAP: Option> = None; +static MSI_PT_MAP: Mutex> = Mutex::new(FnvIndexMap::new()); /// Physical base of the MSI page-table frame for `zone_id` (`vm_id`), after `vimsic_init`. pub fn msi_pt_paddr_for_zone(zone_id: usize) -> Option { - // Once the MSI_PT for one zone is initialized, it wouldn't change. - // Here don't use lock, because it's read-only operation here. - unsafe { MSI_PT_MAP.as_ref()?.get(&zone_id).map(|f| f.start_paddr()) } + MSI_PT_MAP.lock().get(&zone_id).map(|f| f.start_paddr()) } pub fn init_aplic(aplic_base: usize) { @@ -71,11 +71,6 @@ pub fn primary_init_early() { let root_config = root_zone_config(); init_aplic(root_config.arch_config.aplic_base as usize); host_aplic().init_global(this_cpu_id(), BOARD_APLIC_INTERRUPTS_NUM); - - unsafe { - VAPLIC_MAP = Some(FnvIndexMap::new()); - MSI_PT_MAP = Some(FnvIndexMap::new()); - } } pub fn primary_init_late() { @@ -110,37 +105,47 @@ pub fn inject_irq(irq: usize, is_hardware: bool) { } // For hvisor on qemu-aia, only software interrupt will be injected. // Hardware interrupt will be transferred to IMSIC's interrupt file directly. - let target = this_cpu_data() - .zone - .as_ref() - .unwrap() - .get_vaplic() - .vaplic_get_target(irq); - let mut hart = (target >> 18) & 0x3FFF; + let irq_post = IrqPostGuard::lock(); + vaplic_pulse(&irq_post, this_zone_id(), irq); +} + +/// Pulse software interrupt `irq` in zone `zone_id`'s vAPLIC; callable from any CPU. +pub fn vaplic_pulse(_irq_post: &IrqPostGuard, zone_id: usize, irq: usize) -> bool { + let Some(target) = VAPLIC_MAP + .lock() + .get(&zone_id) + .map(|vaplic| vaplic.vaplic_get_target(irq)) + else { + return false; + }; + let Some(cpu_set) = find_zone(zone_id).map(|zone| zone.read().cpu_set()) else { + return false; + }; + let Some(first_cpu) = cpu_set.first_cpu() else { + return false; + }; + let vhart = ((target >> 18) & 0x3FFF) as usize; // let guest = (target >> 12) & 0x3F; let eiid = target & 0x3FF; - // Transfer vhart_id to phart_id. - hart = hart - + this_cpu_data() - .zone - .as_ref() - .unwrap() - .read() - .cpu_set() - .first_cpu() - .unwrap() as u32; - imsic_trigger(hart, IMSIC_GUEST_INDEX as u32, eiid); + // Transfer vhart_id to phart_id. The guest writes the target, so the hart + // must stay inside its zone. + let hart = vhart + first_cpu; + if !cpu_set.contains_cpu(hart) { + warn!( + "drop vAPLIC IRQ {} of zone {} to hart {} outside the zone", + irq, zone_id, hart + ); + return false; + } + imsic_trigger(hart as u32, IMSIC_GUEST_INDEX as u32, eiid); + true } /// Print all keys in the VAPLIC_MAP for debugging purposes. fn print_keys() { info!("VAPLIC_MAP keys:"); - unsafe { - if let Some(map) = &VAPLIC_MAP { - for (&key, _) in map.iter() { - info!("\tZone {}'s vaplic in VAPLIC_MAP", key); - } - } + for (&key, _) in VAPLIC_MAP.lock().iter() { + info!("\tZone {}'s vaplic in VAPLIC_MAP", key); } } @@ -148,21 +153,15 @@ impl Zone { /// Initial the virtual APLIC related to thiz Zone. pub fn vaplic_init(&mut self, config: &HvZoneConfig) { // Create a new VirtualAPLIC for this Zone. - unsafe { - if let Some(map) = &mut VAPLIC_MAP { - if map.contains_key(&self.id()) { - panic!("VirtualAPLIC for Zone {} already exists!", self.id()); - } - let vaplic = vaplic::VirtualAPLIC::new( - config.arch_config.aplic_base, - BOARD_APLIC_INTERRUPTS_NUM, - ); - // Insert into Map - let _ = map.insert(self.id(), vaplic); - } else { - panic!("VAPLIC_MAP is not initialized!"); - } + let mut map = VAPLIC_MAP.lock(); + if map.contains_key(&self.id()) { + panic!("VirtualAPLIC for Zone {} already exists!", self.id()); } + let vaplic = + vaplic::VirtualAPLIC::new(config.arch_config.aplic_base, BOARD_APLIC_INTERRUPTS_NUM); + // Insert into Map + let _ = map.insert(self.id(), Arc::new(vaplic)); + drop(map); info!( "VirtualAPLIC for Zone {} initialized successfully", self.id() @@ -174,31 +173,24 @@ impl Zone { pub fn vimsic_init(&self, _config: &HvZoneConfig) { info!("Zone {} vIMSIC init", self.id()); let msi_pt = vimsic::vimsic_init(self, IMSIC_S_BASE, IMSIC_GUEST_NUM); - unsafe { - if let Some(map) = &mut MSI_PT_MAP { - if map.contains_key(&self.id()) { - panic!("MSI page table for Zone {} already exists!", self.id()); - } - if map.insert(self.id(), msi_pt).is_err() { - panic!("MSI_PT_MAP full"); - } - } else { - panic!("MSI_PT_MAP is not initialized!"); - } + let mut map = MSI_PT_MAP.lock(); + if map.contains_key(&self.id()) { + panic!("MSI page table for Zone {} already exists!", self.id()); + } + if map.insert(self.id(), msi_pt).is_err() { + panic!("MSI_PT_MAP full"); } } - pub fn get_vaplic(&self) -> &VirtualAPLIC { - unsafe { - VAPLIC_MAP - .as_ref() - .expect("VAPLIC_MAP is not initialized!") - .get(&self.id()) - .expect("VirtualAPLIC for this Zone does not exist!") - } + pub fn get_vaplic(&self) -> Arc { + VAPLIC_MAP + .lock() + .get(&self.id()) + .cloned() + .expect("VirtualAPLIC for this Zone does not exist!") } - pub fn arch_irqchip_reset(&self) { + pub fn arch_irqchip_reset(&self, _irq_lifecycle: &IrqLifecycleGuard) { // We should make sure only one cpu to do this. // This func will only be called by one root zone's cpu. let host_aplic = host_aplic(); @@ -226,18 +218,8 @@ impl Zone { crate::event::clear_events(cpuid); }); - unsafe { - if let Some(map) = &mut VAPLIC_MAP { - map.remove(&self.id()); - } else { - panic!("VAPLIC_MAP is not initialized!"); - } - if let Some(map) = &mut MSI_PT_MAP { - let _ = map.remove(&self.id()); - } else { - panic!("MSI_PT_MAP is not initialized!"); - } - } + VAPLIC_MAP.lock().remove(&self.id()); + MSI_PT_MAP.lock().remove(&self.id()); print_keys(); } diff --git a/src/device/irqchip/mod.rs b/src/device/irqchip/mod.rs index 25b3c4ac4..8423dcecc 100644 --- a/src/device/irqchip/mod.rs +++ b/src/device/irqchip/mod.rs @@ -24,11 +24,6 @@ use core::sync::atomic::{fence, Ordering}; #[cfg(target_arch = "aarch64")] pub(crate) const SGIS_NUM: usize = SGI_RANGE.end; -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -pub fn handle_virtio_irq_event() { - crate::device::virtio_trampoline::handle_virtio_irq(); -} - /// What a `post_guest_irq()` call does to the guest IRQ. // // Each IRQ number has a fixed trigger type: numbers in `GUEST_LINES` are @@ -328,4 +323,4 @@ pub mod pic; pub use ls7a2000::{percpu_init, primary_init_early, primary_init_late}; #[cfg(target_arch = "x86_64")] -pub use pic::{inject_irq, inject_vector, percpu_init, primary_init_early, primary_init_late}; +pub use pic::{inject_irq, percpu_init, post_guest_vector, primary_init_early, primary_init_late}; diff --git a/src/device/irqchip/pic/ioapic.rs b/src/device/irqchip/pic/ioapic.rs index 4d1b07122..b1b642a26 100644 --- a/src/device/irqchip/pic/ioapic.rs +++ b/src/device/irqchip/pic/ioapic.rs @@ -21,12 +21,12 @@ use crate::{ zone::HvArchZoneConfig, }, cpu_data::this_zone, - device::irqchip::pic::inject_vector, device::irqchip::pic::ioapic_state::{Delivery, IoApicState}, + device::irqchip::pic::post_guest_vector, error::HvResult, memory::{GuestPhysAddr, MMIOAccess}, platform::ROOT_ZONE_IOAPIC_BASE, - zone::{this_zone_id, Zone}, + zone::{this_zone_id, IrqLifecycleGuard, IrqPostGuard, Zone}, }; use alloc::vec::Vec; use bit_field::BitField; @@ -84,15 +84,21 @@ impl VirtIoApic { if gpa == 0 { return Ok(ioapic.lock().cur_reg as _); } - assert!(gpa == 0x10); + if gpa != 0x10 { + warn!("ignore vIOAPIC read at offset {:#x}", gpa); + return Ok(0); + } let inner = ioapic.lock(); match inner.cur_reg { IoApicReg::ID => Ok(0), IoApicReg::VERSION => Ok(IOAPIC_MAX_REDIRECT_ENTRIES << 16 | 0x11), // max redirect entries: 0x17, version: 0x11 IoApicReg::ARBITRATION => Ok(0), - mut reg => { - reg -= IoApicReg::TABLE_BASE; + reg => { + // Registers 0x03..0x0f are reserved. + let Some(reg) = reg.checked_sub(IoApicReg::TABLE_BASE) else { + return Ok(0); + }; let index = (reg >> 1) as usize; // info!("ioapic read index: {:x}", index); if this_zone_id() != 0 && index == 4 { @@ -124,14 +130,20 @@ impl VirtIoApic { ioapic.lock().cur_reg = value as _; return Ok(()); } - assert!(gpa == 0x10); + if gpa != 0x10 { + warn!("ignore vIOAPIC write at offset {:#x}", gpa); + return Ok(()); + } let mut inner = ioapic.lock(); let mut replay = None; match inner.cur_reg { IoApicReg::ID | IoApicReg::VERSION | IoApicReg::ARBITRATION => {} - mut reg => { - reg -= IoApicReg::TABLE_BASE; + reg => { + // Registers 0x03..0x0f are reserved. + let Some(reg) = reg.checked_sub(IoApicReg::TABLE_BASE) else { + return Ok(()); + }; let index = (reg >> 1) as usize; if let Some(entry) = inner.state.entry(index) { let value = if reg % 2 == 0 { @@ -166,7 +178,7 @@ impl VirtIoApic { fn inject_delivery(delivery: Delivery, allow_repeat: bool) { let dest = try_get_cpu_id(delivery.entry.get_bits(56..=63) as usize).unwrap_or_else(this_cpu_id); - inject_vector( + post_guest_vector( dest, delivery.entry as u8, None, @@ -175,19 +187,19 @@ impl VirtIoApic { ); } - fn get_irq_cpu(&self, irq: usize, zone_id: usize) -> Option { - let ioapic = self.inner.get(zone_id)?; - let entry = ioapic.lock().state.entry(irq)?; - Some(try_get_cpu_id(entry.get_bits(56..=63) as usize).unwrap_or_else(this_cpu_id)) - } - - fn pulse(&self, irq: usize, allow_repeat: bool) { - let ioapic = self.inner.get(this_zone_id()).unwrap(); + fn pulse(&self, zone_id: usize, irq: usize, allow_repeat: bool) -> bool { + let Some(ioapic) = self.inner.get(zone_id) else { + return false; + }; let mut inner = ioapic.lock(); + if inner.state.entry(irq).is_none() { + return false; + } let delivery = inner.state.pulse(irq); if let Some(delivery) = delivery { Self::inject_delivery(delivery, allow_repeat); } + true } fn set_line(&self, zone_id: usize, irq: usize, high: bool) -> bool { @@ -273,19 +285,28 @@ pub fn init_virt_ioapic(max_zones: usize) { VIRT_IOAPIC.call_once(|| VirtIoApic::new(max_zones)); } -pub fn ioapic_inject_irq(irq: u8, allow_repeat: bool) { - VIRT_IOAPIC.get().unwrap().pulse(irq as _, allow_repeat); +/// Pulse an edge on `irq` of zone `zone_id`; the RTE target CPU may be remote. +pub fn ioapic_pulse( + _irq_post: &IrqPostGuard, + zone_id: usize, + irq: usize, + allow_repeat: bool, +) -> bool { + VIRT_IOAPIC.get().unwrap().pulse(zone_id, irq, allow_repeat) } -pub fn get_irq_cpu(irq: usize, zone_id: usize) -> usize { +/// Pulse an edge on `irq` of the current CPU's own zone. +// +// Needs no `IrqPostGuard`: that zone cannot be started or shut down while one of its CPUs +// runs this. +pub fn ioapic_pulse_this_zone(irq: usize, allow_repeat: bool) -> bool { VIRT_IOAPIC .get() .unwrap() - .get_irq_cpu(irq, zone_id) - .unwrap() + .pulse(this_zone_id(), irq, allow_repeat) } -pub fn ioapic_set_line(zone_id: usize, irq: usize, high: bool) -> bool { +pub fn ioapic_set_line(_irq_post: &IrqPostGuard, zone_id: usize, irq: usize, high: bool) -> bool { VIRT_IOAPIC.get().unwrap().set_line(zone_id, irq, high) } @@ -293,7 +314,7 @@ pub fn ioapic_eoi(zone_id: usize, vector: u8) { VIRT_IOAPIC.get().unwrap().eoi(zone_id, vector); } -pub fn ioapic_reset(zone_id: usize) { +pub fn ioapic_reset(_irq_lifecycle: &IrqLifecycleGuard, zone_id: usize) { VIRT_IOAPIC.get().unwrap().reset(zone_id); } diff --git a/src/device/irqchip/pic/mod.rs b/src/device/irqchip/pic/mod.rs index 912d6660e..1ded78e19 100644 --- a/src/device/irqchip/pic/mod.rs +++ b/src/device/irqchip/pic/mod.rs @@ -22,11 +22,11 @@ use crate::{ arch::{acpi, cpu::this_cpu_id, idt, ipi, msr, pio, vmcs::Vmcs}, consts::{MAX_CPU_NUM, MAX_ZONE_NUM}, device::iommu, - zone::Zone, + zone::{IrqLifecycleGuard, Zone}, }; use alloc::{collections::vec_deque::VecDeque, vec::Vec}; use core::arch::asm; -use ioapic::ioapic_inject_irq; +use ioapic::ioapic_pulse_this_zone; use spin::{Mutex, Once}; static PENDING_VECTORS: Once = Once::new(); @@ -135,7 +135,7 @@ impl PendingVectors { } } -pub fn inject_vector( +pub fn post_guest_vector( cpu_id: usize, vector: u8, err_code: Option, @@ -180,8 +180,8 @@ pub fn disable_irq() { unsafe { asm!("cli") }; } -pub fn inject_irq(_irq: usize, allow_repeat: bool) { - ioapic_inject_irq(_irq as _, allow_repeat); +pub fn inject_irq(irq: usize, allow_repeat: bool) { + ioapic_pulse_this_zone(irq, allow_repeat); } pub fn percpu_init() {} @@ -198,7 +198,7 @@ pub fn primary_init_early() { pub fn primary_init_late() {} impl Zone { - pub fn arch_irqchip_reset(&self) { + pub fn arch_irqchip_reset(&self, _irq_lifecycle: &IrqLifecycleGuard) { #[cfg(intel_vtd)] iommu::clear_dma_translation_tables(self.id()); } diff --git a/src/device/irqchip/plic/mod.rs b/src/device/irqchip/plic/mod.rs index 55b22bc86..a9b5009da 100644 --- a/src/device/irqchip/plic/mod.rs +++ b/src/device/irqchip/plic/mod.rs @@ -32,7 +32,7 @@ use crate::cpu_data::this_cpu_data; use crate::error::HvResult; use crate::memory::mmio::MMIOAccess; use crate::platform::*; -use crate::zone::Zone; +use crate::zone::{IrqLifecycleGuard, IrqPostGuard, Zone}; use alloc::collections::BTreeMap; use alloc::sync::Arc; use alloc::vec::Vec; @@ -101,6 +101,14 @@ pub fn inject_irq(irq: usize, is_hardware: bool) { vplic.inject_irq(vcontext_id, irq, is_hardware); } +/// Pulse software interrupt `irq` in zone `zone_id`'s vPLIC; callable from any CPU. +pub fn vplic_pulse(_irq_post: &IrqPostGuard, zone_id: usize, irq: usize) -> bool { + let Some(vplic) = VPLIC_MAP.lock().get(&zone_id).cloned() else { + return false; + }; + vplic.trigger_soft_irq(irq) +} + /// handle Zone's plic mmio access. pub fn vplic_handler(mmio: &mut MMIOAccess, _arg: usize) -> HvResult { // let value = this_cpu_data() @@ -168,7 +176,7 @@ impl Zone { .clone() } - pub fn arch_irqchip_reset(&self) { + pub fn arch_irqchip_reset(&self, _irq_lifecycle: &IrqLifecycleGuard) { // We should make sure only one cpu to do this. // This func will only be called by one root zone's cpu. let host_plic = host_plic(); diff --git a/src/device/irqchip/plic/vplic.rs b/src/device/irqchip/plic/vplic.rs index 02bb9c2ba..ac66e1992 100644 --- a/src/device/irqchip/plic/vplic.rs +++ b/src/device/irqchip/plic/vplic.rs @@ -105,17 +105,37 @@ impl VirtualPLIC { if inner.hw[intr_id] { self.update_hart_line(&inner, vcontext_id); } else { - for vcontext_id in 0..self.num_contexts { - if vcontext_id % NUM_CONTEXTS_PER_HART != 1 { - continue; - } - if inner.vplic_get_enable(intr_id, vcontext_id) - && inner.vplic_get_priority(intr_id) - > inner.vplic_get_threshold(vcontext_id) - { - self.update_hart_line(&inner, vcontext_id); - } - } + self.update_enabled_hart_lines(&inner, intr_id); + } + } + } + + /// Trigger software interrupt `intr_id`; callable from any CPU. + /// Returns false if `intr_id` is out of range or a hardware interrupt. + pub fn trigger_soft_irq(&self, intr_id: usize) -> bool { + if intr_id == 0 || intr_id > self.max_interrupts { + return false; + } + let mut inner = self.inner.lock(); + if inner.vplic_get_hw(intr_id) { + return false; + } + if !inner.vplic_get_pending(intr_id) { + inner.vplic_set_pending(intr_id, true); + self.update_enabled_hart_lines(&inner, intr_id); + } + true + } + + fn update_enabled_hart_lines(&self, inner: &VirtualPLICInner, intr_id: usize) { + for vcontext_id in 0..self.num_contexts { + if vcontext_id % NUM_CONTEXTS_PER_HART != 1 { + continue; + } + if inner.vplic_get_enable(intr_id, vcontext_id) + && inner.vplic_get_priority(intr_id) > inner.vplic_get_threshold(vcontext_id) + { + self.update_hart_line(inner, vcontext_id); } } } diff --git a/src/device/virtio_trampoline.rs b/src/device/virtio_trampoline.rs index 48205181e..07a1a60b2 100644 --- a/src/device/virtio_trampoline.rs +++ b/src/device/virtio_trampoline.rs @@ -20,24 +20,25 @@ #![deny(unused_mut)] #![deny(unused)] -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -use crate::device::irqchip::inject_irq; +#[cfg(any(target_arch = "aarch64", target_arch = "loongarch64"))] +use crate::arch::cpu::get_target_cpu; +#[cfg(all(aia, target_arch = "riscv64"))] +use crate::device::irqchip::aia::vaplic_pulse; #[cfg(target_arch = "loongarch64")] use crate::device::irqchip::ls7a2000::post_guest_hwi; +#[cfg(target_arch = "x86_64")] +use crate::device::irqchip::pic::ioapic::ioapic_pulse; +#[cfg(all(plic, target_arch = "riscv64"))] +use crate::device::irqchip::plic::vplic_pulse; #[cfg(target_arch = "aarch64")] use crate::device::irqchip::post_guest_spi; -use crate::{arch::cpu::get_target_cpu, platform::IRQ_WAKEUP_VIRTIO_DEVICE}; +use crate::platform::IRQ_WAKEUP_VIRTIO_DEVICE; +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +use crate::zone::IrqPostGuard; use crate::{ arch::cpu::this_cpu_id, consts::MAX_WAIT_TIMES, error::HvResult, memory::MMIOAccess, zone::this_zone_id, }; -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -use crate::{ - event::{send_event, IPI_EVENT_WAKEUP_VIRTIO_DEVICE}, - hypercall::SGI_IPI_ID, -}; -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -use alloc::collections::BTreeMap; use core::{ fmt::{Debug, Formatter, Result}, mem::size_of, @@ -49,9 +50,6 @@ use tock_registers::{ registers::ReadWrite, }; -/// Save the irqs the virtio-device wants to inject. The format is >, and the first elem of List is the valid len of it. -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -pub static VIRTIO_IRQS: Mutex> = Mutex::new(BTreeMap::new()); // Controller of the shared memory the root linux's virtio device and hvisor shares. pub static VIRTIO_PCI_BRIDGE: Mutex = Mutex::new(VirtioPCIBridge::dummy()); pub static VIRTIO_BRIDGE: VirtioBridgeController = VirtioBridgeController::new(); @@ -147,30 +145,24 @@ pub fn mmio_virtio_handler(mmio: &mut MMIOAccess, base: usize) -> HvResult { pub fn check_need_wakeup_and_send_ipi(is_send_ipi: &mut bool) { if !(*is_send_ipi) && VIRTIO_BRIDGE.need_wakeup() { debug!("need wakeup (recheck), sending ipi to wake up virtio device"); + #[cfg(any(target_arch = "aarch64", target_arch = "loongarch64"))] let root_cpu = get_target_cpu(IRQ_WAKEUP_VIRTIO_DEVICE, 0); #[cfg(target_arch = "loongarch64")] post_guest_hwi(root_cpu, IRQ_WAKEUP_VIRTIO_DEVICE, true); #[cfg(target_arch = "aarch64")] post_guest_spi(root_cpu, IRQ_WAKEUP_VIRTIO_DEVICE); #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] - send_event(root_cpu, SGI_IPI_ID as _, IPI_EVENT_WAKEUP_VIRTIO_DEVICE); + let irq_post = IrqPostGuard::lock(); + #[cfg(target_arch = "x86_64")] + ioapic_pulse(&irq_post, 0, IRQ_WAKEUP_VIRTIO_DEVICE, false); + #[cfg(all(plic, target_arch = "riscv64"))] + vplic_pulse(&irq_post, 0, IRQ_WAKEUP_VIRTIO_DEVICE); + #[cfg(all(aia, target_arch = "riscv64"))] + vaplic_pulse(&irq_post, 0, IRQ_WAKEUP_VIRTIO_DEVICE); *is_send_ipi = true; } } -/// When virtio req type is notify, root zone will send sgi to non root, \ -/// and non root will call this function. -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -pub fn handle_virtio_irq() { - let mut map = VIRTIO_IRQS.lock(); - let irq_list = map.get_mut(&this_cpu_id()).unwrap(); - let len = irq_list[0] as usize; - for irq_id in irq_list[1..=len].iter() { - inject_irq(*irq_id as _, false); - } - irq_list[0] = 0; -} - /// Virtio bridge controller. pub struct VirtioBridgeController { base_address: AtomicUsize, diff --git a/src/event.rs b/src/event.rs index 1c41d928e..2ac0fb5eb 100644 --- a/src/event.rs +++ b/src/event.rs @@ -14,16 +14,13 @@ // Authors: // #![allow(unused)] -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] -use crate::device::irqchip::handle_virtio_irq_event; -#[cfg(any(target_arch = "riscv64", target_arch = "x86_64", virtio_pci))] +#[cfg(virtio_pci)] use crate::device::irqchip::inject_irq; use crate::{ arch::cpu::this_cpu_id, arch::ipi::arch_notify_event, consts::{IPI_EVENT_DWC_MSI_INJECT, IPI_EVENT_VCPU_SUSPEND, MAX_CPU_NUM}, cpu_data::{this_cpu_data, vcpu_suspend, CpuSet}, - platform::IRQ_WAKEUP_VIRTIO_DEVICE, }; #[cfg(virtio_pci)] use crate::{ @@ -35,8 +32,6 @@ use spin::Mutex; pub const IPI_EVENT_WAKEUP: usize = 0; pub const IPI_EVENT_SHUTDOWN: usize = 1; -pub const IPI_EVENT_VIRTIO_INJECT_IRQ: usize = 2; -pub const IPI_EVENT_WAKEUP_VIRTIO_DEVICE: usize = 3; pub const IPI_EVENT_VIRTIO_PCI_CONFIG: usize = 10; pub const IPI_EVENT_VIRTIO_PCI_DATA: usize = 11; pub const IPI_EVENT_VIRTIO_PCI_DONE: usize = 12; @@ -124,16 +119,6 @@ fn handle_event(event: Option) -> bool { cpu_data.arch_cpu.idle(); false } - #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] - Some(IPI_EVENT_VIRTIO_INJECT_IRQ) => { - handle_virtio_irq_event(); - true - } - #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] - Some(IPI_EVENT_WAKEUP_VIRTIO_DEVICE) => { - inject_irq(IRQ_WAKEUP_VIRTIO_DEVICE, false); - true - } Some(IPI_EVENT_DWC_MSI_INJECT) => { #[cfg(all(target_arch = "aarch64", irq_gicv3, dwc_pcie, dwc_msi))] { diff --git a/src/hypercall/mod.rs b/src/hypercall/mod.rs index a01905b07..f23b1b99c 100644 --- a/src/hypercall/mod.rs +++ b/src/hypercall/mod.rs @@ -22,26 +22,18 @@ use crate::cpu_data::{get_cpu_data, PerCpu, VcpuState}; use crate::device::virtio_trampoline::{ VirtioPCIHypercallOp, VIRTIO_BRIDGE, VIRTIO_PCI_BRIDGE, VIRTIO_PCI_HYPERCALL_VERSION, }; -#[cfg(target_arch = "riscv64")] -use crate::device::virtio_trampoline::{MAX_DEVS, VIRTIO_IRQS}; use crate::error::HvResult; use crate::pci::pci_config::GLOBAL_PCIE_LIST; use crate::zone::{ add_zone, all_zones_info, clear_zone_boot_mode, find_zone, is_this_root_zone, remove_zone, set_zone_boot_mode, zone_create, ZoneInfo, }; +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +use crate::zone::{IrqLifecycleGuard, IrqPostGuard}; -#[cfg(target_arch = "riscv64")] -use crate::event::IPI_EVENT_VIRTIO_INJECT_IRQ; use crate::event::{send_event, IPI_EVENT_SHUTDOWN, IPI_EVENT_VIRTIO_PCI_DONE, IPI_EVENT_WAKEUP}; use core::convert::TryFrom; use numeric_enum_macro::numeric_enum; -#[cfg(target_arch = "x86_64")] -use spin::RwLock; - -// Serialize in-flight IRQ-line hypercalls with zone stop and restart. -#[cfg(target_arch = "x86_64")] -static X86_IOAPIC_LIFECYCLE: RwLock<()> = RwLock::new(()); numeric_enum! { #[repr(u64)] @@ -151,11 +143,9 @@ impl<'a> HyperCall<'a> { "Virtio send irq operation over non-root zones: unsupported!" ); } - #[cfg(target_arch = "x86_64")] - let _irq_lifecycle = X86_IOAPIC_LIFECYCLE.read(); + #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] + let irq_post = IrqPostGuard::lock(); let mut res_agent = VIRTIO_BRIDGE.res_agent(); - #[cfg(target_arch = "riscv64")] - let mut map_irq = VIRTIO_IRQS.lock(); while !res_agent.is_empty() { let (_res_front, irq_id, target_zone) = res_agent.peek_front(); let Some(zone) = find_zone(target_zone as _) else { @@ -163,9 +153,9 @@ impl<'a> HyperCall<'a> { continue; }; // Reuse `zone`: a second lookup may panic if the zone is shut down. - #[cfg(not(target_arch = "x86_64"))] + #[cfg(any(target_arch = "aarch64", target_arch = "loongarch64"))] let target_cpu = zone.read().cpu_set().first_cpu().unwrap(); - #[cfg(target_arch = "x86_64")] + #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] drop(zone); #[cfg(target_arch = "loongarch64")] @@ -185,6 +175,7 @@ impl<'a> HyperCall<'a> { #[cfg(target_arch = "x86_64")] { crate::device::irqchip::pic::ioapic::ioapic_set_line( + &irq_post, target_zone as usize, irq_id as usize, true, @@ -195,23 +186,24 @@ impl<'a> HyperCall<'a> { #[cfg(target_arch = "riscv64")] { - let irq_list = map_irq.entry(target_cpu).or_insert([0; MAX_DEVS + 1]); - self.wait_for_interrupt(irq_list); - if !irq_list[1..=irq_list[0] as usize].contains(&irq_id) { - let len = irq_list[0] as usize; - assert!(len + 1 < MAX_DEVS); - irq_list[len + 1] = irq_id; - irq_list[0] += 1; - send_event( - target_cpu as _, - SGI_IPI_ID as _, - IPI_EVENT_VIRTIO_INJECT_IRQ, - ); + #[cfg(plic)] + let pulsed = crate::device::irqchip::plic::vplic_pulse( + &irq_post, + target_zone as usize, + irq_id as usize, + ); + #[cfg(aia)] + let pulsed = crate::device::irqchip::aia::vaplic_pulse( + &irq_post, + target_zone as usize, + irq_id as usize, + ); + if !pulsed { + warn!("virtio: drop irq {} for zone {}", irq_id, target_zone); } + res_agent.advance_front(); + continue; } - - #[cfg(target_arch = "riscv64")] - res_agent.advance_front(); } drop(res_agent); HyperCallResult::Ok(0) @@ -261,7 +253,7 @@ impl<'a> HyperCall<'a> { ); } #[cfg(target_arch = "x86_64")] - let _irq_lifecycle = X86_IOAPIC_LIFECYCLE.read(); + let irq_post = IrqPostGuard::lock(); let Some(zone) = find_zone(target_zone) else { return hv_result_err!(EINVAL, format!("zone {} does not exist", target_zone)); }; @@ -287,7 +279,12 @@ impl<'a> HyperCall<'a> { #[cfg(target_arch = "x86_64")] { - if !crate::device::irqchip::pic::ioapic::ioapic_set_line(target_zone, irq_id, false) { + if !crate::device::irqchip::pic::ioapic::ioapic_set_line( + &irq_post, + target_zone, + irq_id, + false, + ) { return hv_result_err!(EINVAL, format!("invalid x86 IOAPIC pin {}", irq_id)); } return HyperCallResult::Ok(0); @@ -322,6 +319,8 @@ impl<'a> HyperCall<'a> { ) ); } + #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] + let irq_lifecycle = IrqLifecycleGuard::lock(); let zone_result = zone_create(config); clear_zone_boot_mode(config.zone_id as usize); let zone = zone_result?; @@ -329,8 +328,6 @@ impl<'a> HyperCall<'a> { let target_data = get_cpu_data(boot_cpu as _); let _lock = target_data.ctrl_lock.lock(); - #[cfg(target_arch = "x86_64")] - let _irq_lifecycle = X86_IOAPIC_LIFECYCLE.write(); if target_data.vcpu.state.is_stopped() { info!("boot_cpu: {}", boot_cpu); @@ -340,7 +337,10 @@ impl<'a> HyperCall<'a> { zone.read().cpu_set().iter().for_each(|cpu_id| { crate::device::irqchip::pic::clear_vectors(cpu_id); }); - crate::device::irqchip::pic::ioapic::ioapic_reset(config.zone_id as usize); + crate::device::irqchip::pic::ioapic::ioapic_reset( + &irq_lifecycle, + config.zone_id as usize, + ); } target_data.vcpu.state.store(VcpuState::Ready); } else { @@ -348,8 +348,8 @@ impl<'a> HyperCall<'a> { return hv_result_err!(EBUSY); }; add_zone(zone); - #[cfg(target_arch = "x86_64")] - drop(_irq_lifecycle); + #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] + drop(irq_lifecycle); send_event(boot_cpu, SGI_IPI_ID as _, IPI_EVENT_WAKEUP); drop(_lock); HyperCallResult::Ok(0) @@ -366,10 +366,6 @@ impl<'a> HyperCall<'a> { if zone_id == 0 { return hv_result_err!(EINVAL); } - // avoid virtio daemon send sgi to the shutdowning zone - #[cfg(target_arch = "riscv64")] - let mut map_irq = VIRTIO_IRQS.lock(); - let zone = match find_zone(zone_id as _) { Some(zone) => zone, _ => { @@ -380,10 +376,7 @@ impl<'a> HyperCall<'a> { } }; #[cfg(target_arch = "x86_64")] - { - let _irq_lifecycle = X86_IOAPIC_LIFECYCLE.write(); - crate::device::irqchip::pic::ioapic::ioapic_begin_shutdown(zone_id as usize); - } + crate::device::irqchip::pic::ioapic::ioapic_begin_shutdown(zone_id as usize); let zone_w = zone.write(); zone_w.cpu_set().iter().for_each(|cpu_id| { @@ -392,11 +385,6 @@ impl<'a> HyperCall<'a> { #[cfg(target_arch = "loongarch64")] get_cpu_data(cpu_id).vcpu.clear_irq_state(); send_event(cpu_id, SGI_IPI_ID as _, IPI_EVENT_SHUTDOWN); - // set the virtio irq list's len to 0 - #[cfg(target_arch = "riscv64")] - if let Some(irq_list) = map_irq.get_mut(&cpu_id) { - irq_list[0] = 0; - } }); let mut count: usize = 0; @@ -424,6 +412,11 @@ impl<'a> HyperCall<'a> { }); drop(zone_w); + #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] + let irq_lifecycle = IrqLifecycleGuard::lock(); + #[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] + zone.arch_irqchip_reset(&irq_lifecycle); + #[cfg(not(any(target_arch = "riscv64", target_arch = "x86_64")))] zone.arch_irqchip_reset(); // Remove viommu instance related to this zone. @@ -440,8 +433,6 @@ impl<'a> HyperCall<'a> { } drop(pci_list); - #[cfg(target_arch = "x86_64")] - let _irq_lifecycle = X86_IOAPIC_LIFECYCLE.write(); remove_zone(zone_id as _); info!("zone {} has been shutdown", zone_id); HyperCallResult::Ok(0) diff --git a/src/zone.rs b/src/zone.rs index 59db65d83..9de853a7e 100644 --- a/src/zone.rs +++ b/src/zone.rs @@ -822,7 +822,44 @@ impl ZoneInner { } } +/// Required to post an IRQ into another zone's virtual irqchip. +// +// Excludes zone start and shutdown while held. +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +pub struct IrqPostGuard { + _guard: RwLockReadGuard<'static, ()>, +} + +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +impl IrqPostGuard { + pub fn lock() -> Self { + Self { + _guard: ZONE_IRQ_LIFECYCLE.read(), + } + } +} + +/// Required to reset a zone's virtual irqchip on zone start or shutdown. +// +// Excludes every `IrqPostGuard` holder while held. +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +pub struct IrqLifecycleGuard { + _guard: RwLockWriteGuard<'static, ()>, +} + +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +impl IrqLifecycleGuard { + pub fn lock() -> Self { + Self { + _guard: ZONE_IRQ_LIFECYCLE.write(), + } + } +} + static ZONE_LIST: RwLock>> = RwLock::new(vec![]); +// Only reachable through `IrqPostGuard` and `IrqLifecycleGuard`. +#[cfg(any(target_arch = "riscv64", target_arch = "x86_64"))] +static ZONE_IRQ_LIFECYCLE: RwLock<()> = RwLock::new(()); static ZONE_BOOT_MODES: Mutex<[Option; MAX_ZONE_NUM]> = Mutex::new([None; MAX_ZONE_NUM]);