1 use alloc::{ 2 collections::BTreeMap, 3 string::{String, ToString}, 4 sync::{Arc, Weak}, 5 }; 6 7 use crate::{ 8 filesystem::{ 9 devfs::{devfs_register, DevFS, DeviceINode}, 10 vfs::{file::FileMode, FilePrivateData, FileType, IndexNode, Metadata, ROOT_INODE}, 11 }, 12 kerror, 13 libs::{ 14 lib_ui::textui::{textui_putchar, FontColor}, 15 rwlock::RwLock, 16 }, 17 syscall::SystemError, 18 }; 19 20 use super::{TtyCore, TtyError, TtyFileFlag, TtyFilePrivateData}; 21 22 lazy_static! { 23 /// 所有TTY设备的B树。用于根据名字,找到Arc<TtyDevice> 24 /// TODO: 待设备驱动模型完善,具有类似功能的机制后,删掉这里 25 pub static ref TTY_DEVICES: RwLock<BTreeMap<String, Arc<TtyDevice>>> = RwLock::new(BTreeMap::new()); 26 } 27 28 /// @brief TTY设备 29 #[derive(Debug)] 30 pub struct TtyDevice { 31 /// TTY核心 32 core: TtyCore, 33 /// TTY所属的文件系统 34 fs: RwLock<Weak<DevFS>>, 35 /// TTY设备私有信息 36 private_data: RwLock<TtyDevicePrivateData>, 37 } 38 39 #[derive(Debug)] 40 struct TtyDevicePrivateData { 41 /// TTY设备名(如tty1) 42 name: String, 43 /// TTY设备文件的元数据 44 metadata: Metadata, 45 // TODO: 增加指向输出端口连接的设备的指针 46 } 47 48 impl TtyDevice { 49 pub fn new(name: &str) -> Arc<TtyDevice> { 50 let result = Arc::new(TtyDevice { 51 core: TtyCore::new(), 52 fs: RwLock::new(Weak::default()), 53 private_data: TtyDevicePrivateData::new(name), 54 }); 55 // 默认开启输入回显 56 result.core.enable_echo(); 57 return result; 58 } 59 60 /// @brief 判断文件私有信息是否为TTY文件的私有信息 61 #[inline] 62 fn verify_file_private_data<'a>( 63 &self, 64 private_data: &'a mut FilePrivateData, 65 ) -> Result<&'a mut TtyFilePrivateData, SystemError> { 66 if let FilePrivateData::Tty(t) = private_data { 67 return Ok(t); 68 } 69 return Err(SystemError::EIO); 70 } 71 72 /// @brief 获取TTY设备名 73 #[inline] 74 pub fn name(&self) -> String { 75 return self.private_data.read().name.clone(); 76 } 77 78 /// @brief 检查TTY文件的读写参数是否合法 79 #[inline] 80 pub fn check_rw_param(&self, len: usize, buf: &[u8]) -> Result<(), SystemError> { 81 if len > buf.len() { 82 return Err(SystemError::EINVAL); 83 } 84 return Ok(()); 85 } 86 87 /// @brief 向TTY的输入端口导入数据 88 pub fn input(&self, buf: &[u8]) -> Result<usize, SystemError> { 89 let r: Result<usize, TtyError> = self.core.input(buf, false); 90 if r.is_ok() { 91 return Ok(r.unwrap()); 92 } 93 94 let r = r.unwrap_err(); 95 match r { 96 TtyError::BufferFull(x) => return Ok(x), 97 TtyError::Closed => return Err(SystemError::ENODEV), 98 e => { 99 kerror!("tty error occurred while writing data to its input port, msg={e:?}"); 100 return Err(SystemError::EBUSY); 101 } 102 } 103 } 104 } 105 106 impl DeviceINode for TtyDevice { 107 fn set_fs(&self, fs: alloc::sync::Weak<crate::filesystem::devfs::DevFS>) { 108 *self.fs.write() = fs; 109 } 110 } 111 112 impl IndexNode for TtyDevice { 113 /// @brief 打开TTY设备 114 /// 115 /// @param data 文件私有信息 116 /// @param mode 打开模式 117 /// 118 /// TTY设备通过mode来确定这个文件到底是stdin/stdout/stderr 119 /// - mode的值为O_RDONLY时,表示这个文件是stdin 120 /// - mode的值为O_WRONLY时,表示这个文件是stdout 121 /// - mode的值为O_WRONLY | O_SYNC时,表示这个文件是stderr 122 fn open(&self, data: &mut FilePrivateData, mode: &FileMode) -> Result<(), SystemError> { 123 let mut p = TtyFilePrivateData::default(); 124 125 // 检查打开模式 126 let accmode = mode.accmode(); 127 if accmode == FileMode::O_RDONLY.accmode() { 128 p.flags.insert(TtyFileFlag::STDIN); 129 } else if accmode == FileMode::O_WRONLY.accmode() { 130 if mode.contains(FileMode::O_SYNC) { 131 p.flags.insert(TtyFileFlag::STDERR); 132 } else { 133 p.flags.insert(TtyFileFlag::STDOUT); 134 } 135 } else { 136 return Err(SystemError::EINVAL); 137 } 138 139 // 保存文件私有信息 140 *data = FilePrivateData::Tty(p); 141 return Ok(()); 142 } 143 144 fn read_at( 145 &self, 146 _offset: usize, 147 len: usize, 148 buf: &mut [u8], 149 data: &mut crate::filesystem::vfs::FilePrivateData, 150 ) -> Result<usize, SystemError> { 151 let _data: &mut TtyFilePrivateData = match self.verify_file_private_data(data) { 152 Ok(t) => t, 153 Err(e) => { 154 kerror!("Try to read tty device, but file private data type mismatch!"); 155 return Err(e); 156 } 157 }; 158 self.check_rw_param(len, buf)?; 159 160 // 读取stdin队列 161 let r: Result<usize, TtyError> = self.core.read_stdin(&mut buf[0..len], true); 162 if r.is_ok() { 163 return Ok(r.unwrap()); 164 } 165 166 match r.unwrap_err() { 167 TtyError::EOF(n) => { 168 return Ok(n); 169 } 170 171 x => { 172 kerror!("Error occurred when reading tty, msg={x:?}"); 173 return Err(SystemError::ECONNABORTED); 174 } 175 } 176 } 177 178 fn write_at( 179 &self, 180 _offset: usize, 181 len: usize, 182 buf: &[u8], 183 data: &mut crate::filesystem::vfs::FilePrivateData, 184 ) -> Result<usize, SystemError> { 185 let data: &mut TtyFilePrivateData = match self.verify_file_private_data(data) { 186 Ok(t) => t, 187 Err(e) => { 188 kerror!("Try to write tty device, but file private data type mismatch!"); 189 return Err(e); 190 } 191 }; 192 193 self.check_rw_param(len, buf)?; 194 195 // 根据当前文件是stdout还是stderr,选择不同的发送方式 196 let r: Result<usize, TtyError> = if data.flags.contains(TtyFileFlag::STDOUT) { 197 self.core.stdout(&buf[0..len], true) 198 } else if data.flags.contains(TtyFileFlag::STDERR) { 199 self.core.stderr(&buf[0..len], true) 200 } else { 201 return Err(SystemError::EPERM); 202 }; 203 204 if r.is_ok() { 205 self.sync().expect("Failed to sync tty device!"); 206 return Ok(r.unwrap()); 207 } 208 209 let r: TtyError = r.unwrap_err(); 210 kerror!("Error occurred when writing tty deivce. Error msg={r:?}"); 211 return Err(SystemError::EIO); 212 } 213 214 fn poll(&self) -> Result<crate::filesystem::vfs::PollStatus, SystemError> { 215 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 216 } 217 218 fn fs(&self) -> Arc<dyn crate::filesystem::vfs::FileSystem> { 219 return self.fs.read().upgrade().unwrap(); 220 } 221 222 fn as_any_ref(&self) -> &dyn core::any::Any { 223 self 224 } 225 226 fn list(&self) -> Result<alloc::vec::Vec<alloc::string::String>, SystemError> { 227 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 228 } 229 230 fn metadata(&self) -> Result<Metadata, SystemError> { 231 return Ok(self.private_data.read().metadata.clone()); 232 } 233 234 fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> { 235 return Ok(()); 236 } 237 238 fn sync(&self) -> Result<(), SystemError> { 239 // TODO: 引入IO重定向后,需要将输出重定向到对应的设备。 240 // 目前只是简单的输出到屏幕(为了实现的简便) 241 242 loop { 243 let mut buf = [0u8; 512]; 244 let r: Result<usize, TtyError> = self.core.output(&mut buf[0..511], false); 245 let len; 246 match r { 247 Ok(x) => { 248 len = x; 249 } 250 Err(TtyError::EOF(x)) | Err(TtyError::BufferEmpty(x)) => { 251 len = x; 252 } 253 _ => return Err(SystemError::EIO), 254 } 255 256 if len == 0 { 257 break; 258 } 259 // 输出到屏幕 260 261 for x in buf { 262 textui_putchar(x as char, FontColor::WHITE, FontColor::BLACK).ok(); 263 } 264 } 265 return Ok(()); 266 } 267 } 268 269 impl TtyDevicePrivateData { 270 pub fn new(name: &str) -> RwLock<Self> { 271 let mut metadata = Metadata::new(FileType::CharDevice, 0o755); 272 metadata.size = TtyCore::STDIN_BUF_SIZE as i64; 273 return RwLock::new(TtyDevicePrivateData { 274 name: name.to_string(), 275 metadata, 276 }); 277 } 278 } 279 280 /// @brief 导出到C的tty初始化函数 281 #[no_mangle] 282 pub extern "C" fn rs_tty_init() -> i32 { 283 let r = tty_init(); 284 if r.is_ok() { 285 return 0; 286 } else { 287 return r.unwrap_err().to_posix_errno(); 288 } 289 } 290 291 /// @brief 初始化TTY设备 292 pub fn tty_init() -> Result<(), SystemError> { 293 let tty: Arc<TtyDevice> = TtyDevice::new("tty0"); 294 let devfs_root_inode = ROOT_INODE().lookup("/dev"); 295 if devfs_root_inode.is_err() { 296 return Err(devfs_root_inode.unwrap_err()); 297 } 298 // 当前关闭键盘输入回显 299 // TODO: 完善Termios之后, 改为默认开启键盘输入回显. 300 tty.core.disable_echo(); 301 let guard = TTY_DEVICES.upgradeable_read(); 302 303 // 如果已经存在了这个设备 304 if guard.contains_key("tty0") { 305 return Err(SystemError::EEXIST); 306 } 307 308 let mut guard = guard.upgrade(); 309 310 guard.insert("tty0".to_string(), tty.clone()); 311 312 drop(guard); 313 314 let r = devfs_register(&tty.name(), tty); 315 if r.is_err() { 316 return Err(devfs_root_inode.unwrap_err()); 317 } 318 319 return Ok(()); 320 } 321