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