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