xref: /DragonOS/kernel/src/virt/kvm/mod.rs (revision 816ee5ae545b60612055c939351911d6cf601c2e)
1 use self::kvm_dev::LockedKvmInode;
2 use crate::arch::KVMArch;
3 use crate::filesystem::devfs::devfs_register;
4 
5 use crate::libs::mutex::Mutex;
6 use alloc::vec::Vec;
7 use log::debug;
8 use vm::Vm;
9 
10 pub mod host_mem;
11 mod kvm_dev;
12 pub mod vcpu;
13 mod vcpu_dev;
14 pub mod vm;
15 mod vm_dev;
16 
17 // pub const KVM_MAX_VCPUS:u32 = 255;
18 // pub const GUEST_STACK_SIZE:usize = 1024;
19 // pub const HOST_STACK_SIZE:usize = 0x1000 * 6;
20 
21 /// @brief 获取全局的VM list
22 pub static VM_LIST: Mutex<Vec<Vm>> = Mutex::new(Vec::new());
23 
24 pub fn push_vm(id: usize) -> Result<(), ()> {
25     let mut vm_list = VM_LIST.lock();
26     if vm_list.iter().any(|x| x.id == id) {
27         debug!("push_vm: vm {} already exists", id);
28         Err(())
29     } else {
30         vm_list.push(Vm::new(id).unwrap());
31         Ok(())
32     }
33 }
34 
35 pub fn remove_vm(id: usize) -> Vm {
36     let mut vm_list = VM_LIST.lock();
37     match vm_list.iter().position(|x| x.id == id) {
38         None => {
39             panic!("VM[{}] not exist in VM LIST", id);
40         }
41         Some(idx) => vm_list.remove(idx),
42     }
43 }
44 
45 pub fn update_vm(id: usize, new_vm: Vm) {
46     remove_vm(id);
47     let mut vm_list = VM_LIST.lock();
48     vm_list.push(new_vm);
49 }
50 
51 pub fn vm(id: usize) -> Option<Vm> {
52     let vm_list = VM_LIST.lock();
53     vm_list.iter().find(|&x| x.id == id).cloned()
54 }
55 
56 #[inline(never)]
57 pub fn kvm_init() {
58     debug!("kvm init");
59 
60     match KVMArch::kvm_arch_cpu_supports_vm() {
61         Ok(_) => {
62             debug!("[+] CPU supports Intel VMX");
63         }
64         Err(e) => {
65             debug!("[-] CPU does not support Intel VMX: {:?}", e);
66         }
67     };
68 
69     KVMArch::kvm_arch_init().expect("kvm arch init");
70 
71     devfs_register("kvm", LockedKvmInode::new()).expect("Failed to register /dev/kvm");
72     // let r = devfs_register("kvm", LockedKvmInode::new());
73     // if r.is_err() {
74     //     panic!("Failed to register /dev/kvm");
75     // }
76     // let guest_stack = vec![0xCC; GUEST_STACK_SIZE];
77     // let host_stack = vec![0xCC; HOST_STACK_SIZE];
78     // let guest_rsp = guest_stack.as_ptr() as u64 + GUEST_STACK_SIZE as u64;
79     // let host_rsp = (host_stack.as_ptr() as u64) + HOST_STACK_SIZE  as u64;
80     // debug!("guest rsp: {:x}", guest_rsp);
81     // debug!("guest rip: {:x}", guest_code as *const () as u64);
82     // debug!("host rsp: {:x}", host_rsp);
83     // let hypervisor = Hypervisor::new(1, host_rsp, 0).expect("Cannot create hypervisor");
84     // let vcpu = VmxVcpu::new(1, Arc::new(Mutex::new(hypervisor)), host_rsp, guest_rsp,  guest_code as *const () as u64).expect("Cannot create VcpuData");
85     // vcpu.virtualize_cpu().expect("Cannot virtualize cpu");
86 }
87