vm_topology/processor.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Processor topology types.
5
6pub mod aarch64;
7pub mod x86;
8
9cfg_if::cfg_if! {
10 if #[cfg(guest_arch = "aarch64")] {
11 pub use aarch64 as arch;
12 pub use aarch64::Aarch64Topology as TargetTopology;
13 pub use aarch64::Aarch64VpInfo as TargetVpInfo;
14 } else if #[cfg(guest_arch = "x86_64")] {
15 pub use x86 as arch;
16 pub use x86::X86Topology as TargetTopology;
17 pub use x86::X86VpInfo as TargetVpInfo;
18 } else {
19 compile_error!("Unsupported architecture");
20 }
21}
22use thiserror::Error;
23
24/// A description of the VM's processor topology.
25///
26/// Currently this just tracks the APIC IDs for the processors.
27///
28/// Build one with [`TopologyBuilder`].
29#[cfg_attr(
30 feature = "inspect",
31 derive(inspect::Inspect),
32 inspect(bound = "T: inspect::Inspect, T::ArchVpInfo: inspect::Inspect")
33)]
34#[derive(Debug, Clone)]
35pub struct ProcessorTopology<T: ArchTopology = TargetTopology> {
36 #[cfg_attr(feature = "inspect", inspect(iter_by_index))]
37 vps: Vec<T::ArchVpInfo>,
38 smt_enabled: bool,
39 vps_per_socket: u32,
40 arch: T,
41}
42
43/// Architecture-specific topology types.
44pub trait ArchTopology: Sized {
45 /// The architecture-specific VP info type.
46 type ArchVpInfo: Copy + AsRef<VpInfo>;
47
48 /// The architecture-specific [`TopologyBuilder`] generic.
49 type BuilderState;
50
51 /// Compute VP topology from a VP.
52 fn vp_topology(topology: &ProcessorTopology<Self>, info: &Self::ArchVpInfo) -> VpTopologyInfo;
53}
54
55/// A builder for [`ProcessorTopology`].
56#[derive(Debug)]
57pub struct TopologyBuilder<T: ArchTopology> {
58 vps_per_socket: u32,
59 smt_enabled: bool,
60 arch: T::BuilderState,
61}
62
63/// Error returned by [`TopologyBuilder::from_host_topology`].
64#[derive(Debug, Error)]
65pub enum HostTopologyError {
66 /// Could not find the host topology.
67 #[error("could not compute host topology via cpuid")]
68 NotFound,
69 /// The host topology has more than 2 threads per core.
70 #[error("unsupported thread-per-core count {0}")]
71 UnsupportedThreadsPerCore(u32),
72}
73
74/// Error when building a [`ProcessorTopology`].
75#[derive(Debug, Error)]
76pub enum InvalidTopology {
77 /// Failed to configure at least one VP.
78 #[error("must have at least one processor")]
79 NoVps,
80 /// Too many virtual processors.
81 #[error("too many processors requested: {requested}, max {max}")]
82 TooManyVps {
83 /// The number of processors requested.
84 requested: u32,
85 /// The maximum number of processors.
86 max: u32,
87 },
88 /// Not all processors will be addressable in XAPIC mode.
89 #[error("too many processors or too high an APIC ID {0} for xapic mode")]
90 ApicIdLimitExceeded(u32),
91 /// VpInfo indices must be linear and start at 0
92 #[error("vp indices don't start at 0 or don't count up")]
93 InvalidVpIndices,
94 /// Failed to query the topology information from Device Tree.
95 #[error("failed to query memory topology from device tree")]
96 StdIoError(#[source] std::io::Error),
97}
98
99impl<T: ArchTopology> TopologyBuilder<T> {
100 /// Sets the number of VPs per socket.
101 ///
102 /// This does not need to be a power of 2, but it should be a multiple of 2
103 /// if SMT is enabled.
104 ///
105 /// The number of VPs per socket will be rounded up to a power of 2 for
106 /// purposes of defining the x2APIC ID.
107 pub fn vps_per_socket(&mut self, count: u32) -> &mut Self {
108 self.vps_per_socket = count.clamp(1, 32768);
109 self
110 }
111
112 /// Sets whether SMT (hyperthreading) is enabled.
113 ///
114 /// This is ignored if `vps_per_socket` is 1.
115 pub fn smt_enabled(&mut self, enabled: bool) -> &mut Self {
116 self.smt_enabled = enabled;
117 self
118 }
119}
120
121impl<
122 #[cfg(feature = "inspect")] T: ArchTopology + inspect::Inspect,
123 #[cfg(not(feature = "inspect"))] T: ArchTopology,
124> ProcessorTopology<T>
125{
126 /// Returns the number of VPs.
127 pub fn vp_count(&self) -> u32 {
128 self.vps.len() as u32
129 }
130
131 /// Returns information for the given processor by VP index.
132 ///
133 /// Panics if the VP index is out of range.
134 pub fn vp(&self, vp_index: VpIndex) -> VpInfo {
135 *self.vps[vp_index.index() as usize].as_ref()
136 }
137
138 /// Returns information for the given processor by VP index, including
139 /// architecture-specific information.
140 ///
141 /// Panics if the VP index is out of range.
142 pub fn vp_arch(&self, vp_index: VpIndex) -> T::ArchVpInfo {
143 self.vps[vp_index.index() as usize]
144 }
145
146 /// Returns an iterator over all VPs.
147 pub fn vps(&self) -> impl '_ + ExactSizeIterator<Item = VpInfo> + Clone {
148 self.vps.iter().map(|vp| *vp.as_ref())
149 }
150
151 /// Returns an iterator over all VPs, including architecture-specific information.
152 pub fn vps_arch(&self) -> impl '_ + ExactSizeIterator<Item = T::ArchVpInfo> + Clone {
153 self.vps.iter().copied()
154 }
155
156 /// Returns whether SMT (hyperthreading) is enabled.
157 pub fn smt_enabled(&self) -> bool {
158 self.smt_enabled
159 }
160
161 /// Returns the number of VPs per socket.
162 ///
163 /// This will always be a power of 2. The number of VPs actually populated
164 /// in a socket may be smaller than this.
165 pub fn reserved_vps_per_socket(&self) -> u32 {
166 self.vps_per_socket.next_power_of_two()
167 }
168
169 /// Computes the processor topology information for a VP.
170 pub fn vp_topology(&self, vp_index: VpIndex) -> VpTopologyInfo {
171 T::vp_topology(self, &self.vp_arch(vp_index))
172 }
173}
174
175/// Per-processor topology information.
176#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
177#[derive(Debug, Copy, Clone)]
178pub struct VpInfo {
179 /// The VP index of the processor.
180 pub vp_index: VpIndex,
181 /// The virtual NUMA node of the processor.
182 pub vnode: u32,
183}
184
185impl AsRef<VpInfo> for VpInfo {
186 fn as_ref(&self) -> &VpInfo {
187 self
188 }
189}
190
191impl VpInfo {
192 /// Returns true if this is the BSP.
193 pub fn is_bsp(&self) -> bool {
194 self.vp_index.is_bsp()
195 }
196}
197
198/// Topology information about a virtual processor.
199pub struct VpTopologyInfo {
200 /// The socket index.
201 pub socket: u32,
202 /// The core index within the socket.
203 pub core: u32,
204 /// The thread index within the core.
205 pub thread: u32,
206}
207
208/// The virtual processor index.
209///
210/// This value is used inside the VMM to identify the processor. It is expected
211/// to be used as an index into processor arrays, so it starts at zero and has
212/// no gaps.
213///
214/// VP index zero is special in that it is always present and is always the BSP.
215///
216/// The same value is exposed to the guest operating system as the HV VP index,
217/// via the Microsoft hypervisor guest interface. This constrains the HV VP
218/// index to start at zero and have no gaps, which is not required by the
219/// hypervisor interface, but it matches the behavior of Hyper-V and is not a
220/// practical limitation.
221///
222/// This value is distinct from the APIC ID, although they are often the same
223/// for all processors in small VMs and some in large VMs. Be careful not to use
224/// them interchangeably.
225#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
226#[cfg_attr(feature = "inspect", derive(inspect::Inspect), inspect(transparent))]
227pub struct VpIndex(u32);
228
229impl VpIndex {
230 /// Returns `index` as a VP index.
231 pub const fn new(index: u32) -> Self {
232 Self(index)
233 }
234
235 /// VP index zero, corresponding to the boot processor (BSP).
236 ///
237 /// Note that this being a constant means that the BSP's HV VP index
238 /// observed by the guest will always be zero. This is consistent with
239 /// Hyper-V and is not a practical limitation.
240 ///
241 /// Note that the APIC ID of the BSP might not be zero.
242 pub const BSP: Self = Self::new(0);
243
244 /// Returns the VP index value.
245 pub fn index(&self) -> u32 {
246 self.0
247 }
248
249 /// Returns true if this is the index of the BSP (0).
250 pub fn is_bsp(&self) -> bool {
251 *self == Self::BSP
252 }
253}