|
| 1 | +/* |
| 2 | +Copyright 2026 The Hyperlight Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +//! Guest virtqueue context. |
| 18 | +
|
| 19 | +use alloc::sync::Arc; |
| 20 | +use alloc::vec::Vec; |
| 21 | +use core::num::NonZeroU16; |
| 22 | +use core::sync::atomic::AtomicU16; |
| 23 | +use core::sync::atomic::Ordering::Relaxed; |
| 24 | + |
| 25 | +use flatbuffers::FlatBufferBuilder; |
| 26 | +use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, FunctionCallType}; |
| 27 | +use hyperlight_common::flatbuffer_wrappers::function_types::{ |
| 28 | + FunctionCallResult, ParameterValue, ReturnType, ReturnValue, |
| 29 | +}; |
| 30 | +use hyperlight_common::flatbuffer_wrappers::util::estimate_flatbuffer_capacity; |
| 31 | +use hyperlight_common::outb::OutBAction; |
| 32 | +use hyperlight_common::virtq::msg::{MsgKind, VirtqMsgHeader}; |
| 33 | +use hyperlight_common::virtq::{BufferPool, Layout, Notifier, QueueStats, VirtqProducer}; |
| 34 | + |
| 35 | +use super::GuestMemOps; |
| 36 | +use crate::bail; |
| 37 | +use crate::error::Result; |
| 38 | + |
| 39 | +static REQUEST_ID: AtomicU16 = AtomicU16::new(0); |
| 40 | +const MAX_RESPONSE_CAP: usize = 4096; |
| 41 | + |
| 42 | +/// Guest-side notifier that triggers a VM exit via outb. |
| 43 | +#[derive(Clone, Copy)] |
| 44 | +pub struct GuestNotifier; |
| 45 | + |
| 46 | +impl Notifier for GuestNotifier { |
| 47 | + fn notify(&self, _stats: QueueStats) { |
| 48 | + unsafe { crate::exit::out32(OutBAction::VirtqNotify as u16, 0) }; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Type alias for the guest-side G2H producer. |
| 53 | +pub type G2hProducer = VirtqProducer<GuestMemOps, GuestNotifier, Arc<BufferPool>>; |
| 54 | + |
| 55 | +/// Virtqueue runtime state for guest-host communication. |
| 56 | +pub struct GuestContext { |
| 57 | + g2h_pool: Arc<BufferPool>, |
| 58 | + g2h_producer: G2hProducer, |
| 59 | + generation: u16, |
| 60 | +} |
| 61 | + |
| 62 | +impl GuestContext { |
| 63 | + /// Create a new context with a G2H queue. |
| 64 | + /// |
| 65 | + /// # Safety |
| 66 | + /// |
| 67 | + /// `ring_gva` must point to valid, zeroed ring memory. |
| 68 | + /// `pool_gva` must point to valid, zeroed memory. |
| 69 | + pub unsafe fn new( |
| 70 | + ring_gva: u64, |
| 71 | + num_descs: u16, |
| 72 | + pool_gva: u64, |
| 73 | + pool_size: usize, |
| 74 | + generation: u16, |
| 75 | + ) -> Self { |
| 76 | + let pool = Arc::new( |
| 77 | + BufferPool::new(pool_gva, pool_size).expect("failed to create G2H buffer pool"), |
| 78 | + ); |
| 79 | + let nz = NonZeroU16::new(num_descs).expect("G2H queue depth must be non-zero"); |
| 80 | + let layout = unsafe { Layout::from_base(ring_gva, nz) }.expect("invalid G2H ring layout"); |
| 81 | + let producer = VirtqProducer::new(layout, GuestMemOps, GuestNotifier, pool.clone()); |
| 82 | + |
| 83 | + Self { |
| 84 | + g2h_pool: pool, |
| 85 | + g2h_producer: producer, |
| 86 | + generation, |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + /// Call a host function via the G2H virtqueue. |
| 91 | + pub fn call_host_function<T: TryFrom<ReturnValue>>( |
| 92 | + &mut self, |
| 93 | + function_name: &str, |
| 94 | + parameters: Option<Vec<ParameterValue>>, |
| 95 | + return_type: ReturnType, |
| 96 | + ) -> Result<T> { |
| 97 | + let params = parameters.as_deref().unwrap_or_default(); |
| 98 | + let estimated_capacity = estimate_flatbuffer_capacity(function_name, params); |
| 99 | + |
| 100 | + let fc = FunctionCall::new( |
| 101 | + function_name.into(), |
| 102 | + parameters, |
| 103 | + FunctionCallType::Host, |
| 104 | + return_type, |
| 105 | + ); |
| 106 | + |
| 107 | + let mut builder = FlatBufferBuilder::with_capacity(estimated_capacity); |
| 108 | + let payload = fc.encode(&mut builder); |
| 109 | + |
| 110 | + let reqid = REQUEST_ID.fetch_add(1, Relaxed); |
| 111 | + let hdr = VirtqMsgHeader::new(MsgKind::Request, reqid, payload.len() as u32); |
| 112 | + let hdr_bytes = bytemuck::bytes_of(&hdr); |
| 113 | + |
| 114 | + let entry_len = VirtqMsgHeader::SIZE + payload.len(); |
| 115 | + |
| 116 | + let mut entry = self |
| 117 | + .g2h_producer |
| 118 | + .chain() |
| 119 | + .entry(entry_len) |
| 120 | + .completion(MAX_RESPONSE_CAP) |
| 121 | + .build()?; |
| 122 | + |
| 123 | + entry.write_all(hdr_bytes)?; |
| 124 | + entry.write_all(payload)?; |
| 125 | + self.g2h_producer.submit(entry)?; |
| 126 | + |
| 127 | + let Some(completion) = self.g2h_producer.poll()? else { |
| 128 | + bail!("G2H: no completion received"); |
| 129 | + }; |
| 130 | + |
| 131 | + let result_bytes = &completion.data; |
| 132 | + if result_bytes.len() > MAX_RESPONSE_CAP { |
| 133 | + bail!("G2H: response is too large"); |
| 134 | + } |
| 135 | + |
| 136 | + let payload_bytes = &result_bytes[VirtqMsgHeader::SIZE..]; |
| 137 | + let Ok(fcr) = FunctionCallResult::try_from(payload_bytes) else { |
| 138 | + bail!("G2H: malformed response"); |
| 139 | + }; |
| 140 | + |
| 141 | + let ret = fcr.into_inner()?; |
| 142 | + let Ok(ret) = T::try_from(ret) else { |
| 143 | + bail!("G2H: host return value type mismatch"); |
| 144 | + }; |
| 145 | + |
| 146 | + Ok(ret) |
| 147 | + } |
| 148 | + |
| 149 | + /// Reset ring and pool state after snapshot restore. |
| 150 | + pub(super) fn reset(&mut self, new_generation: u16) { |
| 151 | + self.g2h_producer.reset(); |
| 152 | + self.g2h_pool.reset(); |
| 153 | + self.generation = new_generation; |
| 154 | + } |
| 155 | + |
| 156 | + pub(super) fn generation(&self) -> u16 { |
| 157 | + self.generation |
| 158 | + } |
| 159 | +} |
0 commit comments