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