x86_vcpu 0.6.2

x86 Virtual CPU implementation for the Arceos Hypervisor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Copyright 2026 The Axvisor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use core::{
    fmt::{Debug, Formatter, LowerHex, UpperHex},
    ops::{Add, AddAssign},
};

use bitflags::bitflags;

use crate::decode::X86ByteRegister;

/// Size of a 4 KiB page.
pub const X86_PAGE_SIZE_4K: usize = 0x1000;

/// Result type returned by the OS-neutral x86 vCPU core.
pub type X86VcpuResult<T = ()> = Result<T, X86VcpuError>;

/// Errors produced by the OS-neutral x86 vCPU core.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum X86VcpuError {
    /// A caller supplied an invalid argument or unsupported hardware encoding.
    InvalidInput,
    /// Hardware register or exit data could not be decoded as a valid value.
    InvalidData,
    /// The requested operation is not supported by this CPU or vCPU backend.
    Unsupported,
    /// Hardware or software state is inconsistent with the requested transition.
    BadState,
    /// A host allocation failed.
    NoMemory,
    /// The requested hardware resource is already in use.
    ResourceBusy,
    /// The host timer service required by an emulated device is unavailable.
    TimerUnavailable,
}

impl From<x86_vlapic::X86VlapicError> for X86VcpuError {
    fn from(err: x86_vlapic::X86VlapicError) -> Self {
        match err {
            x86_vlapic::X86VlapicError::InvalidInput => Self::InvalidInput,
            x86_vlapic::X86VlapicError::InvalidData => Self::InvalidData,
            x86_vlapic::X86VlapicError::Unsupported => Self::Unsupported,
            x86_vlapic::X86VlapicError::NoMemory => Self::NoMemory,
            x86_vlapic::X86VlapicError::BadState => Self::BadState,
            x86_vlapic::X86VlapicError::TimerUnavailable => Self::TimerUnavailable,
        }
    }
}

macro_rules! define_addr_type {
    ($name:ident, $debug_prefix:literal) => {
        #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
        pub struct $name(usize);

        impl $name {
            /// Creates an address from a raw `usize`.
            pub const fn from_usize(addr: usize) -> Self {
                Self(addr)
            }

            /// Returns the raw address value.
            pub const fn as_usize(self) -> usize {
                self.0
            }

            /// Returns this address as an immutable pointer.
            pub const fn as_ptr<T>(self) -> *const T {
                self.0 as *const T
            }

            /// Returns this address as a mutable pointer.
            pub const fn as_mut_ptr<T>(self) -> *mut T {
                self.0 as *mut T
            }
        }

        impl From<usize> for $name {
            fn from(value: usize) -> Self {
                Self::from_usize(value)
            }
        }

        impl From<$name> for usize {
            fn from(value: $name) -> Self {
                value.as_usize()
            }
        }

        impl Add<usize> for $name {
            type Output = Self;

            fn add(self, rhs: usize) -> Self::Output {
                Self(self.0 + rhs)
            }
        }

        impl AddAssign<usize> for $name {
            fn add_assign(&mut self, rhs: usize) {
                self.0 += rhs;
            }
        }

        impl Debug for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}({:#x})", $debug_prefix, self.0)
            }
        }

        impl LowerHex for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                write!(f, "{:#x}", self.0)
            }
        }

        impl UpperHex for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                write!(f, "{:#X}", self.0)
            }
        }
    };
}

define_addr_type!(X86GuestPhysAddr, "GPA");
define_addr_type!(X86GuestVirtAddr, "GVA");
define_addr_type!(X86HostPhysAddr, "HPA");
define_addr_type!(X86HostVirtAddr, "HVA");

/// The port number of an x86 I/O operation.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct X86Port(u16);

impl X86Port {
    /// Creates a new x86 I/O port.
    pub const fn new(port: u16) -> Self {
        Self(port)
    }

    /// Returns the raw port number.
    pub const fn number(self) -> u16 {
        self.0
    }
}

impl From<u16> for X86Port {
    fn from(value: u16) -> Self {
        Self::new(value)
    }
}

impl Debug for X86Port {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "X86Port({:#x})", self.0)
    }
}

/// x86 MSR address.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct X86MsrAddr(usize);

impl X86MsrAddr {
    /// Creates an MSR address from the raw MSR number.
    pub const fn new(addr: usize) -> Self {
        Self(addr)
    }

    /// Returns the raw MSR number.
    pub const fn addr(self) -> usize {
        self.0
    }
}

impl From<usize> for X86MsrAddr {
    fn from(value: usize) -> Self {
        Self::new(value)
    }
}

impl Debug for X86MsrAddr {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "MSR({:#x})", self.0)
    }
}

/// Width of a trapped guest bus access.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum X86AccessWidth {
    /// 8-bit access.
    Byte,
    /// 16-bit access.
    Word,
    /// 32-bit access.
    Dword,
    /// 64-bit access.
    Qword,
}

impl X86AccessWidth {
    /// Returns this access width in bytes.
    pub const fn size(self) -> usize {
        match self {
            Self::Byte => 1,
            Self::Word => 2,
            Self::Dword => 4,
            Self::Qword => 8,
        }
    }

    /// Returns the bit range covered by this access.
    pub fn bits_range(self) -> core::ops::Range<usize> {
        match self {
            Self::Byte => 0..8,
            Self::Word => 0..16,
            Self::Dword => 0..32,
            Self::Qword => 0..64,
        }
    }

    /// Returns the memory-operand width encoded by a MOV opcode plus its
    /// operand-size and REX prefixes.
    pub(crate) fn for_mov_opcode(
        opcode: u8,
        operand_size_override: bool,
        rex_w: bool,
    ) -> Option<Self> {
        match opcode {
            0x88 | 0x8a | 0xc6 => Some(Self::Byte),
            0x89 | 0x8b | 0xc7 => {
                if rex_w {
                    Some(Self::Qword)
                } else if operand_size_override {
                    Some(Self::Word)
                } else {
                    Some(Self::Dword)
                }
            }
            _ => None,
        }
    }

    /// Masks a value down to this width.
    pub(crate) fn mask_value(self, value: u64) -> u64 {
        match self {
            Self::Byte => value & 0xff,
            Self::Word => value & 0xffff,
            Self::Dword => value & 0xffff_ffff,
            Self::Qword => value,
        }
    }
}

impl TryFrom<usize> for X86AccessWidth {
    type Error = X86VcpuError;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(Self::Byte),
            2 => Ok(Self::Word),
            4 => Ok(Self::Dword),
            8 => Ok(Self::Qword),
            _ => Err(X86VcpuError::InvalidInput),
        }
    }
}

impl From<X86AccessWidth> for usize {
    fn from(value: X86AccessWidth) -> Self {
        value.size()
    }
}

bitflags! {
    /// Access flags reported for a nested page fault.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct X86AccessFlags: usize {
        /// Read access.
        const READ = 1 << 0;
        /// Write access.
        const WRITE = 1 << 1;
        /// Execute access.
        const EXECUTE = 1 << 2;
    }
}

/// Information about a nested guest page-table fault.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct X86NestedPageFaultInfo {
    /// Faulting guest physical address.
    pub fault_guest_paddr: X86GuestPhysAddr,
    /// Fault access flags.
    pub access_flags: X86AccessFlags,
}

/// Nested page table configuration selected by the embedding VMM.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct X86NestedPagingConfig {
    /// Root physical address of the nested page table.
    pub root_paddr: X86HostPhysAddr,
    /// Number of nested page-table levels.
    pub levels: usize,
    /// Guest physical address width in bits.
    pub gpa_bits: usize,
    /// Hardware-specific mode value.
    pub mode: usize,
}

impl X86NestedPagingConfig {
    /// Creates a nested paging configuration.
    pub const fn new(
        root_paddr: X86HostPhysAddr,
        levels: usize,
        gpa_bits: usize,
        mode: usize,
    ) -> Self {
        Self {
            root_paddr,
            levels,
            gpa_bits,
            mode,
        }
    }
}

/// VM-exit reason returned by the x86 vCPU core.
#[derive(Debug)]
#[non_exhaustive]
pub enum X86VmExit {
    /// A guest instruction triggered a hypercall.
    Hypercall {
        /// Hypercall number.
        nr: u64,
        /// Hypercall arguments.
        args: [u64; 6],
    },
    /// The guest performed a port I/O read.
    PortIoRead {
        /// I/O port.
        port: X86Port,
        /// Access width.
        width: X86AccessWidth,
    },
    /// The guest performed a port I/O write.
    PortIoWrite {
        /// I/O port.
        port: X86Port,
        /// Access width.
        width: X86AccessWidth,
        /// Value written by the guest.
        data: u64,
    },
    /// The guest performed one element of a string port-I/O instruction.
    PortIoString(crate::X86PortIoStringExit),
    /// The guest performed an MMIO read.
    MmioRead {
        /// Guest physical address.
        addr: X86GuestPhysAddr,
        /// Access width.
        width: X86AccessWidth,
        /// Destination guest register.
        reg: usize,
        /// Destination register width.
        reg_width: X86AccessWidth,
        /// Whether the value should be sign-extended.
        signed_ext: bool,
        /// Byte-register destination for byte-width MOV reads.
        byte_reg: Option<X86ByteRegister>,
    },
    /// The guest performed an MMIO write.
    MmioWrite {
        /// Guest physical address.
        addr: X86GuestPhysAddr,
        /// Access width.
        width: X86AccessWidth,
        /// Value written by the guest.
        data: u64,
    },
    /// The guest performed an MSR read.
    MsrRead {
        /// MSR address.
        addr: X86MsrAddr,
    },
    /// The guest performed an MSR write.
    MsrWrite {
        /// MSR address.
        addr: X86MsrAddr,
        /// Value written by the guest.
        value: u64,
    },
    /// A nested page fault occurred.
    NestedPageFault {
        /// Faulting guest physical address.
        addr: X86GuestPhysAddr,
        /// Access flags.
        access_flags: X86AccessFlags,
    },
    /// A physical host interrupt should be handled by the embedding VMM.
    ExternalInterrupt {
        /// Host vector reported by the backend.
        vector: u8,
    },
    /// The preemption timer expired or the backend wants the VMM to poll timers.
    PreemptionTimer,
    /// A guest EOI completed.
    InterruptEnd {
        /// Vector that may require IOAPIC EOI propagation.
        vector: Option<u8>,
    },
    /// The guest halted.
    Halt,
    /// The guest requested system power-off.
    SystemDown,
    /// VM entry failed in hardware.
    FailEntry {
        /// Hardware entry-failure reason.
        hardware_entry_failure_reason: usize,
    },
    /// The exit was handled inside the x86 core.
    Nothing,
}