1 use core::intrinsics::unlikely; 2 3 use alloc::{ 4 string::{String, ToString}, 5 sync::{Arc, Weak}, 6 vec::Vec, 7 }; 8 9 use system_error::SystemError; 10 use unified_init::macros::unified_init; 11 12 use crate::{ 13 driver::base::{ 14 class::{class_manager, Class}, 15 device::{ 16 bus::Bus, 17 device_manager, 18 device_number::{DeviceNumber, Major}, 19 driver::Driver, 20 sys_dev_char_kset, Device, DeviceType, IdTable, 21 }, 22 kobject::{KObjType, KObject, KObjectState, LockedKObjectState}, 23 kset::KSet, 24 subsys::SubSysPrivate, 25 }, 26 filesystem::{ 27 devfs::{devfs_register, DevFS, DeviceINode}, 28 kernfs::KernFSInode, 29 sysfs::AttributeGroup, 30 vfs::{ 31 file::FileMode, syscall::ModeType, FilePrivateData, FileSystem, FileType, IndexNode, 32 Metadata, 33 }, 34 }, 35 init::initcall::INITCALL_SUBSYS, 36 libs::{ 37 rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}, 38 spinlock::{SpinLock, SpinLockGuard}, 39 }, 40 }; 41 42 use super::{fbcon::fb_console_init, fbsysfs::FbDeviceAttrGroup, FbId, FrameBuffer}; 43 44 /// `/sys/class/graphics` 的 class 实例 45 static mut CLASS_GRAPHICS_INSTANCE: Option<Arc<GraphicsClass>> = None; 46 47 lazy_static! { 48 /// 帧缓冲区管理器 49 static ref FRAME_BUFFER_MANAGER: FrameBufferManager = FrameBufferManager::new(); 50 } 51 52 /// 获取 `/sys/class/graphics` 的 class 实例 53 #[inline(always)] 54 #[allow(dead_code)] 55 pub fn sys_class_graphics_instance() -> Option<&'static Arc<GraphicsClass>> { 56 unsafe { CLASS_GRAPHICS_INSTANCE.as_ref() } 57 } 58 59 #[inline(always)] 60 pub fn frame_buffer_manager() -> &'static FrameBufferManager { 61 &FRAME_BUFFER_MANAGER 62 } 63 64 /// 初始化帧缓冲区子系统 65 #[unified_init(INITCALL_SUBSYS)] 66 pub fn fbmem_init() -> Result<(), SystemError> { 67 let graphics_class = GraphicsClass::new(); 68 class_manager().class_register(&(graphics_class.clone() as Arc<dyn Class>))?; 69 70 unsafe { 71 CLASS_GRAPHICS_INSTANCE = Some(graphics_class); 72 } 73 74 fb_console_init()?; 75 return Ok(()); 76 } 77 78 /// `/sys/class/graphics` 类 79 #[derive(Debug)] 80 pub struct GraphicsClass { 81 subsystem: SubSysPrivate, 82 } 83 84 impl GraphicsClass { 85 const NAME: &'static str = "graphics"; 86 pub fn new() -> Arc<Self> { 87 let r = Self { 88 subsystem: SubSysPrivate::new(Self::NAME.to_string(), None, None, &[]), 89 }; 90 let r = Arc::new(r); 91 r.subsystem() 92 .set_class(Some(Arc::downgrade(&r) as Weak<dyn Class>)); 93 94 return r; 95 } 96 } 97 98 impl Class for GraphicsClass { 99 fn name(&self) -> &'static str { 100 return Self::NAME; 101 } 102 103 fn dev_kobj(&self) -> Option<Arc<dyn KObject>> { 104 Some(sys_dev_char_kset() as Arc<dyn KObject>) 105 } 106 107 fn set_dev_kobj(&self, _kobj: Arc<dyn KObject>) { 108 unimplemented!("GraphicsClass::set_dev_kobj"); 109 } 110 111 fn subsystem(&self) -> &SubSysPrivate { 112 return &self.subsystem; 113 } 114 } 115 116 /// 帧缓冲区管理器 117 #[derive(Debug)] 118 pub struct FrameBufferManager { 119 inner: RwLock<InnerFrameBufferManager>, 120 } 121 122 #[derive(Debug)] 123 struct InnerFrameBufferManager { 124 /// 已经注册的帧缓冲区 125 registered_fbs: [Option<Arc<dyn FrameBuffer>>; FrameBufferManager::FB_MAX], 126 } 127 128 impl FrameBufferManager { 129 pub const FB_MAX: usize = 32; 130 pub fn new() -> Self { 131 Self { 132 inner: RwLock::new(InnerFrameBufferManager { 133 registered_fbs: Default::default(), 134 }), 135 } 136 } 137 138 /// 注册一个帧缓冲区 139 /// 140 /// # 参数 141 /// 142 /// - fb: 帧缓冲区 143 pub fn register_fb(&self, fb: Arc<dyn FrameBuffer>) -> Result<FbId, SystemError> { 144 let id = self.generate_fb_id().expect("no more fb id"); 145 fb.set_fb_id(id); 146 let fb_device = FbDevice::new(Arc::downgrade(&fb) as Weak<dyn FrameBuffer>, id); 147 device_manager().device_default_initialize(&(fb_device.clone() as Arc<dyn Device>)); 148 fb_device.set_parent(Some(Arc::downgrade(&(fb.clone() as Arc<dyn KObject>)))); 149 150 fb.set_fb_device(Some(fb_device.clone())); 151 152 device_manager().add_device(fb_device.clone() as Arc<dyn Device>)?; 153 // 添加到devfs 154 devfs_register(&fb_device.name(), fb_device.clone()).map_err(|e| { 155 kerror!( 156 "register fb device '{}' to devfs failed: {:?}", 157 fb_device.name(), 158 e 159 ); 160 device_manager().remove(&(fb_device.clone() as Arc<dyn Device>)); 161 e 162 })?; 163 164 // todo: 从Modedb中获取信息 165 // 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/video/fbdev/core/fbmem.c#1584 166 167 let mut inner = self.inner.write(); 168 inner.registered_fbs[id.data() as usize] = Some(fb.clone() as Arc<dyn FrameBuffer>); 169 170 // todo: 把fb跟fbcon关联起来 171 return Ok(id); 172 } 173 174 /// 注销一个帧缓冲区 175 /// 176 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/video/fbdev/core/fbmem.c#1726 177 #[allow(dead_code)] 178 pub fn unregister_fb(&self, _fb: Arc<dyn FrameBuffer>) -> Result<(), SystemError> { 179 todo!("unregister_fb") 180 } 181 182 /// 根据id查找帧缓冲区 183 pub fn find_fb_by_id(&self, id: FbId) -> Result<Option<Arc<dyn FrameBuffer>>, SystemError> { 184 if unlikely(!id.is_valid()) { 185 return Err(SystemError::EINVAL); 186 } 187 188 let inner = self.inner.read(); 189 return Ok(inner.registered_fbs[id.data() as usize].clone()); 190 } 191 192 fn generate_fb_id(&self) -> Option<FbId> { 193 for i in 0..Self::FB_MAX { 194 if self.inner.read().registered_fbs[i].is_none() { 195 return Some(FbId::new(i as u32)); 196 } 197 } 198 return None; 199 } 200 } 201 202 /// 抽象的帧缓冲区设备 203 /// 204 /// 对应于`/sys/class/graphics/fb(x)`目录下的设备, 其中`(x)`为帧缓冲区的id 205 /// 206 /// 该设备的父设备为真实的帧缓冲区设备 207 #[derive(Debug)] 208 #[cast_to([sync] Device)] 209 pub struct FbDevice { 210 inner: SpinLock<InnerFbDevice>, 211 kobj_state: LockedKObjectState, 212 } 213 214 impl FbDevice { 215 pub const BASENAME: &'static str = "fb"; 216 fn new(fb: Weak<dyn FrameBuffer>, id: FbId) -> Arc<Self> { 217 let r = Arc::new(Self { 218 inner: SpinLock::new(InnerFbDevice { 219 fb, 220 kern_inode: None, 221 parent: None, 222 kset: None, 223 ktype: None, 224 fb_id: id, 225 device_inode_fs: None, 226 devfs_metadata: Metadata::new( 227 FileType::FramebufferDevice, 228 ModeType::from_bits_truncate(0o666), 229 ), 230 }), 231 kobj_state: LockedKObjectState::new(None), 232 }); 233 234 let mut inner_guard = r.inner.lock(); 235 236 inner_guard.devfs_metadata.raw_dev = r.do_device_number(&inner_guard); 237 drop(inner_guard); 238 239 return r; 240 } 241 242 pub fn framebuffer(&self) -> Option<Arc<dyn FrameBuffer>> { 243 self.inner.lock().fb.upgrade() 244 } 245 246 /// 获取设备号 247 pub fn device_number(&self) -> DeviceNumber { 248 let inner_guard = self.inner.lock(); 249 self.do_device_number(&inner_guard) 250 } 251 252 fn do_device_number(&self, inner_guard: &SpinLockGuard<'_, InnerFbDevice>) -> DeviceNumber { 253 DeviceNumber::new(Major::FB_MAJOR, inner_guard.fb_id.data()) 254 } 255 } 256 257 #[derive(Debug)] 258 struct InnerFbDevice { 259 fb: Weak<dyn FrameBuffer>, 260 kern_inode: Option<Arc<KernFSInode>>, 261 parent: Option<Weak<dyn KObject>>, 262 kset: Option<Arc<KSet>>, 263 ktype: Option<&'static dyn KObjType>, 264 /// 帧缓冲区id 265 fb_id: FbId, 266 267 /// device inode要求的字段 268 device_inode_fs: Option<Weak<DevFS>>, 269 devfs_metadata: Metadata, 270 } 271 272 impl KObject for FbDevice { 273 fn as_any_ref(&self) -> &dyn core::any::Any { 274 self 275 } 276 277 fn set_inode(&self, inode: Option<Arc<KernFSInode>>) { 278 self.inner.lock().kern_inode = inode; 279 } 280 281 fn inode(&self) -> Option<Arc<KernFSInode>> { 282 self.inner.lock().kern_inode.clone() 283 } 284 285 fn parent(&self) -> Option<Weak<dyn KObject>> { 286 self.inner.lock().parent.clone() 287 } 288 289 fn set_parent(&self, parent: Option<Weak<dyn KObject>>) { 290 self.inner.lock().parent = parent; 291 } 292 293 fn kset(&self) -> Option<Arc<KSet>> { 294 self.inner.lock().kset.clone() 295 } 296 297 fn set_kset(&self, kset: Option<Arc<KSet>>) { 298 self.inner.lock().kset = kset; 299 } 300 301 fn kobj_type(&self) -> Option<&'static dyn KObjType> { 302 self.inner.lock().ktype 303 } 304 305 fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) { 306 self.inner.lock().ktype = ktype; 307 } 308 309 fn name(&self) -> String { 310 format!("{}{}", Self::BASENAME, self.inner.lock().fb_id.data()) 311 } 312 313 fn set_name(&self, _name: String) { 314 // do nothing 315 } 316 317 fn kobj_state(&self) -> RwLockReadGuard<KObjectState> { 318 self.kobj_state.read() 319 } 320 321 fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> { 322 self.kobj_state.write() 323 } 324 325 fn set_kobj_state(&self, state: KObjectState) { 326 *self.kobj_state.write() = state; 327 } 328 } 329 330 impl Device for FbDevice { 331 fn dev_type(&self) -> DeviceType { 332 DeviceType::Char 333 } 334 335 fn id_table(&self) -> IdTable { 336 IdTable::new(Self::BASENAME.to_string(), Some(self.device_number())) 337 } 338 339 fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) { 340 todo!() 341 } 342 343 fn class(&self) -> Option<Arc<dyn Class>> { 344 sys_class_graphics_instance().map(|ins| ins.clone() as Arc<dyn Class>) 345 } 346 fn set_class(&self, _class: Option<Weak<dyn Class>>) { 347 // do nothing 348 } 349 350 fn driver(&self) -> Option<Arc<dyn Driver>> { 351 None 352 } 353 354 fn set_driver(&self, _driver: Option<Weak<dyn Driver>>) { 355 // do nothing 356 } 357 358 fn is_dead(&self) -> bool { 359 false 360 } 361 362 fn can_match(&self) -> bool { 363 false 364 } 365 366 fn set_can_match(&self, _can_match: bool) { 367 // do nothing 368 } 369 370 fn state_synced(&self) -> bool { 371 true 372 } 373 374 fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> { 375 Some(&[&FbDeviceAttrGroup]) 376 } 377 } 378 379 impl DeviceINode for FbDevice { 380 fn set_fs(&self, fs: Weak<DevFS>) { 381 self.inner.lock().device_inode_fs = Some(fs); 382 } 383 } 384 385 impl IndexNode for FbDevice { 386 fn open( 387 &self, 388 _data: SpinLockGuard<FilePrivateData>, 389 _mode: &FileMode, 390 ) -> Result<(), SystemError> { 391 Ok(()) 392 } 393 394 fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> { 395 Ok(()) 396 } 397 fn read_at( 398 &self, 399 offset: usize, 400 len: usize, 401 buf: &mut [u8], 402 _data: SpinLockGuard<FilePrivateData>, 403 ) -> Result<usize, SystemError> { 404 let fb = self.inner.lock().fb.upgrade().unwrap(); 405 return fb.fb_read(&mut buf[0..len], offset); 406 } 407 408 fn write_at( 409 &self, 410 offset: usize, 411 len: usize, 412 buf: &[u8], 413 _data: SpinLockGuard<FilePrivateData>, 414 ) -> Result<usize, SystemError> { 415 let fb = self.inner.lock().fb.upgrade().unwrap(); 416 return fb.fb_write(&buf[0..len], offset); 417 } 418 419 fn fs(&self) -> Arc<dyn FileSystem> { 420 self.inner 421 .lock() 422 .device_inode_fs 423 .as_ref() 424 .unwrap() 425 .upgrade() 426 .unwrap() 427 } 428 429 fn as_any_ref(&self) -> &dyn core::any::Any { 430 self 431 } 432 433 fn list(&self) -> Result<Vec<String>, SystemError> { 434 todo!() 435 } 436 437 fn metadata(&self) -> Result<Metadata, SystemError> { 438 Ok(self.inner.lock().devfs_metadata.clone()) 439 } 440 441 fn resize(&self, _len: usize) -> Result<(), SystemError> { 442 return Ok(()); 443 } 444 } 445