Skip to main content

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_select! {
10    guest_arch = "aarch64" => {
11        pub use aarch64 as arch;
12        pub use aarch64::Aarch64Topology as TargetTopology;
13        pub use aarch64::Aarch64VpInfo as TargetVpInfo;
14    }
15    guest_arch = "x86_64" => {
16        pub use x86 as arch;
17        pub use x86::X86Topology as TargetTopology;
18        pub use x86::X86VpInfo as TargetVpInfo;
19    }
20}
21use thiserror::Error;
22
23/// A description of the VM's processor topology.
24///
25/// Currently this just tracks the APIC IDs for the processors.
26///
27/// Build one with [`TopologyBuilder`].
28#[cfg_attr(
29    feature = "inspect",
30    derive(inspect::Inspect),
31    inspect(bound = "T: inspect::Inspect, T::ArchVpInfo: inspect::Inspect")
32)]
33#[derive(Debug, Clone)]
34pub struct ProcessorTopology<T: ArchTopology = TargetTopology> {
35    #[cfg_attr(feature = "inspect", inspect(iter_by_index))]
36    vps: Vec<T::ArchVpInfo>,
37    smt_enabled: bool,
38    vps_per_socket: u32,
39    arch: T,
40}
41
42/// Architecture-specific topology types.
43pub trait ArchTopology: Sized {
44    /// The architecture-specific VP info type.
45    type ArchVpInfo: Copy + AsRef<VpInfo>;
46
47    /// The architecture-specific [`TopologyBuilder`] generic.
48    type BuilderState;
49
50    /// Compute VP topology from a VP.
51    fn vp_topology(topology: &ProcessorTopology<Self>, info: &Self::ArchVpInfo) -> VpTopologyInfo;
52}
53
54/// A builder for [`ProcessorTopology`].
55#[derive(Debug)]
56pub struct TopologyBuilder<T: ArchTopology> {
57    vps_per_socket: u32,
58    smt_enabled: bool,
59    arch: T::BuilderState,
60}
61
62/// Error returned by [`TopologyBuilder::from_host_topology`].
63#[derive(Debug, Error)]
64pub enum HostTopologyError {
65    /// Could not find the host topology.
66    #[error("could not compute host topology via cpuid")]
67    NotFound,
68    /// The host topology has more than 2 threads per core.
69    #[error("unsupported thread-per-core count {0}")]
70    UnsupportedThreadsPerCore(u32),
71}
72
73/// Error when building a [`ProcessorTopology`].
74#[derive(Debug, Error)]
75pub enum InvalidTopology {
76    /// Failed to configure at least one VP.
77    #[error("must have at least one processor")]
78    NoVps,
79    /// Too many virtual processors.
80    #[error("too many processors requested: {requested}, max {max}")]
81    TooManyVps {
82        /// The number of processors requested.
83        requested: u32,
84        /// The maximum number of processors.
85        max: u32,
86    },
87    /// Not all processors will be addressable in XAPIC mode.
88    #[error("too many processors or too high an APIC ID {0} for xapic mode")]
89    ApicIdLimitExceeded(u32),
90    /// VpInfo indices must be linear and start at 0
91    #[error("vp indices don't start at 0 or don't count up")]
92    InvalidVpIndices,
93    /// A PPI INTID is not in the valid range (16..32).
94    #[error("PPI INTID {0} is not in the valid range 16..32")]
95    InvalidPpiIntid(u32),
96    /// The GIC interrupt count is invalid.
97    #[error("gic_nr_irqs {0} must be 64..=992 and a multiple of 32")]
98    InvalidGicNrIrqs(u32),
99    /// GICv2 supports at most 8 CPUs.
100    #[error("GICv2 supports at most 8 CPUs, but {0} were requested")]
101    TooManyCpusForGicV2(u32),
102    /// Failed to query the topology information from Device Tree.
103    #[error("failed to query memory topology from device tree")]
104    StdIoError(#[source] std::io::Error),
105}
106
107impl<T: ArchTopology> TopologyBuilder<T> {
108    /// Sets the number of VPs per socket.
109    ///
110    /// This does not need to be a power of 2, but it should be a multiple of 2
111    /// if SMT is enabled.
112    ///
113    /// The number of VPs per socket will be rounded up to a power of 2 for
114    /// purposes of defining the x2APIC ID.
115    pub fn vps_per_socket(&mut self, count: u32) -> &mut Self {
116        self.vps_per_socket = count.clamp(1, 32768);
117        self
118    }
119
120    /// Sets whether SMT (hyperthreading) is enabled.
121    ///
122    /// This is ignored if `vps_per_socket` is 1.
123    pub fn smt_enabled(&mut self, enabled: bool) -> &mut Self {
124        self.smt_enabled = enabled;
125        self
126    }
127}
128
129impl<T: ArchTopology> ProcessorTopology<T> {
130    /// Computes the socket, core, and thread coordinates of a VP from the
131    /// configured topology.
132    ///
133    /// This describes the regular topology the VM was asked for. It is
134    /// deliberately independent of any architectural CPU identity, since those
135    /// identities are free to encode an offset, reserved holes, or a packing
136    /// that carries no topology at all.
137    ///
138    /// The result is only meaningful if `vps_per_socket` and `smt_enabled`
139    /// actually describe the VPs in this topology. That holds by construction
140    /// for [`TopologyBuilder::build`], which generates VPs from those same
141    /// values, but [`TopologyBuilder::build_with_vp_info`] takes the VP list
142    /// from its caller and keeps the declared values unchecked. A caller that
143    /// supplies VPs laid out some other way gets coordinates describing the
144    /// layout it declared, not the one it passed in.
145    ///
146    /// Irregular topologies cannot be represented at all: `vps_per_socket` is a
147    /// single value, so sockets of differing sizes, or siblings that are not
148    /// adjacent in VP index order, have nowhere to live. Supporting those would
149    /// require storing per-VP coordinates rather than deriving them here.
150    pub(crate) fn logical_topology(&self, vp_index: VpIndex) -> VpTopologyInfo {
151        let index = vp_index.index();
152        let in_socket = index % self.vps_per_socket;
153        let (core, thread) = if self.smt_enabled {
154            (in_socket / THREADS_PER_CORE, in_socket % THREADS_PER_CORE)
155        } else {
156            (in_socket, 0)
157        };
158        VpTopologyInfo {
159            socket: index / self.vps_per_socket,
160            core,
161            thread,
162        }
163    }
164}
165
166/// The number of threads per core when SMT is enabled.
167///
168/// The topology API models SMT as a boolean, so two is the only possibility.
169pub(crate) const THREADS_PER_CORE: u32 = 2;
170
171impl<
172    #[cfg(feature = "inspect")] T: ArchTopology + inspect::Inspect,
173    #[cfg(not(feature = "inspect"))] T: ArchTopology,
174> ProcessorTopology<T>
175{
176    /// Returns the number of VPs.
177    pub fn vp_count(&self) -> u32 {
178        self.vps.len() as u32
179    }
180
181    /// Returns information for the given processor by VP index.
182    ///
183    /// Panics if the VP index is out of range.
184    pub fn vp(&self, vp_index: VpIndex) -> VpInfo {
185        *self.vps[vp_index.index() as usize].as_ref()
186    }
187
188    /// Returns information for the given processor by VP index, including
189    /// architecture-specific information.
190    ///
191    /// Panics if the VP index is out of range.
192    pub fn vp_arch(&self, vp_index: VpIndex) -> T::ArchVpInfo {
193        self.vps[vp_index.index() as usize]
194    }
195
196    /// Returns an iterator over all VPs.
197    pub fn vps(&self) -> impl '_ + ExactSizeIterator<Item = VpInfo> + Clone {
198        self.vps.iter().map(|vp| *vp.as_ref())
199    }
200
201    /// Returns an iterator over all VPs, including architecture-specific information.
202    pub fn vps_arch(&self) -> impl '_ + ExactSizeIterator<Item = T::ArchVpInfo> + Clone {
203        self.vps.iter().copied()
204    }
205
206    /// Returns whether SMT (hyperthreading) is enabled.
207    pub fn smt_enabled(&self) -> bool {
208        self.smt_enabled
209    }
210
211    /// Returns the configured number of VPs per socket.
212    ///
213    /// This is the logical socket size before power-of-two rounding. Use
214    /// this for NUMA VP assignment and other logical topology queries.
215    pub fn vps_per_socket(&self) -> u32 {
216        self.vps_per_socket
217    }
218
219    /// Returns the number of VPs per socket, rounded up to a power of 2.
220    ///
221    /// This is the APIC-ID-space reservation per socket. The number of VPs
222    /// actually populated in a socket may be smaller than this.
223    pub fn reserved_vps_per_socket(&self) -> u32 {
224        self.vps_per_socket.next_power_of_two()
225    }
226
227    /// Computes the processor topology information for a VP.
228    ///
229    /// This reports the topology the VM was configured with, which is only as
230    /// accurate as that configuration. It is not recovered from the VP's
231    /// architectural identity, and callers should not treat it as a
232    /// measurement of the underlying hardware.
233    pub fn vp_topology(&self, vp_index: VpIndex) -> VpTopologyInfo {
234        T::vp_topology(self, &self.vp_arch(vp_index))
235    }
236
237    /// Sets the virtual NUMA node for each VP.
238    ///
239    /// `vnodes` must have exactly `vp_count()` entries, where `vnodes[i]` is
240    /// the vnode for VP index `i`.
241    ///
242    /// # Panics
243    ///
244    /// Panics if `vnodes.len() != vp_count()`.
245    pub fn set_vnodes(&mut self, vnodes: &[u32])
246    where
247        T::ArchVpInfo: AsMut<VpInfo>,
248    {
249        assert_eq!(vnodes.len(), self.vps.len());
250        for (vp, &vnode) in self.vps.iter_mut().zip(vnodes) {
251            vp.as_mut().vnode = vnode;
252        }
253    }
254}
255
256/// Per-processor topology information.
257#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
258#[derive(Debug, Copy, Clone)]
259pub struct VpInfo {
260    /// The VP index of the processor.
261    pub vp_index: VpIndex,
262    /// The virtual NUMA node of the processor.
263    pub vnode: u32,
264}
265
266impl AsRef<VpInfo> for VpInfo {
267    fn as_ref(&self) -> &VpInfo {
268        self
269    }
270}
271
272impl VpInfo {
273    /// Returns true if this is the BSP.
274    pub fn is_bsp(&self) -> bool {
275        self.vp_index.is_bsp()
276    }
277}
278
279/// Topology information about a virtual processor.
280pub struct VpTopologyInfo {
281    /// The socket index.
282    pub socket: u32,
283    /// The core index within the socket.
284    pub core: u32,
285    /// The thread index within the core.
286    pub thread: u32,
287}
288
289/// The virtual processor index.
290///
291/// This value is used inside the VMM to identify the processor. It is expected
292/// to be used as an index into processor arrays, so it starts at zero and has
293/// no gaps.
294///
295/// VP index zero is special in that it is always present and is always the BSP.
296///
297/// The same value is exposed to the guest operating system as the HV VP index,
298/// via the Microsoft hypervisor guest interface. This constrains the HV VP
299/// index to start at zero and have no gaps, which is not required by the
300/// hypervisor interface, but it matches the behavior of Hyper-V and is not a
301/// practical limitation.
302///
303/// This value is distinct from the APIC ID, although they are often the same
304/// for all processors in small VMs and some in large VMs. Be careful not to use
305/// them interchangeably.
306#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
307#[cfg_attr(feature = "inspect", derive(inspect::Inspect), inspect(transparent))]
308pub struct VpIndex(u32);
309
310impl VpIndex {
311    /// Returns `index` as a VP index.
312    pub const fn new(index: u32) -> Self {
313        Self(index)
314    }
315
316    /// VP index zero, corresponding to the boot processor (BSP).
317    ///
318    /// Note that this being a constant means that the BSP's HV VP index
319    /// observed by the guest will always be zero. This is consistent with
320    /// Hyper-V and is not a practical limitation.
321    ///
322    /// Note that the APIC ID of the BSP might not be zero.
323    pub const BSP: Self = Self::new(0);
324
325    /// Returns the VP index value.
326    pub fn index(&self) -> u32 {
327        self.0
328    }
329
330    /// Returns true if this is the index of the BSP (0).
331    pub fn is_bsp(&self) -> bool {
332        *self == Self::BSP
333    }
334}