xref: /DragonOS/kernel/src/virt/kvm/vm_dev.rs (revision fbe6becd6dd3cd72643707e0088f20364ac1b166)
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, PollStatus,
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     fn poll(&self) -> Result<PollStatus, SystemError> {
129         return Ok(PollStatus::READ | PollStatus::WRITE);
130     }
131 
132     /// @brief io control接口
133     ///
134     /// @param cmd 命令
135     /// @param data 数据
136     ///
137     /// @return 成功:Ok()
138     ///         失败:Err(错误码)
139     fn ioctl(&self, cmd: u32, data: usize) -> Result<usize, SystemError> {
140         match cmd {
141             0xdeadbeef => {
142                 kdebug!("kvm_vm ioctl");
143                 Ok(0)
144             }
145             KVM_CREATE_VCPU => {
146                 kdebug!("kvm_vcpu ioctl KVM_CREATE_VCPU");
147                 kvm_vm_ioctl_create_vcpu(data as u32)
148             }
149             KVM_SET_USER_MEMORY_REGION => {
150                 kdebug!("kvm_vcpu ioctl KVM_SET_USER_MEMORY_REGION data={:x}", data);
151                 let mut kvm_userspace_mem = KvmUserspaceMemoryRegion::default(); // = unsafe { (data as *const KvmUserspaceMemoryRegion).as_ref().unwrap() };
152                 unsafe {
153                     copy_from_user(
154                         core::slice::from_raw_parts_mut(
155                             (&mut kvm_userspace_mem as *mut _) as *mut u8,
156                             core::mem::size_of::<KvmUserspaceMemoryRegion>(),
157                         ),
158                         VirtAddr::new(data),
159                     )?;
160                 }
161                 kdebug!(
162                     "slot={}, flag={}, memory_size={:x}, guest_phys_addr={}, userspace_addr={}",
163                     kvm_userspace_mem.slot,
164                     kvm_userspace_mem.flags,
165                     kvm_userspace_mem.memory_size,
166                     kvm_userspace_mem.guest_phys_addr, // starting at physical address guest_phys_addr (from the guest’s perspective)
167                     kvm_userspace_mem.userspace_addr // using memory at linear address userspace_addr (from the host’s perspective)
168                 );
169 
170                 let mut current_vm = vm(0).unwrap();
171                 current_vm.set_user_memory_region(&kvm_userspace_mem)?;
172                 update_vm(0, current_vm);
173                 Ok(0)
174             }
175             KVM_GET_DIRTY_LOG | KVM_IRQFD | KVM_IOEVENTFD | KVM_IRQ_LINE_STATUS => {
176                 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
177             }
178             _ => {
179                 kdebug!("kvm_vm ioctl");
180                 Ok(usize::MAX)
181             }
182         }
183     }
184     /// 读设备 - 应该调用设备的函数读写,而不是通过文件系统读写
185     fn read_at(
186         &self,
187         _offset: usize,
188         _len: usize,
189         _buf: &mut [u8],
190         _data: &mut FilePrivateData,
191     ) -> Result<usize, SystemError> {
192         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
193     }
194 
195     /// 写设备 - 应该调用设备的函数读写,而不是通过文件系统读写
196     fn write_at(
197         &self,
198         _offset: usize,
199         _len: usize,
200         _buf: &[u8],
201         _data: &mut FilePrivateData,
202     ) -> Result<usize, SystemError> {
203         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
204     }
205 }
206 
207 fn kvm_vm_ioctl_create_vcpu(id: u32) -> Result<usize, SystemError> {
208     let vcpu = KVMArch::kvm_arch_vcpu_create(id).unwrap();
209     KVMArch::kvm_arch_vcpu_setup(vcpu.as_ref())?;
210 
211     let mut current_vm = vm(0).unwrap();
212     current_vm.vcpu.push(vcpu);
213     current_vm.nr_vcpus += 1;
214     update_vm(0, current_vm);
215 
216     let vcpu_inode = LockedVcpuInode::new();
217     let file: File = File::new(vcpu_inode, FileMode::O_RDWR)?;
218     let r = ProcessManager::current_pcb()
219         .fd_table()
220         .write()
221         .alloc_fd(file, None)
222         .map(|fd| fd as usize);
223     return r;
224 }
225