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