xref: /DragonOS/kernel/src/virt/kvm/vm_dev.rs (revision f110d330d5493f383067b4e82ebbfb72f40457b2)
1 use crate::filesystem::devfs::DevFS;
2 use crate::filesystem::vfs::{
3     core::generate_inode_id,
4     file::{File, FileMode},
5     make_rawdev, FilePrivateData, FileSystem, FileType, IndexNode, Metadata,
6 };
7 use crate::mm::VirtAddr;
8 use crate::process::ProcessManager;
9 use crate::syscall::user_access::copy_from_user;
10 use crate::virt::kvm::host_mem::KvmUserspaceMemoryRegion;
11 use crate::virt::kvm::update_vm;
12 use crate::virt::kvm::vcpu_dev::LockedVcpuInode;
13 use crate::virt::kvm::vm;
14 use crate::{arch::KVMArch, libs::spinlock::SpinLock, syscall::SystemError, time::TimeSpec};
15 use crate::{filesystem, kdebug};
16 use alloc::{
17     string::String,
18     sync::{Arc, Weak},
19     vec::Vec,
20 };
21 
22 // pub const KVM_API_VERSION:u32 = 12;
23 // pub const GUEST_STACK_SIZE:usize = 1024;
24 // pub const HOST_STACK_SIZE:usize = 0x1000 * 6;
25 
26 /*
27  * ioctls for /dev/vm fds:
28  */
29 pub const KVM_CREATE_VCPU: u32 = 0x00;
30 pub const KVM_SET_USER_MEMORY_REGION: u32 = 0x01;
31 pub const KVM_GET_DIRTY_LOG: u32 = 0x02;
32 pub const KVM_IRQFD: u32 = 0x03;
33 pub const KVM_IOEVENTFD: u32 = 0x04;
34 pub const KVM_IRQ_LINE_STATUS: u32 = 0x05;
35 
36 //  #[derive(Debug)]
37 //  pub struct InodeInfo {
38 //     kvm: Arc<Hypervisor>,
39 //  }
40 
41 #[derive(Debug)]
42 pub struct VmInode {
43     /// uuid 暂时不知道有什么用(x
44     // uuid: Uuid,
45     /// 指向自身的弱引用
46     self_ref: Weak<LockedVmInode>,
47     /// 指向inode所在的文件系统对象的指针
48     fs: Weak<DevFS>,
49     /// INode 元数据
50     metadata: Metadata,
51     // fdata: InodeInfo,
52 }
53 
54 #[derive(Debug)]
55 pub struct LockedVmInode(SpinLock<VmInode>);
56 
57 impl LockedVmInode {
58     pub fn new() -> Arc<Self> {
59         let inode = VmInode {
60             self_ref: Weak::default(),
61             fs: Weak::default(),
62             metadata: Metadata {
63                 dev_id: 1,
64                 inode_id: generate_inode_id(),
65                 size: 0,
66                 blk_size: 0,
67                 blocks: 0,
68                 atime: TimeSpec::default(),
69                 mtime: TimeSpec::default(),
70                 ctime: TimeSpec::default(),
71                 file_type: FileType::KvmDevice, // 文件夹,block设备,char设备
72                 mode: filesystem::vfs::syscall::ModeType::S_IALLUGO,
73                 nlinks: 1,
74                 uid: 0,
75                 gid: 0,
76                 raw_dev: make_rawdev(1, 4), // 这里用来作为device number
77             },
78             // fdata: InodeInfo {
79             //     kvm: kvm,
80             // },
81         };
82 
83         let result = Arc::new(LockedVmInode(SpinLock::new(inode)));
84         result.0.lock().self_ref = Arc::downgrade(&result);
85 
86         return result;
87     }
88 }
89 
90 impl IndexNode for LockedVmInode {
91     fn as_any_ref(&self) -> &dyn core::any::Any {
92         self
93     }
94 
95     fn open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
96         kdebug!("file private data:{:?}", _data);
97         return Ok(());
98     }
99 
100     fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> {
101         return Ok(());
102     }
103 
104     fn metadata(&self) -> Result<Metadata, SystemError> {
105         return Ok(self.0.lock().metadata.clone());
106     }
107 
108     fn fs(&self) -> Arc<dyn FileSystem> {
109         return self.0.lock().fs.upgrade().unwrap();
110     }
111 
112     fn list(&self) -> Result<Vec<String>, SystemError> {
113         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
114     }
115 
116     fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> {
117         let mut inode = self.0.lock();
118         inode.metadata.atime = metadata.atime;
119         inode.metadata.mtime = metadata.mtime;
120         inode.metadata.ctime = metadata.ctime;
121         inode.metadata.mode = metadata.mode;
122         inode.metadata.uid = metadata.uid;
123         inode.metadata.gid = metadata.gid;
124 
125         return Ok(());
126     }
127 
128     /// @brief io control接口
129     ///
130     /// @param cmd 命令
131     /// @param data 数据
132     ///
133     /// @return 成功:Ok()
134     ///         失败:Err(错误码)
135     fn ioctl(&self, cmd: u32, data: usize) -> Result<usize, SystemError> {
136         match cmd {
137             0xdeadbeef => {
138                 kdebug!("kvm_vm ioctl");
139                 Ok(0)
140             }
141             KVM_CREATE_VCPU => {
142                 kdebug!("kvm_vcpu ioctl KVM_CREATE_VCPU");
143                 kvm_vm_ioctl_create_vcpu(data as u32)
144             }
145             KVM_SET_USER_MEMORY_REGION => {
146                 kdebug!("kvm_vcpu ioctl KVM_SET_USER_MEMORY_REGION data={:x}", data);
147                 let mut kvm_userspace_mem = KvmUserspaceMemoryRegion::default(); // = unsafe { (data as *const KvmUserspaceMemoryRegion).as_ref().unwrap() };
148                 unsafe {
149                     copy_from_user(
150                         core::slice::from_raw_parts_mut(
151                             (&mut kvm_userspace_mem as *mut _) as *mut u8,
152                             core::mem::size_of::<KvmUserspaceMemoryRegion>(),
153                         ),
154                         VirtAddr::new(data),
155                     )?;
156                 }
157                 kdebug!(
158                     "slot={}, flag={}, memory_size={:x}, guest_phys_addr={}, userspace_addr={}",
159                     kvm_userspace_mem.slot,
160                     kvm_userspace_mem.flags,
161                     kvm_userspace_mem.memory_size,
162                     kvm_userspace_mem.guest_phys_addr, // starting at physical address guest_phys_addr (from the guest’s perspective)
163                     kvm_userspace_mem.userspace_addr // using memory at linear address userspace_addr (from the host’s perspective)
164                 );
165 
166                 let mut current_vm = vm(0).unwrap();
167                 current_vm.set_user_memory_region(&kvm_userspace_mem)?;
168                 update_vm(0, current_vm);
169                 Ok(0)
170             }
171             KVM_GET_DIRTY_LOG | KVM_IRQFD | KVM_IOEVENTFD | KVM_IRQ_LINE_STATUS => {
172                 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
173             }
174             _ => {
175                 kdebug!("kvm_vm ioctl");
176                 Ok(usize::MAX)
177             }
178         }
179     }
180     /// 读设备 - 应该调用设备的函数读写,而不是通过文件系统读写
181     fn read_at(
182         &self,
183         _offset: usize,
184         _len: usize,
185         _buf: &mut [u8],
186         _data: &mut FilePrivateData,
187     ) -> Result<usize, SystemError> {
188         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
189     }
190 
191     /// 写设备 - 应该调用设备的函数读写,而不是通过文件系统读写
192     fn write_at(
193         &self,
194         _offset: usize,
195         _len: usize,
196         _buf: &[u8],
197         _data: &mut FilePrivateData,
198     ) -> Result<usize, SystemError> {
199         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
200     }
201 }
202 
203 fn kvm_vm_ioctl_create_vcpu(id: u32) -> Result<usize, SystemError> {
204     let vcpu = KVMArch::kvm_arch_vcpu_create(id).unwrap();
205     KVMArch::kvm_arch_vcpu_setup(vcpu.as_ref())?;
206 
207     let mut current_vm = vm(0).unwrap();
208     current_vm.vcpu.push(vcpu);
209     current_vm.nr_vcpus += 1;
210     update_vm(0, current_vm);
211 
212     let vcpu_inode = LockedVcpuInode::new();
213     let file: File = File::new(vcpu_inode, FileMode::O_RDWR)?;
214     let r = ProcessManager::current_pcb()
215         .fd_table()
216         .write()
217         .alloc_fd(file, None)
218         .map(|fd| fd as usize);
219     return r;
220 }
221