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