xref: /DragonOS/kernel/src/driver/video/fbdev/vesafb.rs (revision 0cb807346cb3c47924538585087d9fc846cf5e6f)
1 use core::{
2     ffi::{c_uint, c_void},
3     mem::MaybeUninit,
4     sync::atomic::AtomicBool,
5 };
6 
7 use alloc::{
8     string::{String, ToString},
9     sync::{Arc, Weak},
10     vec::Vec,
11 };
12 use system_error::SystemError;
13 use unified_init::macros::unified_init;
14 
15 use crate::{
16     arch::MMArch,
17     driver::{
18         base::{
19             class::Class,
20             device::{
21                 bus::Bus, device_manager, driver::Driver, Device, DeviceState, DeviceType, IdTable,
22             },
23             kobject::{KObjType, KObject, KObjectState, LockedKObjectState},
24             kset::KSet,
25             platform::{
26                 platform_device::{platform_device_manager, PlatformDevice},
27                 platform_driver::{platform_driver_manager, PlatformDriver},
28                 CompatibleTable,
29             },
30         },
31         serial::serial8250::send_to_default_serial8250_port,
32         video::fbdev::base::{fbmem::frame_buffer_manager, FbVisual, FRAME_BUFFER_SET},
33     },
34     filesystem::{
35         kernfs::KernFSInode,
36         sysfs::{file::sysfs_emit_str, Attribute, AttributeGroup, SysFSOpsSupport},
37         vfs::syscall::ModeType,
38     },
39     include::bindings::bindings::{
40         multiboot2_get_Framebuffer_info, multiboot2_iter, multiboot_tag_framebuffer_info_t,
41         FRAME_BUFFER_MAPPING_OFFSET,
42     },
43     init::{boot_params, initcall::INITCALL_DEVICE},
44     libs::{
45         align::page_align_up,
46         once::Once,
47         rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
48         spinlock::SpinLock,
49     },
50     mm::{
51         allocator::page_frame::PageFrameCount, no_init::pseudo_map_phys, MemoryManagementArch,
52         PhysAddr, VirtAddr,
53     },
54 };
55 
56 use super::base::{
57     fbmem::FbDevice, BlankMode, BootTimeVideoType, FbAccel, FbActivateFlags, FbId, FbState, FbType,
58     FbVModeFlags, FbVarScreenInfo, FbVideoMode, FixedScreenInfo, FrameBuffer, FrameBufferInfo,
59     FrameBufferInfoData, FrameBufferOps,
60 };
61 
62 /// 当前机器上面是否有vesa帧缓冲区
63 static HAS_VESA_FB: AtomicBool = AtomicBool::new(false);
64 
65 lazy_static! {
66     static ref VESAFB_FIX_INFO: RwLock<FixedScreenInfo> = RwLock::new(FixedScreenInfo {
67         id: FixedScreenInfo::name2id("VESA VGA"),
68         fb_type: FbType::PackedPixels,
69         accel: FbAccel::None,
70         ..Default::default()
71     });
72     static ref VESAFB_DEFINED: RwLock<FbVarScreenInfo> = RwLock::new(FbVarScreenInfo {
73         activate: FbActivateFlags::FB_ACTIVATE_NOW,
74         height: None,
75         width: None,
76         right_margin: 32,
77         upper_margin: 16,
78         lower_margin: 4,
79         vsync_len: 4,
80         vmode: FbVModeFlags::FB_VMODE_NONINTERLACED,
81 
82         ..Default::default()
83     });
84 }
85 
86 #[derive(Debug)]
87 #[cast_to([sync] Device)]
88 #[cast_to([sync] PlatformDevice)]
89 pub struct VesaFb {
90     inner: SpinLock<InnerVesaFb>,
91     kobj_state: LockedKObjectState,
92     fb_data: RwLock<FrameBufferInfoData>,
93 }
94 
95 impl VesaFb {
96     pub const NAME: &'static str = "vesa_vga";
97     pub fn new() -> Self {
98         let mut fb_info_data = FrameBufferInfoData::new();
99         fb_info_data.pesudo_palette.resize(256, 0);
100         return Self {
101             inner: SpinLock::new(InnerVesaFb {
102                 bus: None,
103                 class: None,
104                 driver: None,
105                 kern_inode: None,
106                 parent: None,
107                 kset: None,
108                 kobj_type: None,
109                 device_state: DeviceState::NotInitialized,
110                 pdev_id: 0,
111                 pdev_id_auto: false,
112                 fb_id: FbId::INIT,
113                 fb_device: None,
114                 fb_state: FbState::Suspended,
115             }),
116             kobj_state: LockedKObjectState::new(None),
117             fb_data: RwLock::new(fb_info_data),
118         };
119     }
120 }
121 
122 #[derive(Debug)]
123 struct InnerVesaFb {
124     bus: Option<Weak<dyn Bus>>,
125     class: Option<Weak<dyn Class>>,
126     driver: Option<Weak<dyn Driver>>,
127     kern_inode: Option<Arc<KernFSInode>>,
128     parent: Option<Weak<dyn KObject>>,
129     kset: Option<Arc<KSet>>,
130     kobj_type: Option<&'static dyn KObjType>,
131     device_state: DeviceState,
132     pdev_id: i32,
133     pdev_id_auto: bool,
134     fb_id: FbId,
135     fb_device: Option<Arc<FbDevice>>,
136     fb_state: FbState,
137 }
138 
139 impl FrameBuffer for VesaFb {
140     fn fb_id(&self) -> FbId {
141         self.inner.lock().fb_id
142     }
143 
144     fn set_fb_id(&self, id: FbId) {
145         self.inner.lock().fb_id = id;
146     }
147 }
148 
149 impl PlatformDevice for VesaFb {
150     fn pdev_name(&self) -> &str {
151         Self::NAME
152     }
153 
154     fn set_pdev_id(&self, id: i32) {
155         self.inner.lock().pdev_id = id;
156     }
157 
158     fn set_pdev_id_auto(&self, id_auto: bool) {
159         self.inner.lock().pdev_id_auto = id_auto;
160     }
161 
162     fn compatible_table(&self) -> CompatibleTable {
163         todo!()
164     }
165 
166     fn is_initialized(&self) -> bool {
167         self.inner.lock().device_state == DeviceState::Initialized
168     }
169 
170     fn set_state(&self, set_state: DeviceState) {
171         self.inner.lock().device_state = set_state;
172     }
173 }
174 
175 impl Device for VesaFb {
176     fn dev_type(&self) -> DeviceType {
177         DeviceType::Char
178     }
179 
180     fn id_table(&self) -> IdTable {
181         IdTable::new(self.name(), None)
182     }
183 
184     fn bus(&self) -> Option<Weak<dyn Bus>> {
185         self.inner.lock().bus.clone()
186     }
187 
188     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
189         self.inner.lock().bus = bus;
190     }
191 
192     fn set_class(&self, class: Option<Weak<dyn Class>>) {
193         self.inner.lock().class = class;
194     }
195 
196     fn class(&self) -> Option<Arc<dyn Class>> {
197         let mut guard = self.inner.lock();
198 
199         let r = guard.class.clone()?.upgrade();
200         if r.is_none() {
201             // 为了让弱引用失效
202             guard.class = None;
203         }
204 
205         return r;
206     }
207 
208     fn driver(&self) -> Option<Arc<dyn Driver>> {
209         self.inner.lock().driver.clone()?.upgrade()
210     }
211 
212     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
213         self.inner.lock().driver = driver;
214     }
215 
216     fn is_dead(&self) -> bool {
217         false
218     }
219 
220     fn can_match(&self) -> bool {
221         true
222     }
223 
224     fn set_can_match(&self, _can_match: bool) {}
225 
226     fn state_synced(&self) -> bool {
227         true
228     }
229 }
230 
231 impl KObject for VesaFb {
232     fn as_any_ref(&self) -> &dyn core::any::Any {
233         self
234     }
235 
236     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
237         self.inner.lock().kern_inode = inode;
238     }
239 
240     fn inode(&self) -> Option<Arc<KernFSInode>> {
241         self.inner.lock().kern_inode.clone()
242     }
243 
244     fn parent(&self) -> Option<Weak<dyn KObject>> {
245         self.inner.lock().parent.clone()
246     }
247 
248     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
249         self.inner.lock().parent = parent;
250     }
251 
252     fn kset(&self) -> Option<Arc<KSet>> {
253         self.inner.lock().kset.clone()
254     }
255 
256     fn set_kset(&self, kset: Option<Arc<KSet>>) {
257         self.inner.lock().kset = kset;
258     }
259 
260     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
261         self.inner.lock().kobj_type
262     }
263 
264     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
265         self.inner.lock().kobj_type = ktype;
266     }
267 
268     fn name(&self) -> String {
269         Self::NAME.to_string()
270     }
271 
272     fn set_name(&self, _name: String) {
273         // do nothing
274     }
275 
276     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
277         self.kobj_state.read()
278     }
279 
280     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
281         self.kobj_state.write()
282     }
283 
284     fn set_kobj_state(&self, state: KObjectState) {
285         *self.kobj_state.write() = state;
286     }
287 }
288 
289 impl FrameBufferOps for VesaFb {
290     fn fb_open(&self, _user: bool) {
291         todo!()
292     }
293 
294     fn fb_release(&self, _user: bool) {
295         todo!()
296     }
297 
298     fn fb_set_color_register(
299         &self,
300         regno: u16,
301         mut red: u16,
302         mut green: u16,
303         mut blue: u16,
304     ) -> Result<(), SystemError> {
305         let mut fb_data = self.framebuffer_info_data().write();
306         let var = self.current_fb_var();
307         if regno as usize >= fb_data.pesudo_palette.len() {
308             return Err(SystemError::E2BIG);
309         }
310 
311         if var.bits_per_pixel == 8 {
312             todo!("vesa_setpalette todo");
313         } else if regno < 16 {
314             match var.bits_per_pixel {
315                 16 => {
316                     if var.red.offset == 10 {
317                         // RGB 1:5:5:5
318                         fb_data.pesudo_palette[regno as usize] = ((red as u32 & 0xf800) >> 1)
319                             | ((green as u32 & 0xf800) >> 6)
320                             | ((blue as u32 & 0xf800) >> 11);
321                     } else {
322                         fb_data.pesudo_palette[regno as usize] = (red as u32 & 0xf800)
323                             | ((green as u32 & 0xfc00) >> 5)
324                             | ((blue as u32 & 0xf800) >> 11);
325                     }
326                 }
327                 24 | 32 => {
328                     red >>= 8;
329                     green >>= 8;
330                     blue >>= 8;
331                     fb_data.pesudo_palette[regno as usize] = ((red as u32) << var.red.offset)
332                         | ((green as u32) << var.green.offset)
333                         | ((blue as u32) << var.blue.offset);
334                 }
335                 _ => {}
336             }
337         }
338 
339         Ok(())
340     }
341 
342     fn fb_blank(&self, _blank_mode: BlankMode) -> Result<(), SystemError> {
343         todo!()
344     }
345 
346     fn fb_destroy(&self) {
347         todo!()
348     }
349 
350     fn fb_read(&self, buf: &mut [u8], pos: usize) -> Result<usize, SystemError> {
351         let bp = boot_params().read();
352 
353         let vaddr = bp.screen_info.lfb_virt_base.ok_or(SystemError::ENODEV)?;
354         let size = self.current_fb_fix().smem_len;
355         drop(bp);
356         if pos >= size {
357             return Ok(0);
358         }
359 
360         let pos = pos as i64;
361         let size = size as i64;
362 
363         let len = core::cmp::min(size - pos, buf.len() as i64) as usize;
364 
365         let slice = unsafe { core::slice::from_raw_parts(vaddr.as_ptr::<u8>(), size as usize) };
366         buf[..len].copy_from_slice(&slice[pos as usize..(pos as usize + len)]);
367 
368         return Ok(len);
369     }
370 
371     fn fb_write(&self, buf: &[u8], pos: usize) -> Result<usize, SystemError> {
372         let bp = boot_params().read();
373 
374         let vaddr = bp.screen_info.lfb_virt_base.ok_or(SystemError::ENODEV)?;
375         let size = self.current_fb_fix().smem_len;
376 
377         if pos >= size {
378             return Ok(0);
379         }
380 
381         let pos = pos as i64;
382         let size = size as i64;
383 
384         let len = core::cmp::min(size - pos, buf.len() as i64) as usize;
385 
386         let slice = unsafe { core::slice::from_raw_parts_mut(vaddr.as_ptr::<u8>(), size as usize) };
387         slice[pos as usize..(pos as usize + len)].copy_from_slice(&buf[..len]);
388 
389         return Ok(len);
390     }
391 
392     fn fb_image_blit(&self, image: &super::base::FbImage) {
393         self.generic_imageblit(image);
394     }
395 
396     /// ## 填充矩形
397     fn fb_fillrect(&self, rect: super::base::FillRectData) -> Result<(), SystemError> {
398         // kwarn!("rect {rect:?}");
399 
400         let boot_param = boot_params().read();
401         let screen_base = boot_param
402             .screen_info
403             .lfb_virt_base
404             .ok_or(SystemError::ENODEV)?;
405 
406         let fg = if self.current_fb_fix().visual == FbVisual::TrueColor
407             || self.current_fb_fix().visual == FbVisual::DirectColor
408         {
409             self.fb_data.read().pesudo_palette[rect.color as usize]
410         } else {
411             rect.color
412         };
413 
414         let bpp = self.current_fb_var().bits_per_pixel;
415         // 每行像素数
416         let line_offset = self.current_fb_var().xres;
417         match bpp {
418             32 => {
419                 let base = screen_base.as_ptr::<u32>();
420 
421                 for y in rect.dy..(rect.dy + rect.height) {
422                     for x in rect.dx..(rect.dx + rect.width) {
423                         unsafe { *base.add((y * line_offset + x) as usize) = fg };
424                     }
425                 }
426             }
427             16 => {
428                 let base = screen_base.as_ptr::<u16>();
429 
430                 for y in rect.dy..(rect.dy + rect.height) {
431                     for x in rect.dx..(rect.dx + rect.width) {
432                         unsafe { *base.add((y * line_offset + x) as usize) = 0x0000 };
433                     }
434                 }
435             }
436             24 => {
437                 let base = screen_base.as_ptr::<[u8; 3]>();
438 
439                 for y in rect.dy..(rect.dy + rect.height) {
440                     for x in rect.dx..(rect.dx + rect.width) {
441                         unsafe { *base.add((y * line_offset + x) as usize) = [0, 0, 0] };
442                     }
443                 }
444             }
445             _ => {
446                 send_to_default_serial8250_port(
447                     format!("unsupported bit depth:{}!\n\0", bpp).as_bytes(),
448                 );
449                 todo!()
450             }
451         }
452 
453         Ok(())
454     }
455 
456     #[inline(never)]
457     fn fb_copyarea(&self, data: super::base::CopyAreaData) {
458         let bp = boot_params().read();
459         let base = bp.screen_info.lfb_virt_base.unwrap();
460         let var = self.current_fb_var();
461 
462         // 原区域或者目标区域全在屏幕外,则直接返回
463         if data.sx > var.xres as i32
464             || data.sy > var.yres as i32
465             || data.dx > var.xres as i32
466             || data.dy > var.yres as i32
467             || (data.sx + data.width as i32) < 0
468             || (data.sy + data.height as i32) < 0
469             || (data.dx + data.width as i32) < 0
470             || (data.dy + data.height as i32) < 0
471         {
472             return;
473         }
474 
475         // 求两个矩形可视范围交集
476         let (s_visiable_x, s_w) = if data.sx < 0 {
477             (0, (data.width - ((-data.sx) as u32)).min(var.xres))
478         } else {
479             let w = if data.sx as u32 + data.width > var.xres {
480                 var.xres - data.sx as u32
481             } else {
482                 data.width
483             };
484 
485             (data.sx, w)
486         };
487         let (s_visiable_y, s_h) = if data.sy < 0 {
488             (0, (data.height - ((-data.sy) as u32).min(var.yres)))
489         } else {
490             let h = if data.sy as u32 + data.height > var.yres {
491                 var.yres - data.sy as u32
492             } else {
493                 data.height
494             };
495 
496             (data.sy, h)
497         };
498 
499         let (d_visiable_x, d_w) = if data.dx < 0 {
500             (0, (data.width - ((-data.dx) as u32)).min(var.xres))
501         } else {
502             let w = if data.dx as u32 + data.width > var.xres {
503                 var.xres - data.dx as u32
504             } else {
505                 data.width
506             };
507 
508             (data.dx, w)
509         };
510         let (d_visiable_y, d_h) = if data.dy < 0 {
511             (0, (data.height - ((-data.dy) as u32).min(var.yres)))
512         } else {
513             let h = if data.dy as u32 + data.height > var.yres {
514                 var.yres - data.dy as u32
515             } else {
516                 data.height
517             };
518 
519             (data.dy, h)
520         };
521 
522         // 可视范围无交集
523         if !(d_h + s_h > data.height && s_w + d_w > data.width) {
524             return;
525         }
526 
527         // 可视区域左上角相对于矩形的坐标
528         let s_relative_x = s_visiable_x - data.sx;
529         let s_relative_y = s_visiable_y - data.sy;
530         let d_relative_x = d_visiable_x - data.dx;
531         let d_relative_y = d_visiable_y - data.dy;
532 
533         let visiable_x = s_relative_x.max(d_relative_x);
534         let visiable_y = s_relative_y.max(d_relative_y);
535         let visiable_h = d_h + s_h - data.height;
536         let visiable_w = d_w + s_w - data.width;
537 
538         let s_real_x = (visiable_x + data.sx) as u32;
539         let s_real_y = (visiable_y + data.sy) as u32;
540         let d_real_x = (visiable_x + data.dx) as u32;
541         let d_real_y = (visiable_y + data.dy) as u32;
542 
543         let bytes_per_pixel = var.bits_per_pixel >> 3;
544         let bytes_per_line = var.xres * bytes_per_pixel;
545 
546         let src =
547             base + VirtAddr::new((s_real_y * bytes_per_line + s_real_x * bytes_per_pixel) as usize);
548 
549         let dst =
550             base + VirtAddr::new((d_real_y * bytes_per_line + d_real_x * bytes_per_pixel) as usize);
551 
552         let size = (visiable_h * visiable_w) as usize;
553 
554         match bytes_per_pixel {
555             4 => {
556                 // 32bpp
557                 let mut dst = dst.as_ptr::<u32>();
558                 let mut src = src.as_ptr::<u32>();
559                 let line_offset = var.xres as usize;
560 
561                 if s_real_x > d_real_x {
562                     // 如果src在dst下方,则可以直接拷贝不会出现指针覆盖
563                     unsafe {
564                         for _ in 0..visiable_h {
565                             core::ptr::copy(src, dst, visiable_w as usize);
566                             src = src.add(line_offset);
567                             dst = dst.add(visiable_w as usize);
568                         }
569                     }
570                 } else {
571                     let mut tmp: Vec<u32> = vec![0; size];
572                     let mut tmp_ptr = tmp.as_mut_ptr();
573 
574                     // 这里是一个可以优化的点,现在为了避免指针拷贝时覆盖,统一先拷贝进入buf再拷贝到dst
575                     unsafe {
576                         for _ in 0..visiable_h {
577                             core::ptr::copy(src, tmp_ptr, visiable_w as usize);
578                             src = src.add(line_offset);
579                             tmp_ptr = tmp_ptr.add(visiable_w as usize);
580                         }
581 
582                         tmp_ptr = tmp_ptr.sub(size);
583                         for _ in 0..visiable_h {
584                             core::ptr::copy(tmp_ptr, dst, visiable_w as usize);
585                             dst = dst.add(line_offset);
586                             tmp_ptr = tmp_ptr.add(visiable_w as usize);
587                         }
588                     }
589                 }
590             }
591             2 => {
592                 let mut dst = dst.as_ptr::<u16>();
593                 let mut src = src.as_ptr::<u16>();
594                 let line_offset = var.xres as usize;
595 
596                 if s_real_x > d_real_x {
597                     // 如果src在dst下方,则可以直接拷贝不会出现指针覆盖
598                     unsafe {
599                         for _ in 0..visiable_h {
600                             core::ptr::copy(src, dst, visiable_w as usize);
601                             src = src.add(line_offset);
602                             dst = dst.add(visiable_w as usize);
603                         }
604                     }
605                 } else {
606                     let mut tmp: Vec<u16> = vec![0; size];
607                     let mut tmp_ptr = tmp.as_mut_ptr();
608 
609                     // 这里是一个可以优化的点,现在为了避免指针拷贝时覆盖,统一先拷贝进入buf再拷贝到dst
610                     unsafe {
611                         for _ in 0..visiable_h {
612                             core::ptr::copy(src, tmp_ptr, visiable_w as usize);
613                             src = src.add(line_offset);
614                             tmp_ptr = tmp_ptr.add(visiable_w as usize);
615                         }
616 
617                         tmp_ptr = tmp_ptr.sub(size);
618                         for _ in 0..visiable_h {
619                             core::ptr::copy(tmp_ptr, dst, visiable_w as usize);
620                             dst = dst.add(line_offset);
621                             tmp_ptr = tmp_ptr.add(visiable_w as usize);
622                         }
623                     }
624                 }
625             }
626             3 => {
627                 let mut dst = dst.as_ptr::<[u8; 3]>();
628                 let mut src = src.as_ptr::<[u8; 3]>();
629                 let line_offset = var.xres as usize;
630 
631                 if s_real_x > d_real_x {
632                     // 如果src在dst下方,则可以直接拷贝不会出现指针覆盖
633                     unsafe {
634                         for _ in 0..visiable_h {
635                             core::ptr::copy(src, dst, visiable_w as usize);
636                             src = src.add(line_offset);
637                             dst = dst.add(visiable_w as usize);
638                         }
639                     }
640                 } else {
641                     let mut tmp: Vec<u32> = vec![0; size];
642                     let mut tmp_ptr = tmp.as_mut_ptr() as *mut [u8; 3];
643 
644                     // 这里是一个可以优化的点,现在为了避免指针拷贝时覆盖,统一先拷贝进入buf再拷贝到dst
645                     unsafe {
646                         for _ in 0..visiable_h {
647                             core::ptr::copy(src, tmp_ptr, visiable_w as usize);
648                             src = src.add(line_offset);
649                             tmp_ptr = tmp_ptr.add(visiable_w as usize);
650                         }
651 
652                         tmp_ptr = tmp_ptr.sub(size);
653                         for _ in 0..visiable_h {
654                             core::ptr::copy(tmp_ptr, dst, visiable_w as usize);
655                             dst = dst.add(line_offset);
656                             tmp_ptr = tmp_ptr.add(visiable_w as usize);
657                         }
658                     }
659                 }
660             }
661 
662             _ => {
663                 send_to_default_serial8250_port(
664                     format!("bytes_per_pixel:{}\n\0", bytes_per_pixel).as_bytes(),
665                 );
666                 todo!()
667             }
668         }
669     }
670 }
671 
672 impl FrameBufferInfo for VesaFb {
673     fn fb_device(&self) -> Option<Arc<FbDevice>> {
674         self.inner.lock().fb_device.clone()
675     }
676 
677     fn set_fb_device(&self, device: Option<Arc<FbDevice>>) {
678         self.inner.lock().fb_device = device;
679     }
680 
681     fn screen_size(&self) -> usize {
682         todo!()
683     }
684 
685     fn current_fb_var(&self) -> FbVarScreenInfo {
686         *VESAFB_DEFINED.read()
687     }
688 
689     fn current_fb_fix(&self) -> FixedScreenInfo {
690         *VESAFB_FIX_INFO.read()
691     }
692 
693     fn video_mode(&self) -> Option<&FbVideoMode> {
694         todo!()
695     }
696 
697     fn state(&self) -> FbState {
698         self.inner.lock().fb_state
699     }
700 
701     fn framebuffer_info_data(&self) -> &RwLock<FrameBufferInfoData> {
702         &self.fb_data
703     }
704 }
705 
706 #[derive(Debug)]
707 #[cast_to([sync] PlatformDriver)]
708 struct VesaFbDriver {
709     inner: SpinLock<InnerVesaFbDriver>,
710     kobj_state: LockedKObjectState,
711 }
712 
713 impl VesaFbDriver {
714     pub fn new() -> Arc<Self> {
715         let r = Arc::new(Self {
716             inner: SpinLock::new(InnerVesaFbDriver {
717                 ktype: None,
718                 kset: None,
719                 parent: None,
720                 kernfs_inode: None,
721                 devices: Vec::new(),
722                 bus: None,
723                 self_ref: Weak::new(),
724             }),
725             kobj_state: LockedKObjectState::new(None),
726         });
727 
728         r.inner.lock().self_ref = Arc::downgrade(&r);
729 
730         return r;
731     }
732 }
733 
734 #[derive(Debug)]
735 struct InnerVesaFbDriver {
736     ktype: Option<&'static dyn KObjType>,
737     kset: Option<Arc<KSet>>,
738     parent: Option<Weak<dyn KObject>>,
739     kernfs_inode: Option<Arc<KernFSInode>>,
740     devices: Vec<Arc<dyn Device>>,
741     bus: Option<Weak<dyn Bus>>,
742 
743     self_ref: Weak<VesaFbDriver>,
744 }
745 
746 impl VesaFbDriver {
747     const NAME: &'static str = "vesa-framebuffer";
748 }
749 
750 impl PlatformDriver for VesaFbDriver {
751     fn probe(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
752         let device = device
753             .clone()
754             .arc_any()
755             .downcast::<VesaFb>()
756             .map_err(|_| SystemError::EINVAL)?;
757 
758         device.set_driver(Some(self.inner.lock_irqsave().self_ref.clone()));
759 
760         return Ok(());
761     }
762 
763     fn remove(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
764         todo!()
765     }
766 
767     fn shutdown(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
768         // do nothing
769         return Ok(());
770     }
771 
772     fn suspend(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
773         // do nothing
774         return Ok(());
775     }
776 
777     fn resume(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
778         todo!()
779     }
780 }
781 
782 impl Driver for VesaFbDriver {
783     fn id_table(&self) -> Option<IdTable> {
784         Some(IdTable::new(VesaFb::NAME.to_string(), None))
785     }
786 
787     fn devices(&self) -> Vec<Arc<dyn Device>> {
788         self.inner.lock().devices.clone()
789     }
790 
791     fn add_device(&self, device: Arc<dyn Device>) {
792         let mut guard = self.inner.lock();
793         // check if the device is already in the list
794         if guard.devices.iter().any(|dev| Arc::ptr_eq(dev, &device)) {
795             return;
796         }
797 
798         guard.devices.push(device);
799     }
800 
801     fn delete_device(&self, device: &Arc<dyn Device>) {
802         let mut guard = self.inner.lock();
803         guard.devices.retain(|dev| !Arc::ptr_eq(dev, device));
804     }
805 
806     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
807         self.inner.lock().bus = bus;
808     }
809 
810     fn bus(&self) -> Option<Weak<dyn Bus>> {
811         self.inner.lock().bus.clone()
812     }
813 
814     fn dev_groups(&self) -> &'static [&'static dyn AttributeGroup] {
815         return &[&VesaFbAnonAttributeGroup];
816     }
817 }
818 
819 impl KObject for VesaFbDriver {
820     fn as_any_ref(&self) -> &dyn core::any::Any {
821         self
822     }
823 
824     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
825         self.inner.lock().kernfs_inode = inode;
826     }
827 
828     fn inode(&self) -> Option<Arc<KernFSInode>> {
829         self.inner.lock().kernfs_inode.clone()
830     }
831 
832     fn parent(&self) -> Option<Weak<dyn KObject>> {
833         self.inner.lock().parent.clone()
834     }
835 
836     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
837         self.inner.lock().parent = parent;
838     }
839 
840     fn kset(&self) -> Option<Arc<KSet>> {
841         self.inner.lock().kset.clone()
842     }
843 
844     fn set_kset(&self, kset: Option<Arc<KSet>>) {
845         self.inner.lock().kset = kset;
846     }
847 
848     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
849         self.inner.lock().ktype
850     }
851 
852     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
853         self.inner.lock().ktype = ktype;
854     }
855 
856     fn name(&self) -> String {
857         Self::NAME.to_string()
858     }
859 
860     fn set_name(&self, _name: String) {
861         // do nothing
862     }
863 
864     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
865         self.kobj_state.read()
866     }
867 
868     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
869         self.kobj_state.write()
870     }
871 
872     fn set_kobj_state(&self, state: KObjectState) {
873         *self.kobj_state.write() = state;
874     }
875 }
876 
877 #[derive(Debug)]
878 struct VesaFbAnonAttributeGroup;
879 
880 impl AttributeGroup for VesaFbAnonAttributeGroup {
881     fn name(&self) -> Option<&str> {
882         None
883     }
884 
885     fn attrs(&self) -> &[&'static dyn Attribute] {
886         &[&AnonAttrPhysAddr as &'static dyn Attribute]
887     }
888 
889     fn is_visible(
890         &self,
891         _kobj: Arc<dyn KObject>,
892         attr: &'static dyn Attribute,
893     ) -> Option<ModeType> {
894         Some(attr.mode())
895     }
896 }
897 
898 #[derive(Debug)]
899 struct AnonAttrPhysAddr;
900 
901 impl Attribute for AnonAttrPhysAddr {
902     fn name(&self) -> &str {
903         "smem_start"
904     }
905 
906     fn mode(&self) -> ModeType {
907         ModeType::S_IRUGO
908     }
909 
910     fn support(&self) -> SysFSOpsSupport {
911         SysFSOpsSupport::ATTR_SHOW
912     }
913 
914     fn show(&self, _kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
915         sysfs_emit_str(
916             buf,
917             format!(
918                 "0x{:x}\n",
919                 VESAFB_FIX_INFO
920                     .read()
921                     .smem_start
922                     .unwrap_or(PhysAddr::new(0))
923                     .data()
924             )
925             .as_str(),
926         )
927     }
928 }
929 
930 #[unified_init(INITCALL_DEVICE)]
931 pub fn vesa_fb_driver_init() -> Result<(), SystemError> {
932     let driver = VesaFbDriver::new();
933 
934     platform_driver_manager().register(driver)?;
935 
936     return Ok(());
937 }
938 
939 /// 在内存管理初始化之前,初始化vesafb
940 pub fn vesafb_early_init() -> Result<VirtAddr, SystemError> {
941     let mut _reserved: u32 = 0;
942 
943     let mut fb_info: MaybeUninit<multiboot_tag_framebuffer_info_t> = MaybeUninit::uninit();
944     //从multiboot2中读取帧缓冲区信息至fb_info
945 
946     // todo: 换成rust的,并且检测是否成功获取
947     unsafe {
948         multiboot2_iter(
949             Some(multiboot2_get_Framebuffer_info),
950             fb_info.as_mut_ptr() as usize as *mut c_void,
951             &mut _reserved as *mut c_uint,
952         )
953     };
954     unsafe { fb_info.assume_init() };
955     let fb_info: multiboot_tag_framebuffer_info_t = unsafe { core::mem::transmute(fb_info) };
956 
957     // todo: 判断是否有vesa帧缓冲区,这里暂时直接设置true
958     HAS_VESA_FB.store(true, core::sync::atomic::Ordering::SeqCst);
959 
960     let width = fb_info.framebuffer_width;
961     let height = fb_info.framebuffer_height;
962 
963     let mut boot_params_guard = boot_params().write();
964     let boottime_screen_info = &mut boot_params_guard.screen_info;
965 
966     boottime_screen_info.is_vga = true;
967 
968     boottime_screen_info.lfb_base = PhysAddr::new(fb_info.framebuffer_addr as usize);
969 
970     if fb_info.framebuffer_type == 2 {
971         //当type=2时,width与height用字符数表示,故depth=8
972         boottime_screen_info.origin_video_cols = width as u8;
973         boottime_screen_info.origin_video_lines = height as u8;
974         boottime_screen_info.video_type = BootTimeVideoType::Mda;
975         boottime_screen_info.lfb_depth = 8;
976     } else {
977         //否则为图像模式,depth应参照帧缓冲区信息里面的每个像素的位数
978         boottime_screen_info.lfb_width = width;
979         boottime_screen_info.lfb_height = height;
980         boottime_screen_info.video_type = BootTimeVideoType::Vlfb;
981         boottime_screen_info.lfb_depth = fb_info.framebuffer_bpp as u8;
982     }
983 
984     boottime_screen_info.lfb_size =
985         (width * height * ((fb_info.framebuffer_bpp as u32 + 7) / 8)) as usize;
986 
987     // let buf_vaddr = VirtAddr::new(0xffff800003200000);
988     let buf_vaddr = VirtAddr::new(
989         crate::include::bindings::bindings::SPECIAL_MEMOEY_MAPPING_VIRT_ADDR_BASE as usize
990             + FRAME_BUFFER_MAPPING_OFFSET as usize,
991     );
992     boottime_screen_info.lfb_virt_base = Some(buf_vaddr);
993 
994     let init_text = "Video driver to map.\n\0";
995     send_to_default_serial8250_port(init_text.as_bytes());
996 
997     // 地址映射
998     let paddr = PhysAddr::new(fb_info.framebuffer_addr as usize);
999     let count =
1000         PageFrameCount::new(page_align_up(boottime_screen_info.lfb_size) / MMArch::PAGE_SIZE);
1001     unsafe { pseudo_map_phys(buf_vaddr, paddr, count) };
1002     return Ok(buf_vaddr);
1003 }
1004 
1005 #[unified_init(INITCALL_DEVICE)]
1006 fn vesa_fb_device_init() -> Result<(), SystemError> {
1007     // 如果没有vesa帧缓冲区,直接返回
1008     if !HAS_VESA_FB.load(core::sync::atomic::Ordering::SeqCst) {
1009         return Ok(());
1010     }
1011 
1012     static INIT: Once = Once::new();
1013     INIT.call_once(|| {
1014         kinfo!("vesa fb device init");
1015         let device = Arc::new(VesaFb::new());
1016 
1017         let mut fb_fix = VESAFB_FIX_INFO.write_irqsave();
1018         let mut fb_var = VESAFB_DEFINED.write_irqsave();
1019 
1020         let boot_params_guard = boot_params().read();
1021         let boottime_screen_info = &boot_params_guard.screen_info;
1022 
1023         fb_fix.smem_start = Some(boottime_screen_info.lfb_base);
1024         fb_fix.smem_len = boottime_screen_info.lfb_size;
1025 
1026         if boottime_screen_info.video_type == BootTimeVideoType::Mda {
1027             fb_fix.visual = FbVisual::Mono10;
1028             fb_var.bits_per_pixel = 8;
1029             fb_fix.line_length =
1030                 (boottime_screen_info.origin_video_cols as u32) * (fb_var.bits_per_pixel / 8);
1031             fb_var.xres_virtual = boottime_screen_info.origin_video_cols as u32;
1032             fb_var.yres_virtual = boottime_screen_info.origin_video_lines as u32;
1033         } else {
1034             fb_fix.visual = FbVisual::TrueColor;
1035             fb_var.bits_per_pixel = boottime_screen_info.lfb_depth as u32;
1036             fb_fix.line_length =
1037                 (boottime_screen_info.lfb_width as u32) * (fb_var.bits_per_pixel / 8);
1038             fb_var.xres_virtual = boottime_screen_info.lfb_width as u32;
1039             fb_var.yres_virtual = boottime_screen_info.lfb_height as u32;
1040             fb_var.xres = boottime_screen_info.lfb_width as u32;
1041             fb_var.yres = boottime_screen_info.lfb_height as u32;
1042         }
1043 
1044         fb_var.red.length = boottime_screen_info.red_size as u32;
1045         fb_var.green.length = boottime_screen_info.green_size as u32;
1046         fb_var.blue.length = boottime_screen_info.blue_size as u32;
1047 
1048         fb_var.red.offset = boottime_screen_info.red_pos as u32;
1049         fb_var.green.offset = boottime_screen_info.green_pos as u32;
1050         fb_var.blue.offset = boottime_screen_info.blue_pos as u32;
1051 
1052         // TODO: 这里是暂时这样写的,初始化为RGB888格式,后续vesa初始化完善后删掉下面
1053         fb_var.red.offset = 16;
1054         fb_var.green.offset = 8;
1055         fb_var.blue.offset = 0;
1056 
1057         if fb_var.bits_per_pixel >= 1 && fb_var.bits_per_pixel <= 8 {
1058             fb_var.red.length = fb_var.bits_per_pixel;
1059             fb_var.green.length = fb_var.bits_per_pixel;
1060             fb_var.blue.length = fb_var.bits_per_pixel;
1061         }
1062 
1063         device_manager().device_default_initialize(&(device.clone() as Arc<dyn Device>));
1064 
1065         platform_device_manager()
1066             .device_add(device.clone() as Arc<dyn PlatformDevice>)
1067             .expect("vesa_fb_device_init: platform_device_manager().device_add failed");
1068 
1069         frame_buffer_manager()
1070             .register_fb(device.clone() as Arc<dyn FrameBuffer>)
1071             .expect("vesa_fb_device_init: frame_buffer_manager().register_fb failed");
1072 
1073         // 加入全局fb表
1074         let mut guard = FRAME_BUFFER_SET.write();
1075         if guard.get(device.fb_id().data() as usize).unwrap().is_some() {
1076             kwarn!(
1077                 "vesa_fb_device_init: There is already an element {:?} in the FRAME_BUFFER_SET",
1078                 device.fb_id()
1079             );
1080         }
1081         guard[device.fb_id().data() as usize] = Some(device.clone());
1082 
1083         // 设置vesa fb的状态为运行中
1084         device.inner.lock().fb_state = FbState::Running;
1085     });
1086 
1087     return Ok(());
1088 }
1089