xref: /DragonOS/kernel/src/driver/video/fbdev/base/fbmem.rs (revision 28fe4ad2a0b0d8b5abf1f0cb402b1c3204b42242)
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查找帧缓冲区
find_fb_by_id(&self, id: FbId) -> Result<Option<Arc<dyn FrameBuffer>>, SystemError>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 
generate_fb_id(&self) -> Option<FbId>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";
new(fb: Weak<dyn FrameBuffer>, id: FbId) -> Arc<Self>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                 kobject_common: KObjectCommonData::default(),
222                 device_common: DeviceCommonData::default(),
223                 fb_id: id,
224                 device_inode_fs: None,
225                 devfs_metadata: Metadata::new(
226                     FileType::FramebufferDevice,
227                     ModeType::from_bits_truncate(0o666),
228                 ),
229             }),
230             kobj_state: LockedKObjectState::new(None),
231         });
232 
233         let mut inner_guard = r.inner.lock();
234 
235         inner_guard.devfs_metadata.raw_dev = r.do_device_number(&inner_guard);
236         drop(inner_guard);
237 
238         return r;
239     }
240 
framebuffer(&self) -> Option<Arc<dyn FrameBuffer>>241     pub fn framebuffer(&self) -> Option<Arc<dyn FrameBuffer>> {
242         self.inner.lock().fb.upgrade()
243     }
244 
245     /// 获取设备号
device_number(&self) -> DeviceNumber246     pub fn device_number(&self) -> DeviceNumber {
247         let inner_guard = self.inner.lock();
248         self.do_device_number(&inner_guard)
249     }
250 
do_device_number(&self, inner_guard: &SpinLockGuard<'_, InnerFbDevice>) -> DeviceNumber251     fn do_device_number(&self, inner_guard: &SpinLockGuard<'_, InnerFbDevice>) -> DeviceNumber {
252         DeviceNumber::new(Major::FB_MAJOR, inner_guard.fb_id.data())
253     }
254 
inner(&self) -> SpinLockGuard<InnerFbDevice>255     fn inner(&self) -> SpinLockGuard<InnerFbDevice> {
256         self.inner.lock()
257     }
258 }
259 
260 #[derive(Debug)]
261 struct InnerFbDevice {
262     fb: Weak<dyn FrameBuffer>,
263     kobject_common: KObjectCommonData,
264     device_common: DeviceCommonData,
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 {
as_any_ref(&self) -> &dyn core::any::Any274     fn as_any_ref(&self) -> &dyn core::any::Any {
275         self
276     }
277 
set_inode(&self, inode: Option<Arc<KernFSInode>>)278     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
279         self.inner().kobject_common.kern_inode = inode;
280     }
281 
inode(&self) -> Option<Arc<KernFSInode>>282     fn inode(&self) -> Option<Arc<KernFSInode>> {
283         self.inner().kobject_common.kern_inode.clone()
284     }
285 
parent(&self) -> Option<Weak<dyn KObject>>286     fn parent(&self) -> Option<Weak<dyn KObject>> {
287         self.inner().kobject_common.parent.clone()
288     }
289 
set_parent(&self, parent: Option<Weak<dyn KObject>>)290     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
291         self.inner().kobject_common.parent = parent;
292     }
293 
kset(&self) -> Option<Arc<KSet>>294     fn kset(&self) -> Option<Arc<KSet>> {
295         self.inner().kobject_common.kset.clone()
296     }
297 
set_kset(&self, kset: Option<Arc<KSet>>)298     fn set_kset(&self, kset: Option<Arc<KSet>>) {
299         self.inner().kobject_common.kset = kset;
300     }
301 
kobj_type(&self) -> Option<&'static dyn KObjType>302     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
303         self.inner().kobject_common.kobj_type
304     }
305 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)306     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
307         self.inner().kobject_common.kobj_type = ktype;
308     }
309 
name(&self) -> String310     fn name(&self) -> String {
311         format!("{}{}", Self::BASENAME, self.inner.lock().fb_id.data())
312     }
313 
set_name(&self, _name: String)314     fn set_name(&self, _name: String) {
315         // do nothing
316     }
317 
kobj_state(&self) -> RwLockReadGuard<KObjectState>318     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
319         self.kobj_state.read()
320     }
321 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>322     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
323         self.kobj_state.write()
324     }
325 
set_kobj_state(&self, state: KObjectState)326     fn set_kobj_state(&self, state: KObjectState) {
327         *self.kobj_state.write() = state;
328     }
329 }
330 
331 impl Device for FbDevice {
dev_type(&self) -> DeviceType332     fn dev_type(&self) -> DeviceType {
333         DeviceType::Char
334     }
335 
id_table(&self) -> IdTable336     fn id_table(&self) -> IdTable {
337         IdTable::new(Self::BASENAME.to_string(), Some(self.device_number()))
338     }
339 
set_bus(&self, _bus: Option<Weak<dyn Bus>>)340     fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
341         todo!()
342     }
343 
class(&self) -> Option<Arc<dyn Class>>344     fn class(&self) -> Option<Arc<dyn Class>> {
345         sys_class_graphics_instance().map(|ins| ins.clone() as Arc<dyn Class>)
346     }
set_class(&self, _class: Option<Weak<dyn Class>>)347     fn set_class(&self, _class: Option<Weak<dyn Class>>) {
348         // do nothing
349     }
350 
driver(&self) -> Option<Arc<dyn Driver>>351     fn driver(&self) -> Option<Arc<dyn Driver>> {
352         None
353     }
354 
set_driver(&self, _driver: Option<Weak<dyn Driver>>)355     fn set_driver(&self, _driver: Option<Weak<dyn Driver>>) {
356         // do nothing
357     }
358 
is_dead(&self) -> bool359     fn is_dead(&self) -> bool {
360         false
361     }
362 
can_match(&self) -> bool363     fn can_match(&self) -> bool {
364         false
365     }
366 
set_can_match(&self, _can_match: bool)367     fn set_can_match(&self, _can_match: bool) {
368         // do nothing
369     }
370 
state_synced(&self) -> bool371     fn state_synced(&self) -> bool {
372         true
373     }
374 
attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]>375     fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
376         Some(&[&FbDeviceAttrGroup])
377     }
378 
dev_parent(&self) -> Option<Weak<dyn Device>>379     fn dev_parent(&self) -> Option<Weak<dyn Device>> {
380         self.inner().device_common.get_parent_weak_or_clear()
381     }
382 
set_dev_parent(&self, dev_parent: Option<Weak<dyn Device>>)383     fn set_dev_parent(&self, dev_parent: Option<Weak<dyn Device>>) {
384         self.inner().device_common.parent = dev_parent;
385     }
386 }
387 
388 impl DeviceINode for FbDevice {
set_fs(&self, fs: Weak<DevFS>)389     fn set_fs(&self, fs: Weak<DevFS>) {
390         self.inner.lock().device_inode_fs = Some(fs);
391     }
392 }
393 
394 impl IndexNode for FbDevice {
open( &self, _data: SpinLockGuard<FilePrivateData>, _mode: &FileMode, ) -> Result<(), SystemError>395     fn open(
396         &self,
397         _data: SpinLockGuard<FilePrivateData>,
398         _mode: &FileMode,
399     ) -> Result<(), SystemError> {
400         Ok(())
401     }
402 
close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError>403     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
404         Ok(())
405     }
read_at( &self, offset: usize, len: usize, buf: &mut [u8], _data: SpinLockGuard<FilePrivateData>, ) -> Result<usize, SystemError>406     fn read_at(
407         &self,
408         offset: usize,
409         len: usize,
410         buf: &mut [u8],
411         _data: SpinLockGuard<FilePrivateData>,
412     ) -> Result<usize, SystemError> {
413         let fb = self.inner.lock().fb.upgrade().unwrap();
414         return fb.fb_read(&mut buf[0..len], offset);
415     }
416 
write_at( &self, offset: usize, len: usize, buf: &[u8], _data: SpinLockGuard<FilePrivateData>, ) -> Result<usize, SystemError>417     fn write_at(
418         &self,
419         offset: usize,
420         len: usize,
421         buf: &[u8],
422         _data: SpinLockGuard<FilePrivateData>,
423     ) -> Result<usize, SystemError> {
424         let fb = self.inner.lock().fb.upgrade().unwrap();
425         return fb.fb_write(&buf[0..len], offset);
426     }
427 
fs(&self) -> Arc<dyn FileSystem>428     fn fs(&self) -> Arc<dyn FileSystem> {
429         self.inner
430             .lock()
431             .device_inode_fs
432             .as_ref()
433             .unwrap()
434             .upgrade()
435             .unwrap()
436     }
437 
as_any_ref(&self) -> &dyn core::any::Any438     fn as_any_ref(&self) -> &dyn core::any::Any {
439         self
440     }
441 
list(&self) -> Result<Vec<String>, SystemError>442     fn list(&self) -> Result<Vec<String>, SystemError> {
443         todo!()
444     }
445 
metadata(&self) -> Result<Metadata, SystemError>446     fn metadata(&self) -> Result<Metadata, SystemError> {
447         Ok(self.inner.lock().devfs_metadata.clone())
448     }
449 
resize(&self, _len: usize) -> Result<(), SystemError>450     fn resize(&self, _len: usize) -> Result<(), SystemError> {
451         return Ok(());
452     }
453 }
454