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