-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathvcpu.rs
More file actions
1690 lines (1481 loc) · 60.5 KB
/
Copy pathvcpu.rs
File metadata and controls
1690 lines (1481 loc) · 60.5 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 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 alloc::collections::VecDeque;
use bit_field::BitField;
use core::{
arch::naked_asm,
fmt::{Debug, Formatter, Result},
mem::size_of,
};
use raw_cpuid::CpuId;
use x86::{
bits64::vmx,
controlregs::{Xcr0, xcr0 as xcr0_read, xcr0_write},
dtables::{self, DescriptorTablePointer},
segmentation::SegmentSelector,
};
use x86_64::registers::control::{Cr0, Cr0Flags, Cr3, Cr4, Cr4Flags, EferFlags};
use x86_vlapic::EmulatedLocalApic;
use axaddrspace::{
GuestPhysAddr, GuestVirtAddr, HostPhysAddr, NestedPageFaultInfo,
device::{AccessWidth, Port, SysRegAddr, SysRegAddrRange},
};
use axdevice_base::BaseDeviceOps;
use axerrno::{AxResult, ax_err, ax_err_type};
use axvcpu::{AxArchVCpu, AxVCpuExitReason};
use axvisor_api::vmm::{VCpuId, VMId};
use super::VmxExitInfo;
use super::as_axerr;
use super::definitions::VmxExitReason;
use super::structs::{IOBitmap, MsrBitmap, VmxRegion};
use super::vmcs::{
self, ApicAccessExitType, VmcsControl32, VmcsControl64, VmcsControlNW, VmcsGuest16,
VmcsGuest32, VmcsGuest64, VmcsGuestNW, VmcsHost16, VmcsHost32, VmcsHost64, VmcsHostNW,
};
use crate::{ept::GuestPageWalkInfo, msr::Msr, regs::GeneralRegisters};
const VMX_PREEMPTION_TIMER_SET_VALUE: u32 = 1_000_000;
const QEMU_EXIT_PORT: u16 = 0x604;
const QEMU_EXIT_MAGIC: u64 = 0x2000;
pub struct XState {
host_xcr0: u64,
guest_xcr0: u64,
host_xss: u64,
guest_xss: u64,
xsave_available: bool,
xsaves_available: bool,
}
#[derive(PartialEq, Eq, Debug)]
pub enum VmCpuMode {
Real,
Protected,
Compatibility, // IA-32E mode (CS.L = 0)
Mode64, // IA-32E mode (CS.L = 1)
}
impl XState {
/// Create a new [`XState`] instance with current host state
fn new() -> Self {
// Check if XSAVE is available
let xsave_available = Self::xsave_available();
// Check if XSAVES and XRSTORS (as well as IA32_XSS) are available
let xsaves_available = if xsave_available {
Self::xsaves_available()
} else {
false
};
// Read XCR0 iff XSAVE is available
let xcr0 = if xsave_available {
unsafe { xcr0_read().bits() }
} else {
0
};
// Read IA32_XSS iff XSAVES is available
let xss = if xsaves_available {
Msr::IA32_XSS.read()
} else {
0
};
Self {
host_xcr0: xcr0,
guest_xcr0: xcr0,
host_xss: xss,
guest_xss: xss,
xsave_available,
xsaves_available,
}
}
/// Enable extended processor state management instructions, including XGETBV and XSAVE.
pub fn enable_xsave() {
if Self::xsave_available() {
unsafe { Cr4::write(Cr4::read() | Cr4Flags::OSXSAVE) };
}
}
/// Check if XSAVE is available on the current CPU.
pub fn xsave_available() -> bool {
let cpuid = CpuId::new();
cpuid
.get_feature_info()
.map(|f| f.has_xsave())
.unwrap_or(false)
}
/// Check if XSAVES and XRSTORS (as well as IA32_XSS) are available on the current CPU.
pub fn xsaves_available() -> bool {
let cpuid = CpuId::new();
cpuid
.get_extended_state_info()
.map(|f| f.has_xsaves_xrstors())
.unwrap_or(false)
}
/// Save the current host XCR0 and IA32_XSS values and load the guest values.
pub fn switch_to_guest(&mut self) {
unsafe {
if self.xsave_available {
self.host_xcr0 = xcr0_read().bits();
xcr0_write(Xcr0::from_bits_unchecked(self.guest_xcr0));
if self.xsaves_available {
self.host_xss = Msr::IA32_XSS.read();
Msr::IA32_XSS.write(self.guest_xss);
}
}
}
}
/// Save the current guest XCR0 and IA32_XSS values and load the host values.
pub fn switch_to_host(&mut self) {
unsafe {
if self.xsave_available {
self.guest_xcr0 = xcr0_read().bits();
xcr0_write(Xcr0::from_bits_unchecked(self.host_xcr0));
if self.xsaves_available {
self.guest_xss = Msr::IA32_XSS.read();
Msr::IA32_XSS.write(self.host_xss);
}
}
}
}
}
const MSR_IA32_EFER_LMA_BIT: u64 = 1 << 10;
const CR0_PE: usize = 1 << 0;
/// A virtual CPU within a guest.
#[repr(C)]
pub struct VmxVcpu {
// The order of `guest_regs` and `host_stack_top` is mandatory. They must be the first two fields. If you want to
// change the order or the type of these fields, you must also change the assembly in this file.
/// Guest general-purpose registers.
guest_regs: GeneralRegisters,
/// The top of the host stack.
host_stack_top: u64,
// The order of the following fields is not mandatory.
// VCpu states and configurations
/// Whether the VMCS has been launched. Used to determine whether to `vmx_launch` or `vmx_resume`.
launched: bool,
/// The guest entry point.
entry: Option<GuestPhysAddr>,
/// The EPT root address.
ept_root: Option<HostPhysAddr>,
// /// Whether this VCPU is a host VCpu. Used in type 1.5 hypervisor.
// is_host: bool, temporary removed because we don't care about type 1.5 now
// VMCS-related fields
/// The VMCS region.
vmcs: VmxRegion,
/// The I/O bitmap for the VMCS.
io_bitmap: IOBitmap,
/// The MSR bitmap for the VMCS.
msr_bitmap: MsrBitmap,
// Interrupt-related fields
/// Pending events to be injected to the guest.
pending_events: VecDeque<(u8, Option<u32>)>,
/// Emulated Local APIC.
vlapic: EmulatedLocalApic,
// Extra states
/// The XState of the VCpu. Both host and guest.
xstate: XState,
// Tracing-related fields
#[cfg(feature = "tracing")]
/// The guest registers when the VM-exit happens.
guest_regs_exiting: GeneralRegisters,
}
impl VmxVcpu {
/// Create a new [`VmxVcpu`].
pub fn new(vm_id: VMId, vcpu_id: VCpuId) -> AxResult<Self> {
let vmcs_revision_id = super::read_vmcs_revision_id();
let vcpu = Self {
guest_regs: GeneralRegisters::default(),
host_stack_top: 0,
launched: false,
entry: None,
ept_root: None,
// is_host: false,
vmcs: VmxRegion::new(vmcs_revision_id, false)?,
io_bitmap: IOBitmap::passthrough_all()?,
msr_bitmap: MsrBitmap::passthrough_all()?,
pending_events: VecDeque::with_capacity(8),
vlapic: EmulatedLocalApic::new(vm_id, vcpu_id),
xstate: XState::new(),
#[cfg(feature = "tracing")]
guest_regs_exiting: GeneralRegisters::default(),
};
info!("[HV] created VmxVcpu(vmcs: {:#x})", vcpu.vmcs.phys_addr());
Ok(vcpu)
}
/// Set the new [`VmxVcpu`] context from guest OS.
pub fn setup(&mut self, ept_root: HostPhysAddr, entry: GuestPhysAddr) -> AxResult {
self.setup_vmcs(entry, ept_root)?;
Ok(())
}
// /// Get the identifier of this [`VmxVcpu`].
// pub fn vcpu_id(&self) -> usize {
// get_current_vcpu::<Self>().unwrap().id()
// }
/// Bind this [`VmxVcpu`] to current logical processor.
pub fn bind_to_current_processor(&self) -> AxResult {
debug!(
"VmxVcpu bind to current processor vmcs @ {:#x}",
self.vmcs.phys_addr()
);
unsafe {
vmx::vmptrld(self.vmcs.phys_addr().as_usize() as u64).map_err(as_axerr)?;
}
self.setup_vmcs_host()?;
Ok(())
}
/// Unbind this [`VmxVcpu`] from current logical processor.
pub fn unbind_from_current_processor(&self) -> AxResult {
debug!(
"VmxVcpu unbind from current processor vmcs @ {:#x}",
self.vmcs.phys_addr()
);
unsafe {
vmx::vmclear(self.vmcs.phys_addr().as_usize() as u64).map_err(as_axerr)?;
}
Ok(())
}
/// Get CPU mode of the guest.
pub fn get_cpu_mode(&self) -> VmCpuMode {
let ia32_efer = Msr::IA32_EFER.read();
let cs_access_right = VmcsGuest32::CS_ACCESS_RIGHTS.read().unwrap();
let cr0 = VmcsGuestNW::CR0.read().unwrap();
if (ia32_efer & MSR_IA32_EFER_LMA_BIT) != 0 {
if (cs_access_right & 0x2000) != 0 {
// CS.L = 1
VmCpuMode::Mode64
} else {
VmCpuMode::Compatibility
}
} else if (cr0 & CR0_PE) != 0 {
VmCpuMode::Protected
} else {
VmCpuMode::Real
}
}
/// Run the guest. It returns when a vm-exit happens and returns the vm-exit if it cannot be handled by this [`VmxVcpu`] itself.
pub fn inner_run(&mut self) -> Option<VmxExitInfo> {
self.inject_pending_events().unwrap();
// Run guest
self.load_guest_xstate();
#[cfg(feature = "tracing")]
{
use crate::regs::GeneralRegistersDiff;
// Tracing, do a diff of the guest registers before entering the guest
let diff = GeneralRegistersDiff::new(self.guest_regs_exiting, self.guest_regs);
if !diff.is_same() {
debug!("VCpu registers changed during handling VM-exit: {diff:#x?}");
} else {
debug!("VCpu registers unchanged during handling VM-exit");
}
}
unsafe {
if self.launched {
self.vmx_resume();
} else {
self.launched = true;
VmcsHostNW::RSP
.write(&self.host_stack_top as *const _ as usize)
.unwrap();
self.vmx_launch();
}
}
self.load_host_xstate();
#[cfg(feature = "tracing")]
{
self.guest_regs_exiting = self.guest_regs;
}
// Handle vm-exits
let exit_info = self.exit_info().unwrap();
// debug!("VM exit: {:#x?}", exit_info);
match self.builtin_vmexit_handler(&exit_info) {
Some(result) => {
if result.is_err() {
panic!(
"VmxVcpu failed to handle a VM-exit that should be handled by itself: {:?}, error {:?}, vcpu: {:#x?}",
exit_info.exit_reason,
result.unwrap_err(),
self
);
}
None
}
None => Some(exit_info),
}
}
/// Basic information about VM exits.
pub fn exit_info(&self) -> AxResult<vmcs::VmxExitInfo> {
vmcs::exit_info()
}
/// Raw information for VM Exits Due to Vectored Events, See SDM 25.9.2
pub fn raw_interrupt_exit_info(&self) -> AxResult<u32> {
vmcs::raw_interrupt_exit_info()
}
/// Information for VM exits due to external interrupts.
pub fn interrupt_exit_info(&self) -> AxResult<vmcs::VmxInterruptInfo> {
vmcs::interrupt_exit_info()
}
/// Information for VM exits due to I/O instructions.
pub fn io_exit_info(&self) -> AxResult<vmcs::VmxIoExitInfo> {
vmcs::io_exit_info()
}
/// Information for VM exits due to nested page table faults (EPT violation).
pub fn nested_page_fault_info(&self) -> AxResult<NestedPageFaultInfo> {
vmcs::ept_violation_info()
}
/// Information for VM exits due to APIC access.
pub fn apic_access_exit_info(&self) -> AxResult<vmcs::ApicAccessExitInfo> {
vmcs::apic_access_exit_info()
}
/// Guest general-purpose registers.
pub fn regs(&self) -> &GeneralRegisters {
&self.guest_regs
}
/// Mutable reference of guest general-purpose registers.
pub fn regs_mut(&mut self) -> &mut GeneralRegisters {
&mut self.guest_regs
}
/// Guest stack pointer. (`RSP`)
pub fn stack_pointer(&self) -> usize {
VmcsGuestNW::RSP.read().unwrap()
}
/// Set guest stack pointer. (`RSP`)
pub fn set_stack_pointer(&mut self, rsp: usize) {
VmcsGuestNW::RSP.write(rsp).unwrap()
}
/// Translate guest virtual addr to linear addr
pub fn gla2gva(&self, guest_rip: GuestVirtAddr) -> GuestVirtAddr {
let cpu_mode = self.get_cpu_mode();
let seg_base = if cpu_mode == VmCpuMode::Mode64 {
0
} else {
VmcsGuestNW::CS_BASE.read().unwrap()
};
// debug!(
// "seg_base: {:#x}, guest_rip: {:#x} cpu mode:{:?}",
// seg_base, guest_rip, cpu_mode
// );
guest_rip + seg_base
}
/// Get Translate guest page table info
pub fn get_ptw_info(&self) -> GuestPageWalkInfo {
let top_entry = VmcsGuestNW::CR3.read().unwrap();
let level = self.get_paging_level();
let is_write_access = false;
let is_inst_fetch = false;
let is_user_mode_access = ((VmcsGuest32::SS_ACCESS_RIGHTS.read().unwrap() >> 5) & 0x3) == 3;
let mut pse = true;
let mut nxe =
(VmcsGuest64::IA32_EFER.read().unwrap() & EferFlags::NO_EXECUTE_ENABLE.bits()) != 0;
let wp = (VmcsGuestNW::CR0.read().unwrap() & Cr0Flags::WRITE_PROTECT.bits() as usize) != 0;
let is_smap_on = (VmcsGuestNW::CR4.read().unwrap()
& Cr4Flags::SUPERVISOR_MODE_ACCESS_PREVENTION.bits() as usize)
!= 0;
let is_smep_on = (VmcsGuestNW::CR4.read().unwrap()
& Cr4Flags::SUPERVISOR_MODE_EXECUTION_PROTECTION.bits() as usize)
!= 0;
let width: u32;
if level == 4 || level == 3 {
width = 9;
} else if level == 2 {
width = 10;
pse = VmcsGuestNW::CR4.read().unwrap() & Cr4Flags::PAGE_SIZE_EXTENSION.bits() as usize
!= 0;
nxe = false;
} else {
width = 0;
}
GuestPageWalkInfo {
top_entry,
level,
width,
is_user_mode_access,
is_write_access,
is_inst_fetch,
pse,
wp,
nxe,
is_smap_on,
is_smep_on,
}
}
/// Guest rip. (`RIP`)
pub fn rip(&self) -> usize {
VmcsGuestNW::RIP.read().unwrap()
}
/// Guest cs. (`cs`)
pub fn cs(&self) -> u16 {
VmcsGuest16::CS_SELECTOR.read().unwrap()
}
/// Advance guest `RIP` by `instr_len` bytes.
pub fn advance_rip(&mut self, instr_len: u8) -> AxResult {
VmcsGuestNW::RIP.write(VmcsGuestNW::RIP.read()? + instr_len as usize)
}
/// Add a virtual interrupt or exception to the pending events list,
/// and try to inject it before later VM entries.
pub fn queue_event(&mut self, vector: u8, err_code: Option<u32>) {
self.pending_events.push_back((vector, err_code));
}
/// If enable, a VM exit occurs at the beginning of any instruction if
/// `RFLAGS.IF` = 1 and there are no other blocking of interrupts.
/// (see SDM, Vol. 3C, Section 24.4.2)
pub fn set_interrupt_window(&mut self, enable: bool) -> AxResult {
let mut ctrl = VmcsControl32::PRIMARY_PROCBASED_EXEC_CONTROLS.read()?;
let bits = vmcs::controls::PrimaryControls::INTERRUPT_WINDOW_EXITING.bits();
if enable {
ctrl |= bits
} else {
ctrl &= !bits
}
VmcsControl32::PRIMARY_PROCBASED_EXEC_CONTROLS.write(ctrl)?;
Ok(())
}
/// Set I/O intercept by modifying I/O bitmap.
pub fn set_io_intercept_of_range(&mut self, port_base: u32, count: u32, intercept: bool) {
self.io_bitmap
.set_intercept_of_range(port_base, count, intercept)
}
/// Set msr intercept by modifying msr bitmap.
/// Todo: distinguish read and write.
pub fn set_msr_intercept_of_range(&mut self, msr: u32, intercept: bool) {
self.msr_bitmap.set_read_intercept(msr, intercept);
self.msr_bitmap.set_write_intercept(msr, intercept);
}
}
// Implementation of private methods
impl VmxVcpu {
fn setup_io_bitmap(&mut self) -> AxResult {
// By default, I/O bitmap is set as `intercept_all`.
// Todo: these should be combined with emulated pio device management,
// in `modules/axvm/src/device/x86_64/mod.rs` somehow.
let io_to_be_intercepted = QEMU_EXIT_PORT..QEMU_EXIT_PORT + 1; // QEMU exit port
self.io_bitmap.set_intercept_of_range(
io_to_be_intercepted.start as _,
io_to_be_intercepted.count() as u32,
true,
);
Ok(())
}
#[allow(dead_code)]
fn setup_msr_bitmap(&mut self) -> AxResult {
// Intercept IA32_APIC_BASE MSR accesses
// let msr = x86::msr::IA32_APIC_BASE;
// self.msr_bitmap.set_read_intercept(msr, true);
// self.msr_bitmap.set_write_intercept(msr, true);
// This is strange, guest Linux's access to `IA32_UMWAIT_CONTROL` will cause an exception.
// But if we intercept it, it seems okay.
const IA32_UMWAIT_CONTROL: u32 = 0xe1;
self.msr_bitmap
.set_write_intercept(IA32_UMWAIT_CONTROL, true);
self.msr_bitmap
.set_read_intercept(IA32_UMWAIT_CONTROL, true);
// Intercept all x2APIC MSR accesses
for msr in 0x800..=0x83f {
self.msr_bitmap.set_read_intercept(msr, true);
self.msr_bitmap.set_write_intercept(msr, true);
}
Ok(())
}
fn setup_vmcs(&mut self, entry: GuestPhysAddr, ept_root: HostPhysAddr) -> AxResult {
let paddr = self.vmcs.phys_addr().as_usize() as u64;
unsafe {
vmx::vmclear(paddr).map_err(as_axerr)?;
}
self.bind_to_current_processor()?;
self.setup_msr_bitmap()?;
self.setup_vmcs_guest(entry)?;
self.setup_vmcs_control(ept_root, true)?;
self.unbind_from_current_processor()?;
Ok(())
}
fn setup_vmcs_host(&self) -> AxResult {
VmcsHost64::IA32_PAT.write(Msr::IA32_PAT.read())?;
VmcsHost64::IA32_EFER.write(Msr::IA32_EFER.read())?;
VmcsHostNW::CR0.write(Cr0::read_raw() as _)?;
VmcsHostNW::CR3.write(Cr3::read_raw().0.start_address().as_u64() as _)?;
VmcsHostNW::CR4.write(Cr4::read_raw() as _)?;
VmcsHost16::ES_SELECTOR.write(x86::segmentation::es().bits())?;
VmcsHost16::CS_SELECTOR.write(x86::segmentation::cs().bits())?;
VmcsHost16::SS_SELECTOR.write(x86::segmentation::ss().bits())?;
VmcsHost16::DS_SELECTOR.write(x86::segmentation::ds().bits())?;
VmcsHost16::FS_SELECTOR.write(x86::segmentation::fs().bits())?;
VmcsHost16::GS_SELECTOR.write(x86::segmentation::gs().bits())?;
VmcsHostNW::FS_BASE.write(Msr::IA32_FS_BASE.read() as _)?;
VmcsHostNW::GS_BASE.write(Msr::IA32_GS_BASE.read() as _)?;
let tr = unsafe { x86::task::tr() };
let mut gdtp = DescriptorTablePointer::<u64>::default();
let mut idtp = DescriptorTablePointer::<u64>::default();
unsafe {
dtables::sgdt(&mut gdtp);
dtables::sidt(&mut idtp);
}
VmcsHost16::TR_SELECTOR.write(tr.bits())?;
VmcsHostNW::TR_BASE.write(get_tr_base(tr, &gdtp) as _)?;
VmcsHostNW::GDTR_BASE.write(gdtp.base as _)?;
VmcsHostNW::IDTR_BASE.write(idtp.base as _)?;
VmcsHostNW::RIP.write(Self::vmx_exit as usize)?;
VmcsHostNW::IA32_SYSENTER_ESP.write(0)?;
VmcsHostNW::IA32_SYSENTER_EIP.write(0)?;
VmcsHost32::IA32_SYSENTER_CS.write(0)?;
Ok(())
}
fn setup_vmcs_guest(&mut self, entry: GuestPhysAddr) -> AxResult {
let cr0_val: Cr0Flags =
Cr0Flags::NOT_WRITE_THROUGH | Cr0Flags::CACHE_DISABLE | Cr0Flags::EXTENSION_TYPE;
self.set_cr(0, cr0_val.bits());
self.set_cr(4, 0);
macro_rules! set_guest_segment {
($seg: ident, $access_rights: expr) => {{
use VmcsGuest16::*;
use VmcsGuest32::*;
use VmcsGuestNW::*;
paste::paste! {
[<$seg _SELECTOR>].write(0)?;
[<$seg _BASE>].write(0)?;
[<$seg _LIMIT>].write(0xffff)?;
[<$seg _ACCESS_RIGHTS>].write($access_rights)?;
}
}};
}
set_guest_segment!(ES, 0x93); // 16-bit, present, data, read/write, accessed
set_guest_segment!(CS, 0x9b); // 16-bit, present, code, exec/read, accessed
set_guest_segment!(SS, 0x93);
set_guest_segment!(DS, 0x93);
set_guest_segment!(FS, 0x93);
set_guest_segment!(GS, 0x93);
set_guest_segment!(TR, 0x8b); // present, system, 32-bit TSS busy
set_guest_segment!(LDTR, 0x82); // present, system, LDT
VmcsGuestNW::GDTR_BASE.write(0)?;
VmcsGuest32::GDTR_LIMIT.write(0xffff)?;
VmcsGuestNW::IDTR_BASE.write(0)?;
VmcsGuest32::IDTR_LIMIT.write(0xffff)?;
VmcsGuestNW::CR3.write(0)?;
VmcsGuestNW::DR7.write(0x400)?;
VmcsGuestNW::RSP.write(0)?;
VmcsGuestNW::RIP.write(entry.as_usize())?;
VmcsGuestNW::RFLAGS.write(0x2)?;
VmcsGuestNW::PENDING_DBG_EXCEPTIONS.write(0)?;
VmcsGuestNW::IA32_SYSENTER_ESP.write(0)?;
VmcsGuestNW::IA32_SYSENTER_EIP.write(0)?;
VmcsGuest32::IA32_SYSENTER_CS.write(0)?;
VmcsGuest32::INTERRUPTIBILITY_STATE.write(0)?;
VmcsGuest32::ACTIVITY_STATE.write(0)?;
VmcsGuest32::VMX_PREEMPTION_TIMER_VALUE.write(VMX_PREEMPTION_TIMER_SET_VALUE)?;
VmcsGuest64::LINK_PTR.write(u64::MAX)?; // SDM Vol. 3C, Section 24.4.2
VmcsGuest64::IA32_DEBUGCTL.write(0)?;
VmcsGuest64::IA32_PAT.write(Msr::IA32_PAT.read())?;
VmcsGuest64::IA32_EFER.write(0)?;
Ok(())
}
fn setup_vmcs_control(&mut self, ept_root: HostPhysAddr, is_guest: bool) -> AxResult {
// Intercept NMI and external interrupts.
use super::vmcs::controls::*;
use PinbasedControls as PinCtrl;
let raw_cpuid = CpuId::new();
vmcs::set_control(
VmcsControl32::PINBASED_EXEC_CONTROLS,
Msr::IA32_VMX_TRUE_PINBASED_CTLS,
Msr::IA32_VMX_PINBASED_CTLS.read() as u32,
(PinCtrl::NMI_EXITING | PinCtrl::EXTERNAL_INTERRUPT_EXITING).bits(),
// (PinCtrl::NMI_EXITING | PinCtrl::VMX_PREEMPTION_TIMER).bits(),
// PinCtrl::NMI_EXITING.bits(),
0,
)?;
// Intercept all I/O instructions, use MSR bitmaps, activate secondary controls,
// disable CR3 load/store interception.
use PrimaryControls as CpuCtrl;
vmcs::set_control(
VmcsControl32::PRIMARY_PROCBASED_EXEC_CONTROLS,
Msr::IA32_VMX_TRUE_PROCBASED_CTLS,
Msr::IA32_VMX_PROCBASED_CTLS.read() as u32,
(CpuCtrl::USE_IO_BITMAPS | CpuCtrl::USE_MSR_BITMAPS | CpuCtrl::SECONDARY_CONTROLS)
.bits(),
(CpuCtrl::CR3_LOAD_EXITING
| CpuCtrl::CR3_STORE_EXITING
| CpuCtrl::CR8_LOAD_EXITING
| CpuCtrl::CR8_STORE_EXITING)
.bits(),
)?;
// Enable EPT, RDTSCP, INVPCID, and unrestricted guest.
use SecondaryControls as CpuCtrl2;
let mut val =
// CpuCtrl2::VIRTUALIZE_APIC |
CpuCtrl2::ENABLE_EPT | CpuCtrl2::UNRESTRICTED_GUEST;
if let Some(features) = raw_cpuid.get_extended_processor_and_feature_identifiers()
&& features.has_rdtscp()
{
val |= CpuCtrl2::ENABLE_RDTSCP;
}
if let Some(features) = raw_cpuid.get_extended_feature_info()
&& features.has_invpcid()
{
val |= CpuCtrl2::ENABLE_INVPCID;
}
if let Some(features) = raw_cpuid.get_extended_state_info()
&& features.has_xsaves_xrstors()
{
val |= CpuCtrl2::ENABLE_XSAVES_XRSTORS;
}
vmcs::set_control(
VmcsControl32::SECONDARY_PROCBASED_EXEC_CONTROLS,
Msr::IA32_VMX_PROCBASED_CTLS2,
Msr::IA32_VMX_PROCBASED_CTLS2.read() as u32,
val.bits(),
0,
)?;
// Switch to 64-bit host, acknowledge interrupt info, switch IA32_PAT/IA32_EFER on VM exit.
use ExitControls as ExitCtrl;
vmcs::set_control(
VmcsControl32::VMEXIT_CONTROLS,
Msr::IA32_VMX_TRUE_EXIT_CTLS,
Msr::IA32_VMX_EXIT_CTLS.read() as u32,
(ExitCtrl::HOST_ADDRESS_SPACE_SIZE
| ExitCtrl::ACK_INTERRUPT_ON_EXIT
| ExitCtrl::SAVE_IA32_PAT
| ExitCtrl::LOAD_IA32_PAT
| ExitCtrl::SAVE_IA32_EFER
| ExitCtrl::LOAD_IA32_EFER)
.bits(),
0,
)?;
let mut val = EntryCtrl::LOAD_IA32_PAT | EntryCtrl::LOAD_IA32_EFER;
if !is_guest {
// IA-32e mode guest
// On processors that support Intel 64 architecture, this control determines whether the logical processor is in IA-32e mode after VM entry.
// Its value is loaded into IA32_EFER.LMA as part of VM entry.
val |= EntryCtrl::IA32E_MODE_GUEST;
}
// Load guest IA32_PAT/IA32_EFER on VM entry.
use EntryControls as EntryCtrl;
vmcs::set_control(
VmcsControl32::VMENTRY_CONTROLS,
Msr::IA32_VMX_TRUE_ENTRY_CTLS,
Msr::IA32_VMX_ENTRY_CTLS.read() as u32,
val.bits(),
0,
)?;
vmcs::set_ept_pointer(ept_root)?;
// No MSR switches if hypervisor doesn't use and there is only one vCPU.
VmcsControl32::VMEXIT_MSR_STORE_COUNT.write(0)?;
VmcsControl32::VMEXIT_MSR_LOAD_COUNT.write(0)?;
VmcsControl32::VMENTRY_MSR_LOAD_COUNT.write(0)?;
// VmcsControlNW::CR4_GUEST_HOST_MASK.write(0)?;
VmcsControl32::CR3_TARGET_COUNT.write(0)?;
// Pass-through exceptions (except #UD(6)), don't use I/O bitmap, set MSR bitmaps.
let exception_bitmap: u32 = 1 << 6;
self.setup_io_bitmap()?;
VmcsControl32::EXCEPTION_BITMAP.write(exception_bitmap)?;
VmcsControl64::IO_BITMAP_A_ADDR.write(self.io_bitmap.phys_addr().0.as_usize() as _)?;
VmcsControl64::IO_BITMAP_B_ADDR.write(self.io_bitmap.phys_addr().1.as_usize() as _)?;
VmcsControl64::MSR_BITMAPS_ADDR.write(self.msr_bitmap.phys_addr().as_usize() as _)?;
// VmcsControl64::APIC_ACCESS_ADDR.write(
// EmulatedLocalApic::<H::MmHal, DummyHal>::virtual_apic_access_addr().as_usize() as _,
// )?;
Ok(())
}
fn get_paging_level(&self) -> usize {
let mut level: u32 = 0; // non-paging
let cr0 = VmcsGuestNW::CR0.read().unwrap();
let cr4 = VmcsGuestNW::CR4.read().unwrap();
let efer = VmcsGuest64::IA32_EFER.read().unwrap();
// paging is enabled
if cr0 & Cr0Flags::PAGING.bits() as usize != 0 {
if cr4 & Cr4Flags::PHYSICAL_ADDRESS_EXTENSION.bits() as usize != 0 {
// is long mode
if efer & EferFlags::LONG_MODE_ACTIVE.bits() != 0 {
level = 4;
} else {
level = 3;
}
} else {
level = 2;
}
}
level as usize
}
}
// Implementaton for type1.5 hypervisor
// #[cfg(feature = "type1_5")]
impl VmxVcpu {
fn set_cr(&mut self, cr_idx: usize, val: u64) {
(|| -> AxResult {
// debug!("set guest CR{} to val {:#x}", cr_idx, val);
match cr_idx {
0 => {
// Retrieve/validate restrictions on CR0
//
// In addition to what the VMX MSRs tell us, make sure that
// - NW and CD are kept off as they are not updated on VM exit and we
// don't want them enabled for performance reasons while in root mode
// - PE and PG can be freely chosen (by the guest) because we demand
// unrestricted guest mode support anyway
// - ET is ignored
let must0 = Msr::IA32_VMX_CR0_FIXED1.read()
& !(Cr0Flags::NOT_WRITE_THROUGH | Cr0Flags::CACHE_DISABLE).bits();
let must1 = Msr::IA32_VMX_CR0_FIXED0.read()
& !(Cr0Flags::PAGING | Cr0Flags::PROTECTED_MODE_ENABLE).bits();
VmcsGuestNW::CR0.write(((val & must0) | must1) as _)?;
VmcsControlNW::CR0_READ_SHADOW.write(val as _)?;
VmcsControlNW::CR0_GUEST_HOST_MASK.write((must1 | !must0) as _)?;
}
3 => VmcsGuestNW::CR3.write(val as _)?,
4 => {
// Retrieve/validate restrictions on CR4
let must0 = Msr::IA32_VMX_CR4_FIXED1.read();
let must1 = Msr::IA32_VMX_CR4_FIXED0.read();
let val = val | Cr4Flags::VIRTUAL_MACHINE_EXTENSIONS.bits();
VmcsGuestNW::CR4.write(((val & must0) | must1) as _)?;
VmcsControlNW::CR4_READ_SHADOW.write(val as _)?;
VmcsControlNW::CR4_GUEST_HOST_MASK.write((must1 | !must0) as _)?;
}
_ => unreachable!(),
};
Ok(())
})()
.expect("Failed to write guest control register")
}
#[allow(dead_code)]
fn cr(&self, cr_idx: usize) -> usize {
(|| -> AxResult<usize> {
Ok(match cr_idx {
0 => VmcsGuestNW::CR0.read()?,
3 => VmcsGuestNW::CR3.read()?,
4 => {
let host_mask = VmcsControlNW::CR4_GUEST_HOST_MASK.read()?;
(VmcsControlNW::CR4_READ_SHADOW.read()? & host_mask)
| (VmcsGuestNW::CR4.read()? & !host_mask)
}
_ => unreachable!(),
})
})()
.expect("Failed to read guest control register")
}
}
/// Get ready then vmlaunch or vmresume.
macro_rules! vmx_entry_with {
($instr:literal) => {
naked_asm!(
save_regs_to_stack!(), // save host status
"mov [rdi + {host_stack_size}], rsp", // save current RSP to Vcpu::host_stack_top
"mov rsp, rdi", // set RSP to guest regs area
restore_regs_from_stack!(), // restore guest status
$instr, // let's go!
"jmp {failed}",
host_stack_size = const size_of::<GeneralRegisters>(),
failed = sym Self::vmx_entry_failed,
// options(noreturn),
)
}
}
impl VmxVcpu {
#[unsafe(naked)]
/// Enter guest with vmlaunch.
///
/// `#[naked]` is essential here, without it the rust compiler will think `&mut self` is not used and won't give us correct %rdi.
///
/// This function itself never returns, but [`Self::vmx_exit`] will do the return for this.
///
/// The return value is a dummy value.
unsafe extern "C" fn vmx_launch(&mut self) -> usize {
vmx_entry_with!("vmlaunch")
}
#[unsafe(naked)]
/// Enter guest with vmresume.
///
/// See [`Self::vmx_launch`] for detail.
unsafe extern "C" fn vmx_resume(&mut self) -> usize {
vmx_entry_with!("vmresume")
}
#[unsafe(naked)]
/// Return after vm-exit. This function is used only for returning from [`Self::vmx_launch`] or [`Self::vmx_resume`].
///
/// NEVER call this function directly.
///
/// The return value is a dummy value.
unsafe extern "C" fn vmx_exit(&mut self) -> usize {
// it's not necessary to use another `unsafe` here, as Rust now do not require it in naked functions.
naked_asm!(
save_regs_to_stack!(), // save guest status, after this, rsp points to the `VmxVcpu`
"mov rsp, [rsp + {host_stack_top}]", // set RSP to Vcpu::host_stack_top
restore_regs_from_stack!(), // restore host status
"ret",
host_stack_top = const size_of::<GeneralRegisters>(),
);
}
fn vmx_entry_failed() -> ! {
panic!("{}", vmcs::instruction_error().as_str())
}
/// Whether the guest interrupts are blocked. (SDM Vol. 3C, Section 24.4.2, Table 24-3)
fn allow_interrupt(&self) -> bool {
let rflags = VmcsGuestNW::RFLAGS.read().unwrap();
let block_state = VmcsGuest32::INTERRUPTIBILITY_STATE.read().unwrap();
rflags as u64 & x86_64::registers::rflags::RFlags::INTERRUPT_FLAG.bits() != 0
&& block_state == 0
}
/// Try to inject a pending event before next VM entry.
fn inject_pending_events(&mut self) -> AxResult {
if let Some(event) = self.pending_events.front() {
// trace!(
// "pending event vector {:#x} allow_int {}",
// event.0,
// self.allow_interrupt()
// );
if event.0 < 32 || self.allow_interrupt() {
// if it's an exception, or an interrupt that is not blocked, inject it directly.
vmcs::inject_event(event.0, event.1)?;
self.pending_events.pop_front();
} else {
// interrupts are blocked, enable interrupt-window exiting.
self.set_interrupt_window(true)?;
}
}
Ok(())
}
/// Handle vm-exits than can and should be handled by [`VmxVcpu`] itself.
///
/// Return the result or None if the vm-exit was not handled.
fn builtin_vmexit_handler(&mut self, exit_info: &VmxExitInfo) -> Option<AxResult> {
const X2APIC_MSR_BASE: u32 = 0x800;
const X2APIC_MSR_END: u32 = 0x8ff; // SDM says 0x8ff, but actually 0x83f, we respect the SDM here.
// Following vm-exits are handled here:
// - interrupt window: turn off interrupt window;
// - xsetbv: set guest xcr;
// - cr access: just panic;
match exit_info.exit_reason {
VmxExitReason::INTERRUPT_WINDOW => Some(self.set_interrupt_window(false)),
VmxExitReason::PREEMPTION_TIMER => Some(self.handle_vmx_preemption_timer()),
VmxExitReason::XSETBV => Some(self.handle_xsetbv()),
VmxExitReason::CR_ACCESS => Some(self.handle_cr()),
VmxExitReason::CPUID => Some(self.handle_cpuid()),
msr_rw @ (VmxExitReason::MSR_READ | VmxExitReason::MSR_WRITE)
if {
let msr = self.regs().rcx as u32;
(X2APIC_MSR_BASE..=X2APIC_MSR_END).contains(&msr)
} =>
{
Some(self.handle_apic_msr_access(
msr_rw == VmxExitReason::MSR_WRITE,
self.regs().rcx as u32,
))
}
VmxExitReason::APIC_ACCESS => Some(self.handle_apic_access(exit_info)),
_ => None,
}
}
/// Read a 64-bit value from EDX:EAX.
fn read_edx_eax(&self) -> u64 {
((self.regs().rdx & 0xffff_ffff) << 32) | (self.regs().rax & 0xffff_ffff)
}
/// Write a 64-bit value to EDX:EAX.
fn write_edx_eax(&mut self, val: u64) {
self.regs_mut().rax = val & 0xffff_ffff;
self.regs_mut().rdx = val >> 32;
}
fn handle_apic_msr_access(&mut self, write: bool, msr: u32) -> AxResult {
const VMEXIT_INSTR_LEN_RDMSR_WRMSR: u8 = 2;
self.advance_rip(VMEXIT_INSTR_LEN_RDMSR_WRMSR)?;
let msr = msr as _;
if write {
let value = self.read_edx_eax() as usize;
trace!("handle_vlapic_msr_write: msr={msr:#x}, value={value:#x}");
<EmulatedLocalApic as BaseDeviceOps<SysRegAddrRange>>::handle_write(
&self.vlapic,
SysRegAddr::new(msr),