-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathvcpu.rs
3129 lines (2944 loc) · 114 KB
/
vcpu.rs
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 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use kvm_bindings::*;
use libc::EINVAL;
use std::fs::File;
use std::os::unix::io::{AsRawFd, RawFd};
use crate::ioctls::{KvmRunWrapper, Result};
use crate::kvm_ioctls::*;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use kvm_bindings::{
CpuId, Msrs, KVM_MAX_CPUID_ENTRIES, KVM_MSR_EXIT_REASON_FILTER, KVM_MSR_EXIT_REASON_INVAL,
KVM_MSR_EXIT_REASON_UNKNOWN,
};
use vmm_sys_util::errno;
use vmm_sys_util::ioctl::{ioctl, ioctl_with_mut_ref, ioctl_with_ref};
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use vmm_sys_util::ioctl::{ioctl_with_mut_ptr, ioctl_with_ptr, ioctl_with_val};
/// Helper method to obtain the size of the register through its id
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
pub fn reg_size(reg_id: u64) -> usize {
2_usize.pow(((reg_id & KVM_REG_SIZE_MASK) >> KVM_REG_SIZE_SHIFT) as u32)
}
/// Information about a [`VcpuExit`] triggered by an MSR read (`KVM_EXIT_X86_RDMSR`).
#[derive(Debug)]
pub struct ReadMsrExit<'a> {
/// Must be set to 1 by the the user if the read access should fail. This
/// will inject a #GP fault into the guest when the VCPU is executed
/// again.
pub error: &'a mut u8,
/// The reason for this exit.
pub reason: MsrExitReason,
/// The MSR the guest wants to read.
pub index: u32,
/// The data to be supplied by the user as the MSR Contents to the guest.
pub data: &'a mut u64,
}
/// Information about a [`VcpuExit`] triggered by an MSR write (`KVM_EXIT_X86_WRMSR`).
#[derive(Debug)]
pub struct WriteMsrExit<'a> {
/// Must be set to 1 by the the user if the write access should fail. This
/// will inject a #GP fault into the guest when the VCPU is executed
/// again.
pub error: &'a mut u8,
/// The reason for this exit.
pub reason: MsrExitReason,
/// The MSR the guest wants to write.
pub index: u32,
/// The data the guest wants to write into the MSR.
pub data: u64,
}
bitflags::bitflags! {
/// The reason for a [`VcpuExit::X86Rdmsr`] or[`VcpuExit::X86Wrmsr`]. This
/// is also used when enabling
/// [`Cap::X86UserSpaceMsr`](crate::Cap::X86UserSpaceMsr) to specify which
/// reasons should be forwarded to the user via those exits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MsrExitReason: u32 {
/// Corresponds to [`KVM_MSR_EXIT_REASON_UNKNOWN`]. The exit was
/// triggered by an access to an MSR that is unknown to KVM.
const Unknown = KVM_MSR_EXIT_REASON_UNKNOWN;
/// Corresponds to [`KVM_MSR_EXIT_REASON_INVAL`]. The exit was
/// triggered by an access to an invalid MSR or to reserved bits.
const Inval = KVM_MSR_EXIT_REASON_INVAL;
/// Corresponds to [`KVM_MSR_EXIT_REASON_FILTER`]. The exit was
/// triggered by an access to a filtered MSR.
const Filter = KVM_MSR_EXIT_REASON_FILTER;
}
}
/// Reasons for vCPU exits.
///
/// The exit reasons are mapped to the `KVM_EXIT_*` defines in the
/// [Linux KVM header](https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/kvm.h).
#[derive(Debug)]
pub enum VcpuExit<'a> {
/// An out port instruction was run on the given port with the given data.
IoOut(u16 /* port */, &'a [u8] /* data */),
/// An in port instruction was run on the given port.
///
/// The given slice should be filled in before [run()](struct.VcpuFd.html#method.run)
/// is called again.
IoIn(u16 /* port */, &'a mut [u8] /* data */),
/// A read instruction was run against the given MMIO address.
///
/// The given slice should be filled in before [run()](struct.VcpuFd.html#method.run)
/// is called again.
MmioRead(u64 /* address */, &'a mut [u8]),
/// A write instruction was run against the given MMIO address with the given data.
MmioWrite(u64 /* address */, &'a [u8]),
/// Corresponds to KVM_EXIT_UNKNOWN.
Unknown,
/// Corresponds to KVM_EXIT_EXCEPTION.
Exception,
/// Corresponds to KVM_EXIT_HYPERCALL.
Hypercall,
/// Corresponds to KVM_EXIT_DEBUG.
///
/// Provides architecture specific information for the debug event.
Debug(kvm_debug_exit_arch),
/// Corresponds to KVM_EXIT_HLT.
Hlt,
/// Corresponds to KVM_EXIT_IRQ_WINDOW_OPEN.
IrqWindowOpen,
/// Corresponds to KVM_EXIT_SHUTDOWN.
Shutdown,
/// Corresponds to KVM_EXIT_FAIL_ENTRY.
FailEntry(
u64, /* hardware_entry_failure_reason */
u32, /* cpu */
),
/// Corresponds to KVM_EXIT_INTR.
Intr,
/// Corresponds to KVM_EXIT_SET_TPR.
SetTpr,
/// Corresponds to KVM_EXIT_TPR_ACCESS.
TprAccess,
/// Corresponds to KVM_EXIT_S390_SIEIC.
S390Sieic,
/// Corresponds to KVM_EXIT_S390_RESET.
S390Reset,
/// Corresponds to KVM_EXIT_DCR.
Dcr,
/// Corresponds to KVM_EXIT_NMI.
Nmi,
/// Corresponds to KVM_EXIT_INTERNAL_ERROR.
InternalError,
/// Corresponds to KVM_EXIT_OSI.
Osi,
/// Corresponds to KVM_EXIT_PAPR_HCALL.
PaprHcall,
/// Corresponds to KVM_EXIT_S390_UCONTROL.
S390Ucontrol,
/// Corresponds to KVM_EXIT_WATCHDOG.
Watchdog,
/// Corresponds to KVM_EXIT_S390_TSCH.
S390Tsch,
/// Corresponds to KVM_EXIT_EPR.
Epr,
/// Corresponds to KVM_EXIT_SYSTEM_EVENT.
SystemEvent(u32 /* type */, u64 /* flags */),
/// Corresponds to KVM_EXIT_S390_STSI.
S390Stsi,
/// Corresponds to KVM_EXIT_IOAPIC_EOI.
IoapicEoi(u8 /* vector */),
/// Corresponds to KVM_EXIT_HYPERV.
Hyperv,
/// Corresponds to KVM_EXIT_X86_RDMSR.
X86Rdmsr(ReadMsrExit<'a>),
/// Corresponds to KVM_EXIT_X86_WRMSR.
X86Wrmsr(WriteMsrExit<'a>),
/// Corresponds to KVM_EXIT_X86_BUS_LOCK.
X86BusLock,
/// Corresponds to an exit reason that is unknown from the current version
/// of the kvm-ioctls crate. Let the consumer decide about what to do with
/// it.
Unsupported(u32),
}
/// Wrapper over KVM vCPU ioctls.
#[derive(Debug)]
pub struct VcpuFd {
vcpu: File,
kvm_run_ptr: KvmRunWrapper,
}
/// KVM Sync Registers used to tell KVM which registers to sync
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub enum SyncReg {
/// General purpose registers,
Register = KVM_SYNC_X86_REGS,
/// System registers
SystemRegister = KVM_SYNC_X86_SREGS,
/// CPU events
VcpuEvents = KVM_SYNC_X86_EVENTS,
}
impl VcpuFd {
/// Returns the vCPU general purpose registers.
///
/// The registers are returned in a `kvm_regs` structure as defined in the
/// [KVM API documentation](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// See documentation for `KVM_GET_REGS`.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
/// let regs = vcpu.get_regs().unwrap();
/// ```
#[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
pub fn get_regs(&self) -> Result<kvm_regs> {
let mut regs = kvm_regs::default();
// SAFETY: Safe because we know that our file is a vCPU fd, we know the kernel will only
// read the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_REGS(), &mut regs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(regs)
}
/// Sets a specified piece of cpu configuration and/or state.
///
/// See the documentation for `KVM_SET_DEVICE_ATTR` in
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt)
/// # Arguments
///
/// * `device_attr` - The cpu attribute to be set.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// # use kvm_bindings::{
/// KVM_ARM_VCPU_PMU_V3_CTRL, KVM_ARM_VCPU_PMU_V3_INIT
/// };
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
///
/// let dist_attr = kvm_bindings::kvm_device_attr {
/// group: KVM_ARM_VCPU_PMU_V3_CTRL,
/// attr: u64::from(KVM_ARM_VCPU_PMU_V3_INIT),
/// addr: 0x0,
/// flags: 0,
/// };
///
/// if (vcpu.has_device_attr(&dist_attr).is_ok()) {
/// vcpu.set_device_attr(&dist_attr).unwrap();
/// }
/// ```
#[cfg(target_arch = "aarch64")]
pub fn set_device_attr(&self, device_attr: &kvm_device_attr) -> Result<()> {
// SAFETY: Safe because we call this with a Vcpu fd and we trust the kernel.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_DEVICE_ATTR(), device_attr) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Tests whether a cpu supports a particular attribute.
///
/// See the documentation for `KVM_HAS_DEVICE_ATTR` in
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt)
/// # Arguments
///
/// * `device_attr` - The cpu attribute to be tested. `addr` field is ignored.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// # use kvm_bindings::{
/// KVM_ARM_VCPU_PMU_V3_CTRL, KVM_ARM_VCPU_PMU_V3_INIT
/// };
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
///
/// let dist_attr = kvm_bindings::kvm_device_attr {
/// group: KVM_ARM_VCPU_PMU_V3_CTRL,
/// attr: u64::from(KVM_ARM_VCPU_PMU_V3_INIT),
/// addr: 0x0,
/// flags: 0,
/// };
///
/// vcpu.has_device_attr(&dist_attr);
/// ```
#[cfg(target_arch = "aarch64")]
pub fn has_device_attr(&self, device_attr: &kvm_device_attr) -> Result<()> {
// SAFETY: Safe because we call this with a Vcpu fd and we trust the kernel.
let ret = unsafe { ioctl_with_ref(self, KVM_HAS_DEVICE_ATTR(), device_attr) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Sets the vCPU general purpose registers using the `KVM_SET_REGS` ioctl.
///
/// # Arguments
///
/// * `regs` - general purpose registers. For details check the `kvm_regs` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
///
/// #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
/// {
/// // Get the current vCPU registers.
/// let mut regs = vcpu.get_regs().unwrap();
/// // Set a new value for the Instruction Pointer.
/// regs.rip = 0x100;
/// vcpu.set_regs(®s).unwrap();
/// }
/// ```
#[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
pub fn set_regs(&self, regs: &kvm_regs) -> Result<()> {
// SAFETY: Safe because we know that our file is a vCPU fd, we know the kernel will only
// read the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_REGS(), regs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Returns the vCPU special registers.
///
/// The registers are returned in a `kvm_sregs` structure as defined in the
/// [KVM API documentation](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// See documentation for `KVM_GET_SREGS`.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
/// let sregs = vcpu.get_sregs().unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_sregs(&self) -> Result<kvm_sregs> {
let mut regs = kvm_sregs::default();
// SAFETY: Safe because we know that our file is a vCPU fd, we know the kernel will only
// write the correct amount of memory to our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_SREGS(), &mut regs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(regs)
}
/// Sets the vCPU special registers using the `KVM_SET_SREGS` ioctl.
///
/// # Arguments
///
/// * `sregs` - Special registers. For details check the `kvm_sregs` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
/// {
/// let mut sregs = vcpu.get_sregs().unwrap();
/// // Update the code segment (cs).
/// sregs.cs.base = 0;
/// sregs.cs.selector = 0;
/// vcpu.set_sregs(&sregs).unwrap();
/// }
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_sregs(&self, sregs: &kvm_sregs) -> Result<()> {
// SAFETY: Safe because we know that our file is a vCPU fd, we know the kernel will only
// read the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_SREGS(), sregs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Returns the floating point state (FPU) from the vCPU.
///
/// The state is returned in a `kvm_fpu` structure as defined in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// See the documentation for `KVM_GET_FPU`.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
/// let fpu = vcpu.get_fpu().unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_fpu(&self) -> Result<kvm_fpu> {
let mut fpu = kvm_fpu::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_fpu struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_FPU(), &mut fpu) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(fpu)
}
/// Set the floating point state (FPU) of a vCPU using the `KVM_SET_FPU` ioct.
///
/// # Arguments
///
/// * `fpu` - FPU configuration. For details check the `kvm_fpu` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// # use kvm_bindings::kvm_fpu;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
/// {
/// let KVM_FPU_CWD: u16 = 0x37f;
/// let fpu = kvm_fpu {
/// fcw: KVM_FPU_CWD,
/// ..Default::default()
/// };
/// vcpu.set_fpu(&fpu).unwrap();
/// }
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_fpu(&self, fpu: &kvm_fpu) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_fpu struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_FPU(), fpu) };
if ret < 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// X86 specific call to setup the CPUID registers.
///
/// See the documentation for `KVM_SET_CPUID2`.
///
/// # Arguments
///
/// * `cpuid` - CPUID registers.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_bindings::KVM_MAX_CPUID_ENTRIES;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let mut kvm_cpuid = kvm.get_supported_cpuid(KVM_MAX_CPUID_ENTRIES).unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
///
/// // Update the CPUID entries to disable the EPB feature.
/// const ECX_EPB_SHIFT: u32 = 3;
/// {
/// let entries = kvm_cpuid.as_mut_slice();
/// for entry in entries.iter_mut() {
/// match entry.function {
/// 6 => entry.ecx &= !(1 << ECX_EPB_SHIFT),
/// _ => (),
/// }
/// }
/// }
///
/// vcpu.set_cpuid2(&kvm_cpuid).unwrap();
/// ```
///
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_cpuid2(&self, cpuid: &CpuId) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_cpuid2 struct.
let ret = unsafe { ioctl_with_ptr(self, KVM_SET_CPUID2(), cpuid.as_fam_struct_ptr()) };
if ret < 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// X86 specific call to retrieve the CPUID registers.
///
/// It requires knowledge of how many `kvm_cpuid_entry2` entries there are to get.
/// See the documentation for `KVM_GET_CPUID2` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `num_entries` - Number of CPUID entries to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_bindings::KVM_MAX_CPUID_ENTRIES;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let cpuid = vcpu.get_cpuid2(KVM_MAX_CPUID_ENTRIES).unwrap();
/// ```
///
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_cpuid2(&self, num_entries: usize) -> Result<CpuId> {
if num_entries > KVM_MAX_CPUID_ENTRIES {
// Returns the same error the underlying `ioctl` would have sent.
return Err(errno::Error::new(libc::ENOMEM));
}
let mut cpuid = CpuId::new(num_entries).map_err(|_| errno::Error::new(libc::ENOMEM))?;
let ret =
// SAFETY: Here we trust the kernel not to read past the end of the kvm_cpuid2 struct.
unsafe { ioctl_with_mut_ptr(self, KVM_GET_CPUID2(), cpuid.as_mut_fam_struct_ptr()) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(cpuid)
}
///
/// See the documentation for `KVM_ENABLE_CAP`.
///
/// # Arguments
///
/// * kvm_enable_cap - KVM capability structure. For details check the `kvm_enable_cap`
/// structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_bindings::{kvm_enable_cap, KVM_MAX_CPUID_ENTRIES, KVM_CAP_HYPERV_SYNIC, KVM_CAP_SPLIT_IRQCHIP};
/// # use kvm_ioctls::{Kvm, Cap};
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let mut cap: kvm_enable_cap = Default::default();
/// if cfg!(target_arch = "x86") || cfg!(target_arch = "x86_64") {
/// // KVM_CAP_HYPERV_SYNIC needs KVM_CAP_SPLIT_IRQCHIP enabled
/// cap.cap = KVM_CAP_SPLIT_IRQCHIP;
/// cap.args[0] = 24;
/// vm.enable_cap(&cap).unwrap();
///
/// let vcpu = vm.create_vcpu(0).unwrap();
/// if kvm.check_extension(Cap::HypervSynic) {
/// let mut cap: kvm_enable_cap = Default::default();
/// cap.cap = KVM_CAP_HYPERV_SYNIC;
/// vcpu.enable_cap(&cap).unwrap();
/// }
/// }
/// ```
///
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn enable_cap(&self, cap: &kvm_enable_cap) -> Result<()> {
// SAFETY: The ioctl is safe because we allocated the struct and we know the
// kernel will write exactly the size of the struct.
let ret = unsafe { ioctl_with_ref(self, KVM_ENABLE_CAP(), cap) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Returns the state of the LAPIC (Local Advanced Programmable Interrupt Controller).
///
/// The state is returned in a `kvm_lapic_state` structure as defined in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// See the documentation for `KVM_GET_LAPIC`.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// // For `get_lapic` to work, you first need to create a IRQ chip before creating the vCPU.
/// vm.create_irq_chip().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let lapic = vcpu.get_lapic().unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_lapic(&self) -> Result<kvm_lapic_state> {
let mut klapic = kvm_lapic_state::default();
// SAFETY: The ioctl is unsafe unless you trust the kernel not to write past the end of the
// local_apic struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_LAPIC(), &mut klapic) };
if ret < 0 {
return Err(errno::Error::last());
}
Ok(klapic)
}
/// Sets the state of the LAPIC (Local Advanced Programmable Interrupt Controller).
///
/// See the documentation for `KVM_SET_LAPIC`.
///
/// # Arguments
///
/// * `klapic` - LAPIC state. For details check the `kvm_lapic_state` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// use std::io::Write;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// // For `get_lapic` to work, you first need to create a IRQ chip before creating the vCPU.
/// vm.create_irq_chip().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let mut lapic = vcpu.get_lapic().unwrap();
///
/// // Write to APIC_ICR offset the value 2.
/// let apic_icr_offset = 0x300;
/// let write_value: &[u8] = &[2, 0, 0, 0];
/// let mut apic_icr_slice =
/// unsafe { &mut *(&mut lapic.regs[apic_icr_offset..] as *mut [i8] as *mut [u8]) };
/// apic_icr_slice.write(write_value).unwrap();
///
/// // Update the value of LAPIC.
/// vcpu.set_lapic(&lapic).unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_lapic(&self, klapic: &kvm_lapic_state) -> Result<()> {
// SAFETY: The ioctl is safe because the kernel will only read from the klapic struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_LAPIC(), klapic) };
if ret < 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Returns the model-specific registers (MSR) for this vCPU.
///
/// It emulates `KVM_GET_MSRS` ioctl's behavior by returning the number of MSRs
/// successfully read upon success or the last error number in case of failure.
/// The MSRs are returned in the `msr` method argument.
///
/// # Arguments
///
/// * `msrs` - MSRs (input/output). For details check the `kvm_msrs` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// # use kvm_bindings::{kvm_msr_entry, Msrs};
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// // Configure the struct to say which entries we want to get.
/// let mut msrs = Msrs::from_entries(&[
/// kvm_msr_entry {
/// index: 0x0000_0174,
/// ..Default::default()
/// },
/// kvm_msr_entry {
/// index: 0x0000_0175,
/// ..Default::default()
/// },
/// ])
/// .unwrap();
/// let read = vcpu.get_msrs(&mut msrs).unwrap();
/// assert_eq!(read, 2);
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_msrs(&self, msrs: &mut Msrs) -> Result<usize> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_msrs struct.
let ret = unsafe { ioctl_with_mut_ptr(self, KVM_GET_MSRS(), msrs.as_mut_fam_struct_ptr()) };
if ret < 0 {
return Err(errno::Error::last());
}
Ok(ret as usize)
}
/// Setup the model-specific registers (MSR) for this vCPU.
/// Returns the number of MSR entries actually written.
///
/// See the documentation for `KVM_SET_MSRS`.
///
/// # Arguments
///
/// * `msrs` - MSRs. For details check the `kvm_msrs` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// # use kvm_bindings::{kvm_msr_entry, Msrs};
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
///
/// // Configure the entries we want to set.
/// let mut msrs = Msrs::from_entries(&[kvm_msr_entry {
/// index: 0x0000_0174,
/// ..Default::default()
/// }])
/// .unwrap();
/// let written = vcpu.set_msrs(&msrs).unwrap();
/// assert_eq!(written, 1);
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_msrs(&self, msrs: &Msrs) -> Result<usize> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_msrs struct.
let ret = unsafe { ioctl_with_ptr(self, KVM_SET_MSRS(), msrs.as_fam_struct_ptr()) };
// KVM_SET_MSRS actually returns the number of msr entries written.
if ret < 0 {
return Err(errno::Error::last());
}
Ok(ret as usize)
}
/// Returns the vcpu's current "multiprocessing state".
///
/// See the documentation for `KVM_GET_MP_STATE` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_mp_state` - multiprocessing state to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let mp_state = vcpu.get_mp_state().unwrap();
/// ```
#[cfg(any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "s390"
))]
pub fn get_mp_state(&self) -> Result<kvm_mp_state> {
let mut mp_state = Default::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_mp_state struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_MP_STATE(), &mut mp_state) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(mp_state)
}
/// Sets the vcpu's current "multiprocessing state".
///
/// See the documentation for `KVM_SET_MP_STATE` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_mp_state` - multiprocessing state to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let mp_state = Default::default();
/// // Your `mp_state` manipulation here.
/// vcpu.set_mp_state(mp_state).unwrap();
/// ```
#[cfg(any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "s390"
))]
pub fn set_mp_state(&self, mp_state: kvm_mp_state) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_mp_state struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_MP_STATE(), &mp_state) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// X86 specific call that returns the vcpu's current "xsave struct".
///
/// See the documentation for `KVM_GET_XSAVE` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_xsave` - xsave struct to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let xsave = vcpu.get_xsave().unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_xsave(&self) -> Result<kvm_xsave> {
let mut xsave = Default::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_xsave struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_XSAVE(), &mut xsave) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(xsave)
}
/// X86 specific call that sets the vcpu's current "xsave struct".
///
/// See the documentation for `KVM_SET_XSAVE` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_xsave` - xsave struct to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let xsave = Default::default();
/// // Your `xsave` manipulation here.
/// vcpu.set_xsave(&xsave).unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_xsave(&self, xsave: &kvm_xsave) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_xsave struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_XSAVE(), xsave) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// X86 specific call that returns the vcpu's current "xcrs".
///
/// See the documentation for `KVM_GET_XCRS` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_xcrs` - xcrs to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let xcrs = vcpu.get_xcrs().unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_xcrs(&self) -> Result<kvm_xcrs> {
let mut xcrs = Default::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_xcrs struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_XCRS(), &mut xcrs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(xcrs)
}
/// X86 specific call that sets the vcpu's current "xcrs".
///
/// See the documentation for `KVM_SET_XCRS` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_xcrs` - xcrs to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let xcrs = Default::default();
/// // Your `xcrs` manipulation here.
/// vcpu.set_xcrs(&xcrs).unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_xcrs(&self, xcrs: &kvm_xcrs) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_xcrs struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_XCRS(), xcrs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// X86 specific call that returns the vcpu's current "debug registers".
///
/// See the documentation for `KVM_GET_DEBUGREGS` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_debugregs` - debug registers to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let debug_regs = vcpu.get_debug_regs().unwrap();
/// ```
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_debug_regs(&self) -> Result<kvm_debugregs> {
let mut debug_regs = Default::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_debugregs struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_DEBUGREGS(), &mut debug_regs) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(debug_regs)
}
/// X86 specific call that sets the vcpu's current "debug registers".
///
/// See the documentation for `KVM_SET_DEBUGREGS` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `kvm_debugregs` - debug registers to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let debug_regs = Default::default();