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