hcl/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Crate for interacting with the hypervisor via the /dev/mshv_vtl device and
5//! related kernel functionality.
6
7#![cfg(target_os = "linux")]
8// UNSAFETY: Calling ioctls.
9#![expect(unsafe_code)]
10
11use hvdef::Vtl;
12use hvdef::hypercall::HvInputVtl;
13use inspect::Inspect;
14use thiserror::Error;
15
16pub mod ioctl;
17mod mapped_page;
18pub mod protocol;
19pub mod stats;
20pub mod vmbus;
21pub mod vmsa;
22
23/// The VTL, exclusive of the paravisor VTL (VTL2).
24///
25/// This is useful to use instead of [`Vtl`] to statically ensure that the VTL
26/// is not VTL2.
27#[derive(Copy, Clone, Debug, Inspect, PartialEq, Eq, PartialOrd, Ord)]
28pub enum GuestVtl {
29    /// VTL0
30    Vtl0 = 0,
31    /// VTL1
32    Vtl1 = 1,
33}
34
35impl From<GuestVtl> for HvInputVtl {
36    fn from(value: GuestVtl) -> Self {
37        Vtl::from(value).into()
38    }
39}
40
41impl From<GuestVtl> for u8 {
42    fn from(value: GuestVtl) -> Self {
43        Vtl::from(value).into()
44    }
45}
46
47impl From<GuestVtl> for Vtl {
48    fn from(value: GuestVtl) -> Self {
49        match value {
50            GuestVtl::Vtl0 => Vtl::Vtl0,
51            GuestVtl::Vtl1 => Vtl::Vtl1,
52        }
53    }
54}
55
56/// The specified VTL is not supported in the current context.
57#[derive(Debug, Error)]
58#[error("unsupported guest VTL")]
59pub struct UnsupportedGuestVtl(pub u8);
60
61impl TryFrom<Vtl> for GuestVtl {
62    type Error = UnsupportedGuestVtl;
63
64    fn try_from(value: Vtl) -> Result<Self, Self::Error> {
65        Ok(match value {
66            Vtl::Vtl0 => GuestVtl::Vtl0,
67            Vtl::Vtl1 => GuestVtl::Vtl1,
68            _ => return Err(UnsupportedGuestVtl(value.into())),
69        })
70    }
71}
72
73impl TryFrom<u8> for GuestVtl {
74    type Error = UnsupportedGuestVtl;
75
76    fn try_from(value: u8) -> Result<Self, Self::Error> {
77        Ok(match value {
78            0 => GuestVtl::Vtl0,
79            1 => GuestVtl::Vtl1,
80            _ => return Err(UnsupportedGuestVtl(value)),
81        })
82    }
83}