xref: /DragonOS/kernel/src/virt/kvm/kvm_dev.rs (revision 91e9d4ab55ef960f57a1b6287bc523ca4341f67a)
1 use crate::filesystem::devfs::{DevFS, DeviceINode};
2 use crate::filesystem::vfs::{
3     core::generate_inode_id,
4     file::{File, FileMode},
5     make_rawdev, FilePrivateData, FileSystem, FileType, IndexNode, Metadata,
6 };
7 use crate::process::ProcessManager;
8 use crate::{arch::KVMArch, libs::spinlock::SpinLock, time::TimeSpec};
9 use crate::{filesystem, kdebug};
10 // use crate::virt::kvm::{host_stack};
11 use super::push_vm;
12 use crate::virt::kvm::vm_dev::LockedVmInode;
13 use alloc::{
14     string::String,
15     sync::{Arc, Weak},
16     vec::Vec,
17 };
18 use system_error::SystemError;
19 
20 pub const KVM_API_VERSION: u32 = 12;
21 
22 // use crate::virt::kvm::kvm_dev_ioctl_create_vm;
23 /*
24  * ioctls for /dev/kvm fds:
25  */
26 pub const KVM_GET_API_VERSION: u32 = 0x00;
27 pub const KVM_CREATE_VM: u32 = 0x01;
28 pub const KVM_CHECK_EXTENSION: u32 = 0x03;
29 pub const KVM_GET_VCPU_MMAP_SIZE: u32 = 0x04; // Get size for mmap(vcpu_fd) in bytes
30 pub const KVM_TRACE_ENABLE: u32 = 0x05;
31 pub const KVM_TRACE_PAUSE: u32 = 0x06;
32 pub const KVM_TRACE_DISABLE: u32 = 0x07;
33 
34 #[derive(Debug)]
35 pub struct KvmInode {
36     /// uuid 暂时不知道有什么用(x
37     // uuid: Uuid,
38     /// 指向自身的弱引用
39     self_ref: Weak<LockedKvmInode>,
40     /// 指向inode所在的文件系统对象的指针
41     fs: Weak<DevFS>,
42     /// INode 元数据
43     metadata: Metadata,
44 }
45 
46 #[derive(Debug)]
47 pub struct LockedKvmInode(SpinLock<KvmInode>);
48 
49 impl LockedKvmInode {
50     pub fn new() -> Arc<Self> {
51         let inode = KvmInode {
52             self_ref: Weak::default(),
53             fs: Weak::default(),
54             metadata: Metadata {
55                 dev_id: 1,
56                 inode_id: generate_inode_id(),
57                 size: 0,
58                 blk_size: 0,
59                 blocks: 0,
60                 atime: TimeSpec::default(),
61                 mtime: TimeSpec::default(),
62                 ctime: TimeSpec::default(),
63                 file_type: FileType::KvmDevice, // 文件夹,block设备,char设备
64                 mode: filesystem::vfs::syscall::ModeType::S_IALLUGO,
65                 nlinks: 1,
66                 uid: 0,
67                 gid: 0,
68                 raw_dev: make_rawdev(1, 4), // 这里用来作为device number
69             },
70         };
71 
72         let result = Arc::new(LockedKvmInode(SpinLock::new(inode)));
73         result.0.lock().self_ref = Arc::downgrade(&result);
74 
75         return result;
76     }
77 }
78 
79 impl DeviceINode for LockedKvmInode {
80     fn set_fs(&self, fs: Weak<DevFS>) {
81         self.0.lock().fs = fs;
82     }
83 }
84 
85 impl IndexNode for LockedKvmInode {
86     fn as_any_ref(&self) -> &dyn core::any::Any {
87         self
88     }
89 
90     fn open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
91         kdebug!("file private data:{:?}", _data);
92         return Ok(());
93     }
94 
95     fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> {
96         return Ok(());
97     }
98 
99     fn metadata(&self) -> Result<Metadata, SystemError> {
100         return Ok(self.0.lock().metadata.clone());
101     }
102 
103     fn fs(&self) -> Arc<dyn FileSystem> {
104         return self.0.lock().fs.upgrade().unwrap();
105     }
106 
107     fn list(&self) -> Result<Vec<String>, SystemError> {
108         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
109     }
110 
111     fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> {
112         let mut inode = self.0.lock();
113         inode.metadata.atime = metadata.atime;
114         inode.metadata.mtime = metadata.mtime;
115         inode.metadata.ctime = metadata.ctime;
116         inode.metadata.mode = metadata.mode;
117         inode.metadata.uid = metadata.uid;
118         inode.metadata.gid = metadata.gid;
119 
120         return Ok(());
121     }
122 
123     /// @brief io control接口
124     ///
125     /// @param cmd 命令
126     /// @param data 数据
127     ///
128     /// @return 成功:Ok()
129     ///         失败:Err(错误码)
130     fn ioctl(&self, cmd: u32, data: usize) -> Result<usize, SystemError> {
131         match cmd {
132             0xdeadbeef => {
133                 kdebug!("kvm ioctl");
134                 Ok(0)
135             }
136             KVM_GET_API_VERSION => Ok(KVM_API_VERSION as usize),
137             KVM_CREATE_VM => {
138                 kdebug!("kvm KVM_CREATE_VM");
139                 kvm_dev_ioctl_create_vm(data)
140             }
141             KVM_CHECK_EXTENSION
142             | KVM_GET_VCPU_MMAP_SIZE
143             | KVM_TRACE_ENABLE
144             | KVM_TRACE_PAUSE
145             | KVM_TRACE_DISABLE => Err(SystemError::EOPNOTSUPP_OR_ENOTSUP),
146             _ => KVMArch::kvm_arch_dev_ioctl(cmd, data),
147         }
148     }
149     /// 读设备 - 应该调用设备的函数读写,而不是通过文件系统读写
150     fn read_at(
151         &self,
152         _offset: usize,
153         _len: usize,
154         _buf: &mut [u8],
155         _data: &mut FilePrivateData,
156     ) -> Result<usize, SystemError> {
157         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
158     }
159 
160     /// 写设备 - 应该调用设备的函数读写,而不是通过文件系统读写
161     fn write_at(
162         &self,
163         _offset: usize,
164         _len: usize,
165         _buf: &[u8],
166         _data: &mut FilePrivateData,
167     ) -> Result<usize, SystemError> {
168         Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
169     }
170 }
171 
172 #[no_mangle]
173 pub fn kvm_dev_ioctl_create_vm(_vmtype: usize) -> Result<usize, SystemError> {
174     push_vm(0).expect("need a valid vm!");
175 
176     // 创建vm文件,返回文件描述符
177     let vm_inode = LockedVmInode::new();
178     let file: File = File::new(vm_inode, FileMode::O_RDWR)?;
179     let r = ProcessManager::current_pcb()
180         .fd_table()
181         .write()
182         .alloc_fd(file, None)
183         .map(|fd| fd as usize);
184     return r;
185 }
186