1#[cfg(any(unix, feature = "haxm", feature = "whpx"))]
6use std::arch::x86_64::__cpuid;
7use std::arch::x86_64::_rdtsc;
8use std::arch::x86_64::CpuidResult;
9use std::collections::BTreeMap;
10use std::collections::HashSet;
11use std::sync::Arc;
12
13use anyhow::Context;
14use base::custom_serde::deserialize_seq_to_arr;
15use base::custom_serde::serialize_arr;
16use base::error;
17use base::warn;
18use base::Result;
19use bit_field::*;
20use libc::c_void;
21use serde::Deserialize;
22use serde::Serialize;
23use snapshot::AnySnapshot;
24use vm_memory::GuestAddress;
25
26use crate::Hypervisor;
27use crate::IrqRoute;
28use crate::IrqSource;
29use crate::IrqSourceChip;
30use crate::NestedMode;
31use crate::Vcpu;
32use crate::Vm;
33
34const MSR_F15H_PERF_CTL0: u32 = 0xc0010200;
35const MSR_F15H_PERF_CTL1: u32 = 0xc0010202;
36const MSR_F15H_PERF_CTL2: u32 = 0xc0010204;
37const MSR_F15H_PERF_CTL3: u32 = 0xc0010206;
38const MSR_F15H_PERF_CTL4: u32 = 0xc0010208;
39const MSR_F15H_PERF_CTL5: u32 = 0xc001020a;
40const MSR_F15H_PERF_CTR0: u32 = 0xc0010201;
41const MSR_F15H_PERF_CTR1: u32 = 0xc0010203;
42const MSR_F15H_PERF_CTR2: u32 = 0xc0010205;
43const MSR_F15H_PERF_CTR3: u32 = 0xc0010207;
44const MSR_F15H_PERF_CTR4: u32 = 0xc0010209;
45const MSR_F15H_PERF_CTR5: u32 = 0xc001020b;
46const MSR_IA32_PERF_CAPABILITIES: u32 = 0x00000345;
47
48pub trait HypervisorX86_64: Hypervisor {
50 fn get_supported_cpuid(&self) -> Result<CpuId>;
52
53 fn get_msr_index_list(&self) -> Result<Vec<u32>>;
55}
56
57pub trait VmX86_64: Vm {
59 fn set_boot_cpu_id(&self, _vcpu_id: usize) -> Result<()> {
64 Err(base::Error::new(libc::ENOTSUP))
65 }
66
67 fn get_hypervisor(&self) -> &dyn HypervisorX86_64;
69
70 fn create_vcpu(&self, id: usize) -> Result<Arc<dyn VcpuX86_64>>;
72
73 fn set_tss_addr(&self, addr: GuestAddress) -> Result<()>;
75
76 fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()>;
78
79 fn load_protected_vm_firmware(&self, fw_addr: GuestAddress, fw_max_size: u64) -> Result<()>;
83}
84
85pub trait VcpuX86_64: Vcpu {
87 fn set_interrupt_window_requested(&self, requested: bool);
90
91 fn ready_for_interrupt(&self) -> bool;
93
94 fn interrupt(&self, irq: u8) -> Result<()>;
106
107 fn inject_nmi(&self) -> Result<()>;
109
110 fn get_regs(&self) -> Result<Regs>;
112
113 fn set_regs(&self, regs: &Regs) -> Result<()>;
115
116 fn get_sregs(&self) -> Result<Sregs>;
118
119 fn set_sregs(&self, sregs: &Sregs) -> Result<()>;
121
122 fn get_fpu(&self) -> Result<Fpu>;
124
125 fn set_fpu(&self, fpu: &Fpu) -> Result<()>;
127
128 fn get_debugregs(&self) -> Result<DebugRegs>;
130
131 fn set_debugregs(&self, debugregs: &DebugRegs) -> Result<()>;
133
134 fn get_xcrs(&self) -> Result<BTreeMap<u32, u64>>;
136
137 fn set_xcr(&self, xcr: u32, value: u64) -> Result<()>;
139
140 fn get_xsave(&self) -> Result<Xsave>;
142
143 fn set_xsave(&self, xsave: &Xsave) -> Result<()>;
145
146 fn get_hypervisor_specific_state(&self) -> Result<AnySnapshot>;
150
151 fn set_hypervisor_specific_state(&self, data: AnySnapshot) -> Result<()>;
154
155 fn get_msr(&self, msr_index: u32) -> Result<u64>;
157
158 fn get_all_msrs(&self) -> Result<BTreeMap<u32, u64>>;
160
161 fn set_msr(&self, msr_index: u32, value: u64) -> Result<()>;
163
164 fn set_cpuid(&self, cpuid: &CpuId) -> Result<()>;
166
167 fn set_guest_debug(&self, addrs: &[GuestAddress], enable_singlestep: bool) -> Result<()>;
169
170 fn handle_cpuid(&self, entry: &CpuIdEntry) -> Result<()>;
174
175 fn get_tsc_offset(&self) -> Result<u64> {
179 let host_before_tsc = unsafe { _rdtsc() };
182
183 let guest_tsc = self.get_msr(crate::MSR_IA32_TSC)?;
185
186 let host_after_tsc = unsafe { _rdtsc() };
189
190 let host_tsc = ((host_before_tsc as u128 + host_after_tsc as u128) / 2) as u64;
192
193 Ok(guest_tsc.wrapping_sub(host_tsc))
194 }
195
196 fn set_tsc_offset(&self, offset: u64) -> Result<()> {
217 let host_tsc = unsafe { _rdtsc() };
219 self.set_tsc_value(host_tsc.wrapping_add(offset))
220 }
221
222 fn set_tsc_value(&self, value: u64) -> Result<()> {
229 self.set_msr(crate::MSR_IA32_TSC, value)
230 }
231
232 fn restore_timekeeping(&self, host_tsc_reference_moment: u64, tsc_offset: u64) -> Result<()>;
237
238 fn snapshot(&self) -> anyhow::Result<VcpuSnapshot> {
240 Ok(VcpuSnapshot {
241 vcpu_id: self.id(),
242 regs: self.get_regs()?,
243 sregs: self.get_sregs()?,
244 debug_regs: self.get_debugregs()?,
245 xcrs: self.get_xcrs()?,
246 msrs: self.get_all_msrs()?,
247 xsave: self.get_xsave()?,
248 hypervisor_data: self.get_hypervisor_specific_state()?,
249 tsc_offset: self.get_tsc_offset()?,
250 })
251 }
252
253 fn restore(
254 &self,
255 snapshot: &VcpuSnapshot,
256 host_tsc_reference_moment: u64,
257 ) -> anyhow::Result<()> {
258 let msr_allowlist = HashSet::from([
263 MSR_F15H_PERF_CTL0,
264 MSR_F15H_PERF_CTL1,
265 MSR_F15H_PERF_CTL2,
266 MSR_F15H_PERF_CTL3,
267 MSR_F15H_PERF_CTL4,
268 MSR_F15H_PERF_CTL5,
269 MSR_F15H_PERF_CTR0,
270 MSR_F15H_PERF_CTR1,
271 MSR_F15H_PERF_CTR2,
272 MSR_F15H_PERF_CTR3,
273 MSR_F15H_PERF_CTR4,
274 MSR_F15H_PERF_CTR5,
275 MSR_IA32_PERF_CAPABILITIES,
276 ]);
277 assert_eq!(snapshot.vcpu_id, self.id());
278 self.set_regs(&snapshot.regs)?;
279 self.set_sregs(&snapshot.sregs)?;
280 self.set_debugregs(&snapshot.debug_regs)?;
281 for (xcr_index, value) in &snapshot.xcrs {
282 self.set_xcr(*xcr_index, *value)?;
283 }
284
285 for (msr_index, value) in snapshot.msrs.iter() {
286 if self.get_msr(*msr_index) == Ok(*value) {
287 continue; }
289 if let Err(e) = self.set_msr(*msr_index, *value) {
290 if msr_allowlist.contains(msr_index) {
291 warn!(
292 "Failed to set MSR. MSR might not be supported in this kernel. Err: {}",
293 e
294 );
295 } else {
296 return Err(e).context(
297 "Failed to set MSR. MSR might not be supported by the CPU or by the kernel,
298 and was not allow-listed.",
299 );
300 }
301 };
302 }
303 self.set_xsave(&snapshot.xsave)?;
304 self.set_hypervisor_specific_state(snapshot.hypervisor_data.clone())?;
305 self.restore_timekeeping(host_tsc_reference_moment, snapshot.tsc_offset)?;
306 Ok(())
307 }
308}
309
310#[derive(Clone, Debug, Serialize, Deserialize)]
312pub struct VcpuSnapshot {
313 pub vcpu_id: usize,
314 regs: Regs,
315 sregs: Sregs,
316 debug_regs: DebugRegs,
317 xcrs: BTreeMap<u32, u64>,
318 msrs: BTreeMap<u32, u64>,
319 xsave: Xsave,
320 hypervisor_data: AnySnapshot,
321 tsc_offset: u64,
322}
323
324pub const MSR_IA32_TSC: u32 = 0x00000010;
326
327#[cfg(any(unix, feature = "haxm", feature = "whpx"))]
329pub(crate) fn host_phys_addr_bits() -> u8 {
330 let highest_ext_function = unsafe { __cpuid(0x80000000) };
332 if highest_ext_function.eax >= 0x80000008 {
333 let addr_size = unsafe { __cpuid(0x80000008) };
335 addr_size.eax as u8
337 } else {
338 36
339 }
340}
341
342#[derive(Clone, Default)]
344pub struct VcpuInitX86_64 {
345 pub regs: Regs,
347
348 pub sregs: Sregs,
350
351 pub fpu: Fpu,
353
354 pub msrs: BTreeMap<u32, u64>,
356}
357
358#[derive(Clone, Debug, PartialEq, Eq)]
360pub struct CpuConfigX86_64 {
361 pub force_calibrated_tsc_leaf: bool,
363
364 pub host_cpu_topology: bool,
366
367 pub enable_hwp: bool,
369
370 pub no_smt: bool,
372
373 pub itmt: bool,
375
376 pub hybrid_type: Option<CpuHybridType>,
378
379 pub nested: NestedMode,
381}
382
383impl CpuConfigX86_64 {
384 pub fn new(
385 force_calibrated_tsc_leaf: bool,
386 host_cpu_topology: bool,
387 enable_hwp: bool,
388 no_smt: bool,
389 itmt: bool,
390 hybrid_type: Option<CpuHybridType>,
391 nested: NestedMode,
392 ) -> Self {
393 CpuConfigX86_64 {
394 force_calibrated_tsc_leaf,
395 host_cpu_topology,
396 enable_hwp,
397 no_smt,
398 itmt,
399 hybrid_type,
400 nested,
401 }
402 }
403}
404
405#[repr(C)]
411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412pub struct CpuIdEntry {
413 pub function: u32,
414 pub index: u32,
415 pub flags: u32,
418 pub cpuid: CpuidResult,
419}
420
421pub struct CpuId {
423 pub cpu_id_entries: Vec<CpuIdEntry>,
424}
425
426impl CpuId {
427 pub fn new(initial_capacity: usize) -> Self {
429 CpuId {
430 cpu_id_entries: Vec::with_capacity(initial_capacity),
431 }
432 }
433}
434
435#[bitfield]
436#[derive(Clone, Copy, Debug, PartialEq, Eq)]
437pub enum DestinationMode {
438 Physical = 0,
439 Logical = 1,
440}
441
442#[bitfield]
443#[derive(Clone, Copy, Debug, PartialEq, Eq)]
444pub enum TriggerMode {
445 Edge = 0,
446 Level = 1,
447}
448
449#[bitfield]
450#[derive(Debug, Clone, Copy, PartialEq, Eq)]
451pub enum DeliveryMode {
452 Fixed = 0b000,
453 Lowest = 0b001,
454 SMI = 0b010, RemoteRead = 0b011, NMI = 0b100, Init = 0b101,
458 Startup = 0b110,
459 External = 0b111,
460}
461
462#[bitfield]
467#[derive(Clone, Copy, PartialEq, Eq)]
468pub struct MsiAddressMessage {
469 pub reserved: BitField2,
470 #[bits = 1]
471 pub destination_mode: DestinationMode,
472 pub redirection_hint: BitField1,
473 pub reserved_2: BitField8,
474 pub destination_id: BitField8,
475 pub always_0xfee: BitField12,
477}
478
479#[bitfield]
480#[derive(Clone, Copy, PartialEq, Eq)]
481pub struct MsiDataMessage {
482 pub vector: BitField8,
483 #[bits = 3]
484 pub delivery_mode: DeliveryMode,
485 pub reserved: BitField3,
486 #[bits = 1]
487 pub level: Level,
488 #[bits = 1]
489 pub trigger: TriggerMode,
490 pub reserved2: BitField16,
491}
492
493#[bitfield]
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub enum DeliveryStatus {
496 Idle = 0,
497 Pending = 1,
498}
499
500#[bitfield]
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum Level {
504 Deassert = 0,
505 Assert = 1,
506}
507
508#[bitfield]
510#[derive(Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
511pub struct IoapicRedirectionTableEntry {
512 vector: BitField8,
513 #[bits = 3]
514 delivery_mode: DeliveryMode,
515 #[bits = 1]
516 dest_mode: DestinationMode,
517 #[bits = 1]
518 delivery_status: DeliveryStatus,
519 polarity: BitField1,
520 remote_irr: bool,
521 #[bits = 1]
522 trigger_mode: TriggerMode,
523 interrupt_mask: bool, reserved: BitField39,
525 dest_id: BitField8,
526}
527
528pub const NUM_IOAPIC_PINS: usize = 24;
530
531#[repr(C)]
533#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
534pub struct IoapicState {
535 pub base_address: u64,
537 pub ioregsel: u8,
539 pub ioapicid: u32,
541 pub current_interrupt_level_bitmap: u32,
543 #[serde(
545 serialize_with = "serialize_arr",
546 deserialize_with = "deserialize_seq_to_arr"
547 )]
548 pub redirect_table: [IoapicRedirectionTableEntry; NUM_IOAPIC_PINS],
549}
550
551impl Default for IoapicState {
552 fn default() -> IoapicState {
553 unsafe { std::mem::zeroed() }
555 }
556}
557
558#[repr(C)]
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum PicSelect {
561 Primary = 0,
562 Secondary = 1,
563}
564
565#[repr(C)]
566#[derive(enumn::N, Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
567pub enum PicInitState {
568 #[default]
569 Icw1 = 0,
570 Icw2 = 1,
571 Icw3 = 2,
572 Icw4 = 3,
573}
574
575impl From<u8> for PicInitState {
577 fn from(item: u8) -> Self {
578 PicInitState::n(item).unwrap_or_else(|| {
579 error!("Invalid PicInitState {}, setting to 0", item);
580 PicInitState::Icw1
581 })
582 }
583}
584
585#[repr(C)]
587#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
588pub struct PicState {
589 pub last_irr: u8,
591 pub irr: u8,
593 pub imr: u8,
595 pub isr: u8,
597 pub priority_add: u8,
599 pub irq_base: u8,
600 pub read_reg_select: bool,
601 pub poll: bool,
602 pub special_mask: bool,
603 pub init_state: PicInitState,
604 pub auto_eoi: bool,
605 pub rotate_on_auto_eoi: bool,
606 pub special_fully_nested_mode: bool,
607 pub use_4_byte_icw: bool,
610 pub elcr: u8,
614 pub elcr_mask: u8,
615}
616
617#[repr(C)]
621#[derive(Clone, Copy, Serialize, Deserialize)]
622pub struct LapicState {
623 #[serde(
624 serialize_with = "serialize_arr",
625 deserialize_with = "deserialize_seq_to_arr"
626 )]
627 pub regs: [LapicRegister; 64],
628}
629
630pub type LapicRegister = u32;
631
632impl std::fmt::Debug for LapicState {
634 fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
635 self.regs[..].fmt(formatter)
636 }
637}
638
639impl PartialEq for LapicState {
641 fn eq(&self, other: &LapicState) -> bool {
642 self.regs[..] == other.regs[..]
643 }
644}
645
646impl Eq for LapicState {}
648
649pub const APIC_ID_REG: usize = 2;
651pub const APIC_IRR_START_REG: usize = 32;
653
654impl LapicState {
655 pub fn get_apic_id(&self) -> u32 {
657 (self.regs[APIC_ID_REG] >> 24) & 0xFF
658 }
659
660 pub fn get_pending_irr_vectors(&self) -> Vec<u8> {
662 let mut vectors = Vec::new();
663 for (i, ®) in self.regs[APIC_IRR_START_REG..=APIC_IRR_START_REG + 7]
664 .iter()
665 .enumerate()
666 {
667 if reg != 0 {
668 for bit in 0..32 {
669 if (reg & (1 << bit)) != 0 {
670 vectors.push((i * 32 + bit) as u8);
671 }
672 }
673 }
674 }
675 vectors
676 }
677}
678
679#[repr(C)]
682#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
683pub struct PitState {
684 pub channels: [PitChannelState; 3],
685 pub flags: u32,
687}
688
689#[repr(C)]
694#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
695pub enum PitRWMode {
696 None = 0,
698 Least = 1,
700 Most = 2,
702 Both = 3,
705}
706
707impl From<u8> for PitRWMode {
709 fn from(item: u8) -> Self {
710 PitRWMode::n(item).unwrap_or_else(|| {
711 error!("Invalid PitRWMode value {}, setting to 0", item);
712 PitRWMode::None
713 })
714 }
715}
716
717#[repr(C)]
721#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
722pub enum PitRWState {
723 None = 0,
725 LSB = 1,
727 MSB = 2,
729 Word0 = 3,
732 Word1 = 4,
736}
737
738impl From<u8> for PitRWState {
740 fn from(item: u8) -> Self {
741 PitRWState::n(item).unwrap_or_else(|| {
742 error!("Invalid PitRWState value {}, setting to 0", item);
743 PitRWState::None
744 })
745 }
746}
747
748#[repr(C)]
750#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
751pub struct PitChannelState {
752 pub count: u32,
754 pub latched_count: u16,
756 pub count_latched: PitRWState,
758 pub status_latched: bool,
760 pub status: u8,
764 pub read_state: PitRWState,
766 pub write_state: PitRWState,
768 pub reload_value: u16,
771 pub rw_mode: PitRWMode,
773 pub mode: u8,
775 pub bcd: bool,
777 pub gate: bool,
779 pub count_load_time: u64,
781}
782
783impl IrqRoute {
785 pub fn ioapic_irq_route(irq_num: u32) -> IrqRoute {
786 IrqRoute {
787 gsi: irq_num,
788 source: IrqSource::Irqchip {
789 chip: IrqSourceChip::Ioapic,
790 pin: irq_num,
791 },
792 }
793 }
794
795 pub fn pic_irq_route(id: IrqSourceChip, irq_num: u32) -> IrqRoute {
796 IrqRoute {
797 gsi: irq_num,
798 source: IrqSource::Irqchip {
799 chip: id,
800 pin: irq_num % 8,
801 },
802 }
803 }
804}
805
806#[repr(C)]
808#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
809pub struct Regs {
810 pub rax: u64,
811 pub rbx: u64,
812 pub rcx: u64,
813 pub rdx: u64,
814 pub rsi: u64,
815 pub rdi: u64,
816 pub rsp: u64,
817 pub rbp: u64,
818 pub r8: u64,
819 pub r9: u64,
820 pub r10: u64,
821 pub r11: u64,
822 pub r12: u64,
823 pub r13: u64,
824 pub r14: u64,
825 pub r15: u64,
826 pub rip: u64,
827 pub rflags: u64,
828}
829
830impl Default for Regs {
831 fn default() -> Self {
832 Regs {
833 rax: 0,
834 rbx: 0,
835 rcx: 0,
836 rdx: 0,
837 rsi: 0,
838 rdi: 0,
839 rsp: 0,
840 rbp: 0,
841 r8: 0,
842 r9: 0,
843 r10: 0,
844 r11: 0,
845 r12: 0,
846 r13: 0,
847 r14: 0,
848 r15: 0,
849 rip: 0xfff0, rflags: 0x2, }
852 }
853}
854
855#[repr(C)]
857#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
858pub struct Segment {
859 pub base: u64,
860 pub limit_bytes: u32,
862 pub selector: u16,
863 pub type_: u8,
864 pub present: u8,
865 pub dpl: u8,
866 pub db: u8,
867 pub s: u8,
868 pub l: u8,
869 pub g: u8,
870 pub avl: u8,
871}
872
873#[repr(C)]
875#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
876pub struct DescriptorTable {
877 pub base: u64,
878 pub limit: u16,
879}
880
881#[repr(C)]
883#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
884pub struct Sregs {
885 pub cs: Segment,
886 pub ds: Segment,
887 pub es: Segment,
888 pub fs: Segment,
889 pub gs: Segment,
890 pub ss: Segment,
891 pub tr: Segment,
892 pub ldt: Segment,
893 pub gdt: DescriptorTable,
894 pub idt: DescriptorTable,
895 pub cr0: u64,
896 pub cr2: u64,
897 pub cr3: u64,
898 pub cr4: u64,
899 pub cr8: u64,
900 pub efer: u64,
901}
902
903impl Default for Sregs {
904 fn default() -> Self {
905 const SEG_TYPE_DATA: u8 = 0b0000;
907 const SEG_TYPE_DATA_WRITABLE: u8 = 0b0010;
908
909 const SEG_TYPE_CODE: u8 = 0b1000;
910 const SEG_TYPE_CODE_READABLE: u8 = 0b0010;
911
912 const SEG_TYPE_ACCESSED: u8 = 0b0001;
913
914 const SEG_S_SYSTEM: u8 = 0; const SEG_S_CODE_OR_DATA: u8 = 1; let code_seg = Segment {
920 base: 0xffff0000,
921 limit_bytes: 0xffff,
922 selector: 0xf000,
923 type_: SEG_TYPE_CODE | SEG_TYPE_CODE_READABLE | SEG_TYPE_ACCESSED, present: 1,
925 s: SEG_S_CODE_OR_DATA,
926 ..Default::default()
927 };
928
929 let data_seg = Segment {
931 base: 0,
932 limit_bytes: 0xffff,
933 selector: 0,
934 type_: SEG_TYPE_DATA | SEG_TYPE_DATA_WRITABLE | SEG_TYPE_ACCESSED, present: 1,
936 s: SEG_S_CODE_OR_DATA,
937 ..Default::default()
938 };
939
940 let task_seg = Segment {
942 base: 0,
943 limit_bytes: 0xffff,
944 selector: 0,
945 type_: SEG_TYPE_CODE | SEG_TYPE_CODE_READABLE | SEG_TYPE_ACCESSED, present: 1,
947 s: SEG_S_SYSTEM,
948 ..Default::default()
949 };
950
951 let ldt = Segment {
953 base: 0,
954 limit_bytes: 0xffff,
955 selector: 0,
956 type_: SEG_TYPE_DATA | SEG_TYPE_DATA_WRITABLE, present: 1,
958 s: SEG_S_SYSTEM,
959 ..Default::default()
960 };
961
962 let gdt = DescriptorTable {
964 base: 0,
965 limit: 0xffff,
966 };
967
968 let idt = DescriptorTable {
970 base: 0,
971 limit: 0xffff,
972 };
973
974 let cr0 = (1 << 4) | (1 << 30); Sregs {
978 cs: code_seg,
979 ds: data_seg,
980 es: data_seg,
981 fs: data_seg,
982 gs: data_seg,
983 ss: data_seg,
984 tr: task_seg,
985 ldt,
986 gdt,
987 idt,
988 cr0,
989 cr2: 0,
990 cr3: 0,
991 cr4: 0,
992 cr8: 0,
993 efer: 0,
994 }
995 }
996}
997
998#[repr(C)]
1000#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
1001pub struct FpuReg {
1002 pub significand: u64,
1004
1005 pub sign_exp: u16,
1007}
1008
1009impl FpuReg {
1010 pub fn from_16byte_arrays(byte_arrays: &[[u8; 16]; 8]) -> [FpuReg; 8] {
1015 let mut regs = [FpuReg::default(); 8];
1016 for (dst, src) in regs.iter_mut().zip(byte_arrays.iter()) {
1017 let tbyte: [u8; 10] = src[0..10].try_into().unwrap();
1018 *dst = FpuReg::from(tbyte);
1019 }
1020 regs
1021 }
1022
1023 pub fn to_16byte_arrays(regs: &[FpuReg; 8]) -> [[u8; 16]; 8] {
1025 let mut byte_arrays = [[0u8; 16]; 8];
1026 for (dst, src) in byte_arrays.iter_mut().zip(regs.iter()) {
1027 *dst = (*src).into();
1028 }
1029 byte_arrays
1030 }
1031}
1032
1033impl From<[u8; 10]> for FpuReg {
1034 fn from(value: [u8; 10]) -> FpuReg {
1036 let significand_bytes = value[0..8].try_into().unwrap();
1039 let significand = u64::from_le_bytes(significand_bytes);
1040 let sign_exp_bytes = value[8..10].try_into().unwrap();
1041 let sign_exp = u16::from_le_bytes(sign_exp_bytes);
1042 FpuReg {
1043 significand,
1044 sign_exp,
1045 }
1046 }
1047}
1048
1049impl From<FpuReg> for [u8; 10] {
1050 fn from(value: FpuReg) -> [u8; 10] {
1052 let mut bytes = [0u8; 10];
1053 bytes[0..8].copy_from_slice(&value.significand.to_le_bytes());
1054 bytes[8..10].copy_from_slice(&value.sign_exp.to_le_bytes());
1055 bytes
1056 }
1057}
1058
1059impl From<FpuReg> for [u8; 16] {
1060 fn from(value: FpuReg) -> [u8; 16] {
1063 let mut bytes = [0u8; 16];
1064 bytes[0..8].copy_from_slice(&value.significand.to_le_bytes());
1065 bytes[8..10].copy_from_slice(&value.sign_exp.to_le_bytes());
1066 bytes
1067 }
1068}
1069
1070#[repr(C)]
1072#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
1073pub struct Fpu {
1074 pub fpr: [FpuReg; 8],
1075 pub fcw: u16,
1076 pub fsw: u16,
1077 pub ftwx: u8,
1078 pub last_opcode: u16,
1079 pub last_ip: u64,
1080 pub last_dp: u64,
1081 pub xmm: [[u8; 16usize]; 16usize],
1082 pub mxcsr: u32,
1083}
1084
1085impl Default for Fpu {
1086 fn default() -> Self {
1087 Fpu {
1088 fpr: Default::default(),
1089 fcw: 0x37f, fsw: 0,
1091 ftwx: 0,
1092 last_opcode: 0,
1093 last_ip: 0,
1094 last_dp: 0,
1095 xmm: Default::default(),
1096 mxcsr: 0x1f80, }
1098 }
1099}
1100
1101#[repr(C)]
1103#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
1104pub struct DebugRegs {
1105 pub db: [u64; 4usize],
1106 pub dr6: u64,
1107 pub dr7: u64,
1108}
1109
1110#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1112pub enum CpuHybridType {
1113 Atom,
1115 Core,
1117}
1118
1119#[derive(Clone, Debug, Serialize, Deserialize)]
1122pub struct Xsave {
1123 data: Vec<u32>,
1124
1125 len: usize,
1128}
1129
1130impl Xsave {
1131 pub fn new(len: usize) -> Self {
1136 Xsave {
1137 data: vec![0; len.div_ceil(4)],
1138 len,
1139 }
1140 }
1141
1142 pub fn as_ptr(&self) -> *const c_void {
1143 self.data.as_ptr() as *const c_void
1144 }
1145
1146 pub fn as_mut_ptr(&mut self) -> *mut c_void {
1147 self.data.as_mut_ptr() as *mut c_void
1148 }
1149
1150 pub fn len(&self) -> usize {
1152 self.len
1153 }
1154
1155 pub fn is_empty(&self) -> bool {
1157 self.len() == 0
1158 }
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163 use super::*;
1164
1165 #[test]
1166 fn test_lapic_get_apic_id() {
1167 let mut lapic = LapicState { regs: [0; 64] };
1168 assert_eq!(lapic.get_apic_id(), 0);
1169
1170 lapic.regs[APIC_ID_REG] = 0x05000000;
1172 assert_eq!(lapic.get_apic_id(), 5);
1173
1174 lapic.regs[APIC_ID_REG] = 0xFE000000;
1175 assert_eq!(lapic.get_apic_id(), 0xFE);
1176 }
1177
1178 #[test]
1179 fn test_lapic_get_pending_irr_vectors() {
1180 let mut lapic = LapicState { regs: [0; 64] };
1181 assert!(lapic.get_pending_irr_vectors().is_empty());
1182
1183 lapic.regs[APIC_IRR_START_REG + 7] |= 1 << 12;
1185 lapic.regs[APIC_IRR_START_REG + 1] |= 1 << 16;
1187
1188 let vectors = lapic.get_pending_irr_vectors();
1189 assert_eq!(vectors, vec![48, 236]);
1190 }
1191}