Newer
Older
AMI-Aptio-BIOS-Reversed / AmiModulePkg / CSM / CsmVideo / CsmVideo.md
@Ajax Dong Ajax Dong 2 days ago 21 KB Full restructure

CsmVideo

Function Table

Address Name Description
_ModuleEntryPoint
CsmVideoDriverEntry
CsmVideoChildInit
CsmVideoModeSet
CsmVideoInstanceCreate
CsmVideoDetectDevice
CsmVideoChildAddProtocol
CsmVideoFreeBuffers
EdidParseAndMerge
VesaGetControllerCapabilities
VesaEnumerateModes
GraphicsOutputQueryMode
AllocateVideoBuffers
GraphicsOutputSetMode
GraphicsOutputSetModeWrapper
VgaTextSetCursorPosition
EdidOverrideUninstall
VgaClassConstructor
VgaClassDestructor
VgaTextInit
VgaTextStringOutput
VgaTextTestStringValid
VgaTextClearScreen
VgaTextEnableCursor
VgaTextQueryModeInfo
VgaTextSetMode
VgaCursorSetPosition
VgaWriteCrtRegister
VgaOemCharTranslate
IsVgaEnableCheck
LegacyBiosPlatformSetVideoController
IsPciRootBridgeVgaCompatible
CmosReadVideoType
Forward declarations from CsmVideo.h / library code
EFI_BOOT_SERVICES *gBS;
_ModuleEntryPoint @ 0x390
CsmVideoDriverEntry @ 0x44C
Install protocols on ImageHandle:
Status = gBS->InstallMultipleProtocolInterfaces (
Install EDID_ACTIVE protocol on a child handle
ChildHandle = NULL;
Connect the LegacyBiosPlatform protocol
Status = gBS->ConnectController (
sub_7A0 -- CsmVideoChildInit: initialize a VGA/display child
Get PCI Root Bridge IO protocol on the child
Status = gBS->HandleProtocol (
Locate Legacy BIOS Platform protocol
Status = gBS->LocateProtocol (
Open PCI IO protocol with VGA attribute
Attributes = (UINT64 )((UINT8 *)Instance + 40); // Instance->Attributes
Get current mode / attributes
Status = PciIo->GetAttributes (PciIo, NULL, &Supported, NULL, NULL);
Enable VGA decode, IO, and memory access
Status = PciIo->SetAttributes (
Check if this is a VGA-compatible device via LegacyBIOS platform
Status = LegacyBiosPlatform->GetVgaCompatible (
Allocate resources descriptor for VGA legacy IO range
if (CsmVideo != NULL) {
Check if already VGA enabled - skip if so
if (IsVgaEnableCheck (ChildHandle)) {
Create the CsmVideo instance
Status = CsmVideoInstanceCreate (
sub_9EC -- CsmVideoModeSet: set display mode
If no modes requested, try EDID_OVERRIDE first, then EDID_ACTIVE
if (ModeCount == 0) {
Try to open EDID_OVERRIDE protocol
Status = gBS->OpenProtocol (
Otherwise open EDID_ACTIVE and configure display
Detect VGA child info
For each requested mode, try to add it
for (Index = 0; Index < ModeCount; Index++) {
Restore previous VGA mode if needed
if (!IsVgaEnableCheck (ChildHandle) && IsVesaModeEnabled) {
Detect the video device
Status = CsmVideoDetectDevice (Instance, ModeArray[0], &CsmVideo);
Add each requested mode
Restore VGA mode if necessary
sub_CE0 -- CsmVideoInstanceCreate: create and initialize video instance
Allocate 264-byte instance
Status = gBS->AllocatePool (EfiBootServicesData, sizeof (CSM_VIDEO_INSTANCE), (VOID )&CsmVideo);**
Query the VGA PCI config space for class code
Status = PciIo->Pci.Read (
Detect device type: VGA compatible (class 3) or not
if **(!(Class[2] == 3 (Class[2] == 0 && Class[1] == 3 && !Class[0]))) {**
Not VGA-compatible; check for other video class
Not VGA, not a display controller
Is VGA compatible - check for VESA mode
Not already in VGA mode, but VGA compatible
Initialize instance fields
Default to legacy VGA
Assume VESA-capable
If no Legacy BIOS platform, go straight to legacy VGA
if (!gLegacyBiosPlatformAvailable) {
Create end of device path for VGA IO range claim
if (LegacyBiosHandle == NULL) {
Create ACPI device path for VGA IO range
Apppend device path for the VGA rom
Install protocol interfaces for the VESA/child
Enumerate VESA modes
Status = VesaEnumerateModes (CsmVideo);
VESA succeeded
Fall back to legacy VGA
Legacy BIOS platform path install EDID protocol only
Install full set of protocols for VESA/child
Install GOP protocol
Legacy VGA mode: populate VGA text mode parameters
Legacy VGA CRTC parameters
CRTC index
CRTC data
Mono CRTC index
Mono CRTC data
Attribute Controller
Sequencer CsmVideo->InputRanges = 0xFF;
sub_1080 -- CsmVideoDetectDevice: detect video controller and return instance
Returns ptr to EdidActive field
Adjust from field offset back to instance start
EdidActive is at offset 32 in CsmVideoInstance
Fall back to EDID_OVERRIDE protocol
EdidOverride is at offset 0x60 (96) in the instance
sub_1178 -- CsmVideoChildAddProtocol: install protocols on video child
Status = CsmVideoDetectDevice (Instance, ParentHandle, &CsmVideo);
Close any existing EDID_ACTIVE protocol on the target handle
Install the full protocol set on this child (VESA mode)
Install EDID_OVERRIDE (legacy VGA mode)
If install failed, re-open EDID_ACTIVE to restore state
Initialize cursor to 80x25 text mode
80x25 color text mode
VGA INT10 AH=00h: set video mode 3 (80x25 color text)
VGA INT10 AH=01h: set cursor shape (no cursor)
Function 01h, CH=11h, CL=14h
Initialize VESA controller
VesaGetControllerCapabilities (CsmVideo);
Mark the global child handle
sub_1300 -- CsmVideoFreeBuffers: free all resources
Free frame buffer 3
Free frame buffer 2
Free frame buffer
Free scan line buffer
Free text buffer + its memory descriptor
Free EDID override buffer
Free the instance itself
sub_145C -- EdidParseAndMerge: parse EDID block, extract timings
Validate EDID checksum
Parse established timings from EDID byte 0x23
EstablishedTimings **= Edid->EstablishedTimings[0] **
Map known established timing resolutions
Established timings from EDID spec
720x400 @ 70Hz
Check each flag bit
for (TimingIndex = 0; TimingIndex < 17; TimingIndex++) {
Parse detailed timing descriptors (EDID bytes 0x36-0x6F, 18 bytes each)
for (DetailedTimingIndex = 0; DetailedTimingIndex < 4; DetailedTimingIndex++) {
Check if this is a timing descriptor (byte 0 = tag, byte 1 != 1 = pixel clock)
if (TimingDescriptor[0] != 0x01 && TimingDescriptor[1] != 0x01) {
Extract Horizontal pixels from bytes 0x02-0x04 (packed)
HorizontalPixels = (UINT16)(TimingDescriptor[2] + ((TimingDescriptor[4] & 0xF0) << 4));
Aspect ratio / Vertical lines extraction
AspectRatio = TimingDescriptor[3] >> 6;
Ratio 16:10
Ratio 4:3
Ratio 5:4
Ratio 16:9
sub_16A0 -- VesaGetControllerCapabilities: query VESA VBE BIOS
48 bytes
Issue VBE controller capabilities call
0x4F15 VbeControllerInfo[1] = 0x10; // Function = Get Capabilities
Number of graphics ports
Default to 1
Enumerate each graphics port to find a connected display
for (PortIndex = 0; PortIndex < GraphicsPortCount; PortIndex++) {
Function = Get Port
Found a connected port
sub_17D8 -- VesaEnumerateModes: enumerate all VESA VBE modes
256 byte VBE mode info block
256 byte VBE controller info
Get VBE controller info
Status = VesaGetControllerCapabilities (CsmVideo);
Get EDID override data if present
EdidOverrideProtocolSize = 0;
Allocate space for mode list (up to ~256 VBE modes)
ModeBuffer = AllocateZeroPool (256 * sizeof (UINT16));
Loop through VESA/VBE modes
for (Index = 0; ; Index++) {
Get VBE mode info for this mode number
VBE function 0x4F01: Get Mode Info
VBE function
Mode number
No more modes or error
Validate mode number
if (VbeModeNumber < 0x100) {
Check mode attributes bit 7 (linear FB supported) and bit 0 (mode supported)
if **(!(VbeModeInfo[0] & 0x80) !(VbeModeInfo[0] & 0x01)) {**
Check mode type (must be invalid type to be graphical)
if ((VbeModeInfo & 0x08) == 0) {
Check for linear frame buffer
if (!(VbeModeInfo[0] & VESA_MODE_LINEAR_FB_BIT)) {
Check bits per pixel: must be 24-32, and modulo 8 == 0
Check PhysBasePtr is non-zero
Check resolution against EDID table
HorizontalRes = (UINT32 )&VbeModeInfo[0x12]; // XResolution
YResolution EdidMatchFound = FALSE;
Check for duplicate
for (Index = 0; Index < UsableModes; Index++) {
Mode is usable add to our mode table
Update mode count
Allocate video buffers for this instance
Status = AllocateVideoBuffers (CsmVideo);
sub_21AC -- GraphicsOutputQueryMode: GOP QueryMode
Get instance from CR (This is at offset 32 from instance)
CsmVideo = (CSM_VIDEO_INSTANCE )((UINT8 )This - 32);
Check if initialized
if (CsmVideo->bEdidOverrideActive) {
Validate parameters
if **(ModeNumber >= CsmVideo->MaxMode SizeOfInfo == NULL Info == NULL) {**
Allocate output buffer (36 bytes as observed)
Populate mode info from VESA mode table (72 bytes per entry)
ModeInfoEntry = &CsmVideo->VesaModeInfo[ModeNumber];
Calculate pixel information
PixelsPerScanLine = 8 * BytesPerScanLine / BitsPerPixel
sub_22D4 -- AllocateVideoBuffers: allocate scan line, text, and frame buffers
Compute worst-case dimensions from all modes
Scan all modes to find the largest
Status = gBS->AllocatePool (
Allocate text buffer (153600 bytes = 80252*24 VGA text mode save area)
sub_24AC -- GraphicsOutputSetMode: GOP SetMode
48 bytes buffer for INT10
Find instance via CR (This at offset 32)
if (ModeNumber >= CsmVideo->MaxMode) {
Prepare VBE call buffer
If mode number < 0x100, use standard VGA mode set
if (ModeInfo->VbeModeNumber < 0x100) {
VGA mode set via INT10 AH=00h, AL=mode
VBE Set Mode
Update current mode info
Calculate frame buffer size
Clear the frame buffer (fill with zeros)
Copy current frame buffer from VESA linear FB to our shadow buffer
sub_26DC -- GraphicsOutputSetModeWrapper: 10-param wrapper for GOP SetMode
Get current EDID override info from instance
CsmVideo = CR_FROM_EDID_ACTIVE (CsmVideo);
If currently in EDID override mode, handle state transition
if (EdidOverrideActive) {
Close EDID_ACTIVE protocol (open from child controller)
Status = gBS->CloseProtocol (
Set the VGA mode
Status = GraphicsOutputSetMode (&CsmVideo->GraphicsOutput, ModeNumber);
Open EDID_ACTIVE with BY_CHILD_CONTROLLER after mode set
sub_2D84 -- VgaTextSetCursorPosition: set cursor via INT10 AH=02h
Validate cursor mode
if (CursorMode > Instance->ModeTableSize) {
Perform INT10 call
DX = 0 (row=0, col=0)
Set cursor to end of screen for mode 1
Call INT10 to set cursor position
sub_2E58 -- EdidOverrideUninstall: remove EDID override protocols
Open EDID_OVERRIDE protocol on child
Close and uninstall EDID_ACTIVE protocol
sub_2ED0 -- VgaClassConstructor: create VGA text class
Get PCI Root Bridge IO protocol
Open PCI IO protocol
Open EDID_OVERRIDE protocol
Allocate VGA Class Instance (144 bytes)
Status = gBS->AllocatePool (EfiBootServicesData, sizeof (VGA_CLASS_INSTANCE), (VOID )&VgaClass);**
Set signature
Fill vtable
Initialize the VGA class instance:
init -> set mode (15) -> set cursor -> enable cursor
Status = VgaClass->SetMode (&VgaClass->ModeTableSize, 15);
Install Legacy BIOS protocol on the child
sub_3138 -- VgaClassDestructor: destroy VGA class instance
Open Legacy BIOS protocol
Adjust from LegacyBios protocol interface back to instance
VgaClass = (VGA_CLASS_INSTANCE )((UINT8 )VgaClass - 16);
Status = gBS->ReinstallProtocolInterface (
Uninstall EDID_ACTIVE protocol
Free the instance
sub_322C -- VgaTextInit: initialize VGA text mode
Set palette registers (INT10 AH=0Bh/BH=01h)
Set cursor type (start, end)
return This->SetCursor (This, 0);
sub_3280 -- VgaTextStringOutput: output string to VGA text screen
Validate This signature
if (This->Signature != VGA_CLASS_INSTANCE_SIGNATURE) {
Get current mode dimensions
Status = This->QueryMode (This, &ScreenWidth, &ScreenHeight);
Get text cursor position from attribute fields
CursorX = This->CursorX;
Get current attribute
Attribute = This->Attribute;
Get frame buffer stride (bytes per scan line)
Stride = This->FrameBufferStride;
Process each character in the string
for (; *String != 0; String++) {
Backspace if (CursorX > 0) {
Line feed
Scroll the screen up by one line
if (CursorY == (ScreenHeight - 1)) {
Scroll **CursorData[0] = ((Attribute << 8) 0x20);**
Carriage return
Convert OEM characters to VGA glyphs
if (VgaOemCharTranslate (CurrentChar, &GlyphData)) {
Write character to frame buffer at current cursor position
FrameBufferOffset = CursorY Stride + CursorX 2;
Write character + attribute to VGA text buffer (B8000 or shadow)
Advance to next line
Update cursor position
sub_34BC -- VgaTextTestStringValid: validate Unicode string for VGA
ASCII printable range (0x20-0x7F)
if ((CurrentChar - 0x20) > 0x5F) {
Check for control characters (0x00-0x0D with supported set)
if **(CurrentChar > 0x0D **
Check for OEM character range
if (((CurrentChar & 0xFF00) - 0x2100) & 0xFBFF) {
Look up in OEM-to-VGA translation table
if (!VgaOemCharTranslate (CurrentChar, NULL)) {
sub_3550 -- VgaTextClearScreen: fill VGA text screen with spaces
Validate //
Get dimensions
Clear the entire screen buffer
Stride = ScreenWidth * 2; // Two bytes per character (char + attr)
Space with current attribute
Fill the VGA text region
for (CursorY = 0; CursorY < ScreenHeight; CursorY++) {
Set cursor to home (0,0)
sub_362C -- VgaTextSetCursorPosition: set text cursor with bounds check
Status = This->QueryMode (This, &MaxCol, &MaxRow);
Bounds check
if **(Column >= MaxCol Row >= MaxRow) {**
Set cursor position via CRT controller registers
VgaCursorSetPosition (This, Column, Row, MaxCol);
Update internal state
sub_36D0 -- VgaTextEnableCursor: enable/disable cursor
Enable cursor via INT10: AH=01h, CH=cursor start, CL=cursor end
if (Enable) {
Disable cursor by moving it off screen
VgaWriteCrtRegister (This, CRTC_CURSOR_START, 0x20);
sub_3770 -- VgaTextQueryModeInfo: return cols/rows for VGA text mode
Validate mode index
if (ModeIndex >= This->ModeTableSize) {
Mode 0 = 80x25, Mode 1 = 80x50
if (ModeIndex == 0) {
sub_3810 -- VgaTextSetMode: select VGA text mode
Clear the current screen
Store current mode index
Program the frame buffer mode
return This->FrameBufferModeSet (This->FrameBufferAccess, ModeIndex);
sub_388C -- VgaCursorSetPosition: program cursor via CRT registers
Calculate linear cursor offset
CursorOffset = X + ScreenWidth * Y;
Write cursor location high byte to CRTC register 0x0E
VgaWriteCrtRegister (This, CRTC_CURSOR_LOC_HIGH, (CursorOffset >> 8));
Write cursor location low byte to CRTC register 0x0F
VgaWriteCrtRegister (This, CRTC_CURSOR_LOC_LOW, (CursorOffset & 0xFF));
sub_38F4 -- VgaWriteCrtRegister: write CRTC register
__outbyte (CRTC_INDEX_PORT, RegisterIndex);
sub_396C -- VgaOemCharTranslate: convert OEM/Unicode to VGA glyph
OEM character range: Unicode code page 437 / OEM
if (((UnicodeChar & 0xFF00) - 0x2100) & 0xFBFF) {
Look up the character in the translation table (a global static list)
The table maps pairs of (Unicode, VGA_Index)
sub_568 -- IsVgaEnableCheck: check if any child has VGA enable
Open protocol info for EDID_ACTIVE on this handle
Status = gBS->OpenProtocolInformation (
Check each open protocol entry for BIT3 (VGA enable flag)
for (Index = 0; Index < OpenInfoCount; Index++) {
sub_5E0 -- LegacyBiosPlatformSetVideoController: set/clear video owner
If no platform handle or already in the desired state, skip
if (BiosPlatformHandle == NULL) {
Check if the current state matches the request (byte_5770 optimization)
if (gIsLegacyVgaMode == SetAsActive && !Force) {
Set or clear VGA controller ownership on the legacy BIOS platform
if (SetAsActive) {
sub_6B0 -- IsPciRootBridgeVgaCompatible: check PCI class code
Get PCI IO protocol on the child handle
Read PCI class code
Check if VGA compatible (class 3, subclass 0, prog IF 0)
or VGA-compatible (class 3, any subclass, prog IF 0)
if (Class[2] == 3 && Class[1] == 0 && Class[0] == 0) {
Is VGA compatible
Close protocol
sub_2E0 -- CopyMemInternal: low-level memcpy
Handle overlapping case: if Source < Dest and overlap detected
copy backwards from end
if (Source < Destination &&
Copy backwards
return CopyMemBackwards (Destination, Source, Length);
Copy forwards with 8-byte chunks then remaining bytes
return CopyMemForward (Destination, Source, Length);
sub_4310 -- CmosReadVideoType: get video type from CMOS
Read CMOS register 0x4B (video type)
NmiBits = __inbyte (0x70) & 0x80;
Invalid or non-standard video
EFI_VGA_DEVICE }
sub_46AE -- SetMem: memset with alignment optimization
Build 64-bit word: 8 copies of Value
QuadValue = Value;
Align to 4-byte boundary
if (Length >= 4 && ((UINTN)Buf & 3)) {
Write aligned 32-bit words
for (AlignedCount = Length >> 2; AlignedCount > 0; AlignedCount--) {
Write remaining bytes
if (Length > 0) {
sub_4700 -- CopyMemOverlapped: memcpy with direction detection
Determine direction: backward if src < dst && overlap
if (Src < Dst && (Src + Length) > Dst) {
Fast aligned copy: 8 bytes at a time when both aligned
if (Length >= 8 && ((UINTN)Src & 7) == ((UINTN)Dst & 7)) {
Handle leading misaligned bytes
UINTN Align = (UINTN)Src & 7;
Copy alignment bytes
Copy aligned 8-byte chunks
UINTN Count = Length >> 3;
qmemcpy with 8-byte alignment
qmemcpy remaining

Generated by HR650X BIOS Decompilation Project