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, DeviceCommonData, DeviceType, IdTable,
22 },
23 kobject::{KObjType, KObject, KObjectCommonData, 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)]
sys_class_graphics_instance() -> Option<&'static Arc<GraphicsClass>>56 pub fn sys_class_graphics_instance() -> Option<&'static Arc<GraphicsClass>> {
57 unsafe { CLASS_GRAPHICS_INSTANCE.as_ref() }
58 }
59
60 #[inline(always)]
frame_buffer_manager() -> &'static FrameBufferManager61 pub fn frame_buffer_manager() -> &'static FrameBufferManager {
62 &FRAME_BUFFER_MANAGER
63 }
64
65 /// 初始化帧缓冲区子系统
66 #[unified_init(INITCALL_SUBSYS)]
fbmem_init() -> Result<(), SystemError>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";
new() -> Arc<Self>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 {
name(&self) -> &'static str100 fn name(&self) -> &'static str {
101 return Self::NAME;
102 }
103
dev_kobj(&self) -> Option<Arc<dyn KObject>>104 fn dev_kobj(&self) -> Option<Arc<dyn KObject>> {
105 Some(sys_dev_char_kset() as Arc<dyn KObject>)
106 }
107
set_dev_kobj(&self, _kobj: Arc<dyn KObject>)108 fn set_dev_kobj(&self, _kobj: Arc<dyn KObject>) {
109 unimplemented!("GraphicsClass::set_dev_kobj");
110 }
111
subsystem(&self) -> &SubSysPrivate112 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;
new() -> Self131 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: 帧缓冲区
register_fb(&self, fb: Arc<dyn FrameBuffer>) -> Result<FbId, SystemError>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_dev_parent(Some(Arc::downgrade(&(fb.clone() as Arc<dyn Device>))));
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)]
unregister_fb(&self, _fb: Arc<dyn FrameBuffer>) -> Result<(), SystemError>179 pub fn unregister_fb(&self, _fb: Arc<dyn FrameBuffer>) -> Result<(), SystemError> {
180 todo!("unregister_fb")
181 }
182
183 /// 根据id查找帧缓冲区
184 #[allow(dead_code)]
find_fb_by_id(&self, id: FbId) -> Result<Option<Arc<dyn FrameBuffer>>, SystemError>185 pub fn find_fb_by_id(&self, id: FbId) -> Result<Option<Arc<dyn FrameBuffer>>, SystemError> {
186 if unlikely(!id.is_valid()) {
187 return Err(SystemError::EINVAL);
188 }
189
190 let inner = self.inner.read();
191 return Ok(inner.registered_fbs[id.data() as usize].clone());
192 }
193
generate_fb_id(&self) -> Option<FbId>194 fn generate_fb_id(&self) -> Option<FbId> {
195 for i in 0..Self::FB_MAX {
196 if self.inner.read().registered_fbs[i].is_none() {
197 return Some(FbId::new(i as u32));
198 }
199 }
200 return None;
201 }
202 }
203
204 /// 抽象的帧缓冲区设备
205 ///
206 /// 对应于`/sys/class/graphics/fb(x)`目录下的设备, 其中`(x)`为帧缓冲区的id
207 ///
208 /// 该设备的父设备为真实的帧缓冲区设备
209 #[derive(Debug)]
210 #[cast_to([sync] Device)]
211 pub struct FbDevice {
212 inner: SpinLock<InnerFbDevice>,
213 kobj_state: LockedKObjectState,
214 }
215
216 impl FbDevice {
217 pub const BASENAME: &'static str = "fb";
new(fb: Weak<dyn FrameBuffer>, id: FbId) -> Arc<Self>218 fn new(fb: Weak<dyn FrameBuffer>, id: FbId) -> Arc<Self> {
219 let r = Arc::new(Self {
220 inner: SpinLock::new(InnerFbDevice {
221 fb,
222 kobject_common: KObjectCommonData::default(),
223 device_common: DeviceCommonData::default(),
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
framebuffer(&self) -> Option<Arc<dyn FrameBuffer>>242 pub fn framebuffer(&self) -> Option<Arc<dyn FrameBuffer>> {
243 self.inner.lock().fb.upgrade()
244 }
245
246 /// 获取设备号
device_number(&self) -> DeviceNumber247 pub fn device_number(&self) -> DeviceNumber {
248 let inner_guard = self.inner.lock();
249 self.do_device_number(&inner_guard)
250 }
251
do_device_number(&self, inner_guard: &SpinLockGuard<'_, InnerFbDevice>) -> DeviceNumber252 fn do_device_number(&self, inner_guard: &SpinLockGuard<'_, InnerFbDevice>) -> DeviceNumber {
253 DeviceNumber::new(Major::FB_MAJOR, inner_guard.fb_id.data())
254 }
255
inner(&self) -> SpinLockGuard<InnerFbDevice>256 fn inner(&self) -> SpinLockGuard<InnerFbDevice> {
257 self.inner.lock()
258 }
259 }
260
261 #[derive(Debug)]
262 struct InnerFbDevice {
263 fb: Weak<dyn FrameBuffer>,
264 kobject_common: KObjectCommonData,
265 device_common: DeviceCommonData,
266 /// 帧缓冲区id
267 fb_id: FbId,
268
269 /// device inode要求的字段
270 device_inode_fs: Option<Weak<DevFS>>,
271 devfs_metadata: Metadata,
272 }
273
274 impl KObject for FbDevice {
as_any_ref(&self) -> &dyn core::any::Any275 fn as_any_ref(&self) -> &dyn core::any::Any {
276 self
277 }
278
set_inode(&self, inode: Option<Arc<KernFSInode>>)279 fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
280 self.inner().kobject_common.kern_inode = inode;
281 }
282
inode(&self) -> Option<Arc<KernFSInode>>283 fn inode(&self) -> Option<Arc<KernFSInode>> {
284 self.inner().kobject_common.kern_inode.clone()
285 }
286
parent(&self) -> Option<Weak<dyn KObject>>287 fn parent(&self) -> Option<Weak<dyn KObject>> {
288 self.inner().kobject_common.parent.clone()
289 }
290
set_parent(&self, parent: Option<Weak<dyn KObject>>)291 fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
292 self.inner().kobject_common.parent = parent;
293 }
294
kset(&self) -> Option<Arc<KSet>>295 fn kset(&self) -> Option<Arc<KSet>> {
296 self.inner().kobject_common.kset.clone()
297 }
298
set_kset(&self, kset: Option<Arc<KSet>>)299 fn set_kset(&self, kset: Option<Arc<KSet>>) {
300 self.inner().kobject_common.kset = kset;
301 }
302
kobj_type(&self) -> Option<&'static dyn KObjType>303 fn kobj_type(&self) -> Option<&'static dyn KObjType> {
304 self.inner().kobject_common.kobj_type
305 }
306
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)307 fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
308 self.inner().kobject_common.kobj_type = ktype;
309 }
310
name(&self) -> String311 fn name(&self) -> String {
312 format!("{}{}", Self::BASENAME, self.inner.lock().fb_id.data())
313 }
314
set_name(&self, _name: String)315 fn set_name(&self, _name: String) {
316 // do nothing
317 }
318
kobj_state(&self) -> RwLockReadGuard<KObjectState>319 fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
320 self.kobj_state.read()
321 }
322
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>323 fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
324 self.kobj_state.write()
325 }
326
set_kobj_state(&self, state: KObjectState)327 fn set_kobj_state(&self, state: KObjectState) {
328 *self.kobj_state.write() = state;
329 }
330 }
331
332 impl Device for FbDevice {
dev_type(&self) -> DeviceType333 fn dev_type(&self) -> DeviceType {
334 DeviceType::Char
335 }
336
id_table(&self) -> IdTable337 fn id_table(&self) -> IdTable {
338 IdTable::new(Self::BASENAME.to_string(), Some(self.device_number()))
339 }
340
set_bus(&self, _bus: Option<Weak<dyn Bus>>)341 fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
342 todo!()
343 }
344
class(&self) -> Option<Arc<dyn Class>>345 fn class(&self) -> Option<Arc<dyn Class>> {
346 sys_class_graphics_instance().map(|ins| ins.clone() as Arc<dyn Class>)
347 }
set_class(&self, _class: Option<Weak<dyn Class>>)348 fn set_class(&self, _class: Option<Weak<dyn Class>>) {
349 // do nothing
350 }
351
driver(&self) -> Option<Arc<dyn Driver>>352 fn driver(&self) -> Option<Arc<dyn Driver>> {
353 None
354 }
355
set_driver(&self, _driver: Option<Weak<dyn Driver>>)356 fn set_driver(&self, _driver: Option<Weak<dyn Driver>>) {
357 // do nothing
358 }
359
is_dead(&self) -> bool360 fn is_dead(&self) -> bool {
361 false
362 }
363
can_match(&self) -> bool364 fn can_match(&self) -> bool {
365 false
366 }
367
set_can_match(&self, _can_match: bool)368 fn set_can_match(&self, _can_match: bool) {
369 // do nothing
370 }
371
state_synced(&self) -> bool372 fn state_synced(&self) -> bool {
373 true
374 }
375
attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]>376 fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
377 Some(&[&FbDeviceAttrGroup])
378 }
379
dev_parent(&self) -> Option<Weak<dyn Device>>380 fn dev_parent(&self) -> Option<Weak<dyn Device>> {
381 self.inner().device_common.get_parent_weak_or_clear()
382 }
383
set_dev_parent(&self, dev_parent: Option<Weak<dyn Device>>)384 fn set_dev_parent(&self, dev_parent: Option<Weak<dyn Device>>) {
385 self.inner().device_common.parent = dev_parent;
386 }
387 }
388
389 impl DeviceINode for FbDevice {
set_fs(&self, fs: Weak<DevFS>)390 fn set_fs(&self, fs: Weak<DevFS>) {
391 self.inner.lock().device_inode_fs = Some(fs);
392 }
393 }
394
395 impl IndexNode for FbDevice {
open( &self, _data: SpinLockGuard<FilePrivateData>, _mode: &FileMode, ) -> Result<(), SystemError>396 fn open(
397 &self,
398 _data: SpinLockGuard<FilePrivateData>,
399 _mode: &FileMode,
400 ) -> Result<(), SystemError> {
401 Ok(())
402 }
403
close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError>404 fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
405 Ok(())
406 }
read_at( &self, offset: usize, len: usize, buf: &mut [u8], _data: SpinLockGuard<FilePrivateData>, ) -> Result<usize, SystemError>407 fn read_at(
408 &self,
409 offset: usize,
410 len: usize,
411 buf: &mut [u8],
412 _data: SpinLockGuard<FilePrivateData>,
413 ) -> Result<usize, SystemError> {
414 let fb = self.inner.lock().fb.upgrade().unwrap();
415 return fb.fb_read(&mut buf[0..len], offset);
416 }
417
write_at( &self, offset: usize, len: usize, buf: &[u8], _data: SpinLockGuard<FilePrivateData>, ) -> Result<usize, SystemError>418 fn write_at(
419 &self,
420 offset: usize,
421 len: usize,
422 buf: &[u8],
423 _data: SpinLockGuard<FilePrivateData>,
424 ) -> Result<usize, SystemError> {
425 let fb = self.inner.lock().fb.upgrade().unwrap();
426 return fb.fb_write(&buf[0..len], offset);
427 }
428
fs(&self) -> Arc<dyn FileSystem>429 fn fs(&self) -> Arc<dyn FileSystem> {
430 self.inner
431 .lock()
432 .device_inode_fs
433 .as_ref()
434 .unwrap()
435 .upgrade()
436 .unwrap()
437 }
438
as_any_ref(&self) -> &dyn core::any::Any439 fn as_any_ref(&self) -> &dyn core::any::Any {
440 self
441 }
442
list(&self) -> Result<Vec<String>, SystemError>443 fn list(&self) -> Result<Vec<String>, SystemError> {
444 todo!()
445 }
446
metadata(&self) -> Result<Metadata, SystemError>447 fn metadata(&self) -> Result<Metadata, SystemError> {
448 Ok(self.inner.lock().devfs_metadata.clone())
449 }
450
resize(&self, _len: usize) -> Result<(), SystemError>451 fn resize(&self, _len: usize) -> Result<(), SystemError> {
452 return Ok(());
453 }
454 }
455