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