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
use kvm_bindings::*;
use libc::{open, O_CLOEXEC, O_RDWR};
use std::fs::File;
use std::io;
use std::os::raw::{c_char, c_ulong};
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use cap::Cap;
use ioctls::vec_with_array_field;
use ioctls::vm::{new_vmfd, VmFd};
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use ioctls::CpuId;
use ioctls::Result;
use kvm_ioctls::*;
use sys_ioctl::*;
pub struct Kvm {
kvm: File,
}
impl Kvm {
#[allow(clippy::new_ret_no_self)]
pub fn new() -> Result<Self> {
let fd = Self::open_with_cloexec(true)?;
Ok(unsafe { Self::new_with_fd_number(fd) })
}
pub unsafe fn new_with_fd_number(fd: RawFd) -> Self {
Kvm {
kvm: File::from_raw_fd(fd),
}
}
pub fn open_with_cloexec(close_on_exec: bool) -> Result<RawFd> {
let open_flags = O_RDWR | if close_on_exec { O_CLOEXEC } else { 0 };
let ret = unsafe { open("/dev/kvm\0".as_ptr() as *const c_char, open_flags) };
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(ret)
}
}
pub fn get_api_version(&self) -> i32 {
unsafe { ioctl(self, KVM_GET_API_VERSION()) }
}
fn check_extension_int(&self, c: Cap) -> i32 {
unsafe { ioctl_with_val(self, KVM_CHECK_EXTENSION(), c as c_ulong) }
}
pub fn check_extension(&self, c: Cap) -> bool {
self.check_extension_int(c) > 0
}
pub fn get_vcpu_mmap_size(&self) -> Result<usize> {
let res = unsafe { ioctl(self, KVM_GET_VCPU_MMAP_SIZE()) };
if res > 0 {
Ok(res as usize)
} else {
Err(io::Error::last_os_error())
}
}
pub fn get_nr_vcpus(&self) -> usize {
let x = self.check_extension_int(Cap::NrVcpus);
if x > 0 {
x as usize
} else {
4
}
}
pub fn get_nr_memslots(&self) -> usize {
let x = self.check_extension_int(Cap::NrMemslots);
if x > 0 {
x as usize
} else {
32
}
}
pub fn get_max_vcpus(&self) -> usize {
match self.check_extension_int(Cap::MaxVcpus) {
0 => self.get_nr_vcpus(),
x => x as usize,
}
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_cpuid(&self, kind: u64, max_entries_count: usize) -> Result<CpuId> {
let mut cpuid = CpuId::new(max_entries_count);
let ret = unsafe {
ioctl_with_mut_ptr(self, kind, cpuid.as_mut_ptr())
};
if ret < 0 {
return Err(io::Error::last_os_error());
}
Ok(cpuid)
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_emulated_cpuid(&self, max_entries_count: usize) -> Result<CpuId> {
self.get_cpuid(KVM_GET_EMULATED_CPUID(), max_entries_count)
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_supported_cpuid(&self, max_entries_count: usize) -> Result<CpuId> {
self.get_cpuid(KVM_GET_SUPPORTED_CPUID(), max_entries_count)
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_msr_index_list(&self) -> Result<Vec<u32>> {
const MAX_KVM_MSR_ENTRIES: usize = 256;
let mut msr_list = vec_with_array_field::<kvm_msr_list, u32>(MAX_KVM_MSR_ENTRIES);
msr_list[0].nmsrs = MAX_KVM_MSR_ENTRIES as u32;
let ret = unsafe {
ioctl_with_mut_ref(self, KVM_GET_MSR_INDEX_LIST(), &mut msr_list[0])
};
if ret < 0 {
return Err(io::Error::last_os_error());
}
let mut nmsrs = msr_list[0].nmsrs;
let indices: &[u32] = unsafe {
if nmsrs > MAX_KVM_MSR_ENTRIES as u32 {
nmsrs = MAX_KVM_MSR_ENTRIES as u32;
}
msr_list[0].indices.as_slice(nmsrs as usize)
};
Ok(indices.to_vec())
}
pub fn create_vm(&self) -> Result<VmFd> {
let ret = unsafe { ioctl(&self.kvm, KVM_CREATE_VM()) };
if ret >= 0 {
let vm_file = unsafe { File::from_raw_fd(ret) };
let run_mmap_size = self.get_vcpu_mmap_size()?;
Ok(new_vmfd(vm_file, run_mmap_size))
} else {
Err(io::Error::last_os_error())
}
}
}
impl AsRawFd for Kvm {
fn as_raw_fd(&self) -> RawFd {
self.kvm.as_raw_fd()
}
}
#[cfg(test)]
mod tests {
use super::*;
use MAX_KVM_CPUID_ENTRIES;
#[test]
fn test_kvm_new() {
Kvm::new().unwrap();
}
#[test]
fn test_kvm_api_version() {
let kvm = Kvm::new().unwrap();
assert_eq!(kvm.get_api_version(), 12);
assert!(kvm.check_extension(Cap::UserMemory));
}
#[test]
fn test_kvm_getters() {
let kvm = Kvm::new().unwrap();
let nr_vcpus = kvm.get_nr_vcpus();
assert!(nr_vcpus >= 4);
assert!(kvm.get_max_vcpus() >= nr_vcpus);
assert!(kvm.get_vcpu_mmap_size().unwrap() > 0);
assert!(kvm.get_nr_memslots() >= 32);
}
#[test]
fn test_create_vm() {
let kvm = Kvm::new().unwrap();
let vm = kvm.create_vm().unwrap();
assert_eq!(vm.run_size(), kvm.get_vcpu_mmap_size().unwrap());
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[test]
fn test_get_supported_cpuid() {
let kvm = Kvm::new().unwrap();
let mut cpuid = kvm.get_supported_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap();
let cpuid_entries = cpuid.mut_entries_slice();
assert!(cpuid_entries.len() > 0);
assert!(cpuid_entries.len() <= MAX_KVM_CPUID_ENTRIES);
}
#[test]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn test_get_emulated_cpuid() {
let kvm = Kvm::new().unwrap();
let mut cpuid = kvm.get_emulated_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap();
let cpuid_entries = cpuid.mut_entries_slice();
assert!(cpuid_entries.len() > 0);
assert!(cpuid_entries.len() <= MAX_KVM_CPUID_ENTRIES);
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[test]
fn test_cpuid_clone() {
let kvm = Kvm::new().unwrap();
let cpuid_1 = kvm.get_supported_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap();
let mut cpuid_2 = cpuid_1.clone();
assert!(cpuid_1 == cpuid_2);
cpuid_2 = unsafe { std::mem::zeroed() };
assert!(cpuid_1 != cpuid_2);
}
#[test]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_msr_index_list() {
let kvm = Kvm::new().unwrap();
let msr_list = kvm.get_msr_index_list().unwrap();
assert!(msr_list.len() >= 2);
}
fn get_raw_errno<T>(result: super::Result<T>) -> i32 {
result.err().unwrap().raw_os_error().unwrap()
}
#[test]
fn test_bad_kvm_fd() {
let badf_errno = libc::EBADF;
let faulty_kvm = Kvm {
kvm: unsafe { File::from_raw_fd(-1) },
};
assert_eq!(get_raw_errno(faulty_kvm.get_vcpu_mmap_size()), badf_errno);
assert_eq!(faulty_kvm.get_nr_vcpus(), 4);
assert_eq!(faulty_kvm.get_nr_memslots(), 32);
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
assert_eq!(get_raw_errno(faulty_kvm.get_emulated_cpuid(4)), badf_errno);
assert_eq!(get_raw_errno(faulty_kvm.get_supported_cpuid(4)), badf_errno);
assert_eq!(get_raw_errno(faulty_kvm.get_msr_index_list()), badf_errno);
}
assert_eq!(get_raw_errno(faulty_kvm.create_vm()), badf_errno);
}
}