Main BIOS ================ 1. [Introduction](#introduction) 2. [Using The Main BIOS Calls](#using-the-main-bios-calls) 3. [Taxonomy](#taxonomy) # Introduction The Mega CD includes an internal ROM that contains the code and data for such things as the startup screen, the CD player and the memory manager. It also includes a library of system calls on both the Main CPU and Sub CPU side. System calls on the Sub side deal primarily with CD drive control, audio playback and data reads, as well as BRAM control. The Main side system library is quite varied, providing many useful functions for commonly used processes in games such as reading controller input, random number generation, DMA transfer, and data decompression. For the Sub CPU side, these calls are well-documented within the official Sega documentation (see MEGA CD BIOS MANUAL). The calls on the Main CPU side, however, are undocumented and are only understood from reverse engineering. This document discusses the pros and cons of using the Main side system library (which we call the "Main BIOS" for simplicity's sake) and provides a detailed reference for all the functionality it provides. ## Naming To be pedantic, "Main BIOS" is somewhat of a misnomer here. A more accurate term may be "Boot ROM System Library", and indeed for a while in Megadev we prefixed these calls with "bootlib". However, we eventually decided to go with "bios" as it is shorter and there is a symmetry to having a bios on both the Main and Sub side. Moreover, the entire internal ROM is very often colloquially called "the BIOS" especially in terms of emulation. So while the term BIOS may not be accurate (even Sega's use of the term BIOS in regards to the Sub CPU side *system calls* isn't exactly correct), we have opted to use it to keep things simple and familiar. # Main BIOS Mysteries There is no official English documentation for the Main BIOS yet there are games that use it. This raises some questions. Feel free to skip this section if you're only interested in practicalities. ## With no documentation, how do we know it exists? On startup, the Main CPU bootstraps from the 1 megabit internal ROM, memory mapped to the range 0 to 0x20000. The "MEGA CD HARDWARE MANUAL" and "MEGA CD SOFTWARE DEVELOPMENT" documentation both describe this space as simply being for "CD-ROM boot". While the documentation never explicitly says this area cannot be used by games, there is also never any explanation as to what, if anything, is available there or how to access it. Given the (lack of) information available, it follows that this space is purely internal and not meant to be used by games. Yet it was discovered that a number of games were making calls into this "CD-ROM boot" area (such as Keio Yūgekitai, Switch, Alshark, Jangō World Cup, and Ishii Hisaichi no Daiseikai, among many others). Looking into this, we find these calls reference a jump table beginning at 0x280, and further analysis shows that these functions perform a wide variety of common Mega Drive processes. Many of the routines are called by the CD Player, for example, but many are also unused by the built-in programs. The wide range of functionality, the only-partial use by the internal utilities, the existence of a fixed-position jump table and the fact that a significant number of production games make calls via this table all suggest that this was a library meant to be used by game developers to reduce some boilerplate code. ## What is a jump table? A jump table is simply an array of JMP opcodes (that is, commands to jump to an arbitrary piece of code without any register pushes or other wrapping; you might think of it as a redirect in the program). In the case of the Main BIOS, it is a fixed-position jump table, meaning it appears at the same memory offset across all revisions and versions of the internal ROM. You can find this table at offset 0x280 in the Model 1 USA version ROM, in the Model 2 Japanese version, in the Wondermega and Mega LD, and so on. The idea here is that the position and order of this table will never change, but the addresses pointed *to* by the table can vary. This allows code to be updated for bugfixes or changed for a region without breaking games that use the routines pointed to by the table. Think of it like the index in the back of a book: maybe different editions of the book have sections expanded or moved, which change the page number on which you can find the topic, but you can always determine that page number by checking the jump table (the index), which has a fixed position (the end of the book) and ordering (alphabetic order). This ensures that the very first Mega CD game will still work on the last hardware model, even though its internal ROM is a later revision. The fact that there is a "revision-proof" jump table within the Main side internal ROM strongly suggests that it was meant to be used by game developers. ## Are we simply missing some English documentation? It seems unlikely that we are missing any English paperwork. For whatever lucky reason, we have not one, not two, but three different sources of the same documents (and some partial pages from a fourth set). While the quality of the scans varies, all have the same core documents and content. It seems improbable for an additional mystery document to be missing across all three (four) sets. ## Is there at least any mention of the Main BIOS calls at all? While there is no printed, dedicated document to the topic, we do have some brief mentions of the Main BIOS located within "Sega CD Technical Bulletin #3." One section says this (emphasis added): > ### 3. The status after booting is completed. > > #### Main Side > > The loading occurs from the beginning of WORK RAM. The stack is > $FFFD00. The RAM's usage status is as follows. Please refer to the > RAM and PORT assignments in 'MEM_MAP.ASS'. Subsequent to $fffd00 > are jump table, etc., and therefore, should not be used. Those > preceding $fffd00 could be freely used **provided that boot ROM > sample routine is not used**. Also, when setting jump address in the > jump table, jump address must be set to a value equal to the label > value plus 2. The label value should not be rewritten. **Subroutine in > the boot ROM may also be used (please see mainent.i, rom_util.doc). > Use "works" defined by the using routine.** Enter SEGA-specified > security program at the head of IP. Please note that Europe and the > U.S. have different contents and sizes. **Outside of the system area, > work RAM values could differ depending on the BOOT-ROM version; > also keep in mind that the work RAM values are not guaranteed.** Despite the less than optimial translation, this actually gives us some great information and a clue about the documentation. Firstly, it says quite plainly that "subroutine in the boot ROM may also be used," which tells us, yes, code within the Main side ROM is allowed to be used by games. Next, it refers us to `MAINENT.I` and `ROM_UTIL.DOC`. Unfortunately, we do not have either of these files, but given the name of the latter file, it's possible that in lieu of printed documentation, there was a text file for reference. Whether these files were actually made available to international developers is a different question. Following this in the tech bulletin is a badly faxed list of assembly language equates that define a number of places throughout Work RAM. This includes things like the CRAM and VDP register buffers, which line up with those that appear in the Main BIOS functions. This may very well be the contents of `MAINENT.I`, though it is not specifically identified with a filename. While this doesn't provide us with information about the Main BIOS calls themselves, it does provide information on the location of some data structures used by those calls. It also says "use 'works' defined by the using routine," which seems to mean "only use the routines marked as 'working'." We know for a fact that a handful of the calls are broken, and this seems to confirm that there were known issues. This may have played a factor in keeping them less publicized. Thanks to this tech bulletin, we have A) proof that these calls were allowed to be used by games and B) some concrete names and offsets within the memory map used by these calls. ## Why do only Japanese games use these calls? Given that the Main BIOS was described in English to some extent in Tech Bulletin #3, it doesn't appear there was a cabal of Japanese developers hoarding secrets. Perhaps the probable documentation (the mysterious `ROM_UTIL.DOC` file) didn't make it to international developers in time and the translator for Bulletin #3 wasn't aware. Or perhaps the file was available, but the whole Main BIOS concept was just missed by non-Japanese devs since it wasn't as obvious as printed documentation in a binder. Though the exact state of affairs is unclear and there is much "he said, she said" around the two organizations, it does seem that Sega of Japan and Sega of America did not have the best relationship in the 1990s. I am cautious to not imply any malice or to imply Japanese devs were seeking an "edge" (as these calls don't activate hidden functionality, but simply reduce boilerplate code), but perhaps it was more of a case of an ocean and language separating the offices. I can imagine Japanese developers meeting with the engineers at Sega who designed and wrote the internal ROM, and having actual discussions about how to best utilize the hardware, speaking in their native language. Meanwhile international developers would be at the mercy of translated documentation and intermediary interpreters and the time lag of communicating with busy teams on the other side of the planet. I do find the following comment quite telling. It is from official sample code for the Super 32X, illustrating its use in conjunction with the Mega CD. The file `MAINCPU.INC` says this (emphasis added): > ;--------------------------------------------------------------------------- > ; the comment above says the memory area above $FFD000 is not for general use. > ; the jump table is considered system use. Below you will see that we have > ; put our VDP slaves in the "not for general use area". This came from a > ; code example contained in CD Tech Note #3. That code used this same area > ; for VDP slaves. **As of 5/25/93, SOJ has not provided an answer as to > ; whether this area is okay to use.** For production games, I would advise not > ; using this area, since the manual says this area is not for general use. > ; > ; We do know that trying to use any memory after these slaves ($FFFDDD) will > ; cause the machine to lock up and die. > ;---------------------------------------------------------------------------- We have a Sega of America engineer, writing official Sega of America code, who is citing the same Tech Bulletin we are as his primary source for information on using some otherwise "forbidden" areas of memory. He has apparently asked Sega of Japan for clarification, who did not respond, and suggests that developers not use this space in production games. It is difficult to do anything more than speculate about what happened here. It's also worth mentioning that we have not checked every single non-Japanese game, so we may yet find one that uses the Main BIOS calls. But now, more than 30 years later and thanks to detailed reverse engineering, we have a good understanding of these calls to make writing the games we make a little bit easier. # Using The Main BIOS Calls Using the Main BIOS calls in your code is as simple as including `main/bios.h` in your C code or `main/bios.def.h` in your ASM code. However, there are some major considerations that must be taken when using some of these calls. # Memory Usage The biggest deciding factor for using the Main BIOS or not is its use of Work RAM. Work RAM is the smallest of the memory buffers available, yet it is arguably the most important. Of the 64KB of space available in Work RAM, 768 bytes are reserved for the system vector jump table beginning at 0xFFFD00. Below that is the runtime stack, which varies in size as the program runs but generally has 256 bytes reserved. This leaves 63KB of space available to the programmer. Some Main BIOS calls use additional memory, which can take at most another 1.25KB of space, leaving you with a total of 61.75KB to use. That is still the majority of the buffer left free, but consider that Work RAM space will likely hold your game kernel, shared/global resources, and runtime memory/stack. It can fill up quickly, and that 1.25KB of space claimed by the Main BIOS may be valuable. On the other hand, the space used by the Main BIOS library is for utilities that would otherwise need to be written by yourself and would use their own memory anyway, namely, a decompression buffer for compressed graphics, a sprite list cache, and a palette cache. So the end result may be zero sum. We recommend reading through this reference and deciding early on if you wish to use any BIOS calls, then plan your memory layout around the calls you intend to use. ## Memory Map Here is the memory map for Work RAM when using the Main BIOS (modified from diagram in Tech Bulletin #3): FF0000 +----------------+ | Free Use | | | = = | | | | FFF700 +----------------+ | Main BIOS Use | | | FFFC00 +----------------+ | Stack | FFFD00 +----------------+ | System Use | FFFFFF +----------------+ In this layout, we have 61.75KB of memory to work with freely, from 0xFF0000 to 0xFFF700. Below that we have an area marked for Main BIOS Use and System Use, with a small stack in between. That last area, from 0xFFFD00 to the top of RAM, is important as it contains the system vector jump table (that is, the vectors for exceptions and interrupts - very important!). **As a rule, simply leave this space alone** whether you use the Main BIOS calls or not. ## Main BIOS Use The area from 0xFFF700 to 0xFFFB80 is 1,280 bytes (1.25kb) in size. It is divided up like so: FFF700 +----------------+ | Decompression | | Buffer | FFF900 +----------------+ | Sprite List | | Cache | FFFB80 +----------------+ | Palette Cache | FFFC00 +----------------+ We can see it is neatly partitioned into space for specific functionality. Main BIOS calls related to sprites will use the Sprite List Cache space; those related to palettes will use the Palette Cache; and so on. This means that if you do not plan to use Main BIOS calls that relate to one or more of these memory spaces, you are free to use that space yourself. For example, if there are no compressed graphics and thus no need for a decompression buffer, that space from 0xFFF700 to 0xFFF900 is free for use by your code. ## The Stack By default, the stack is set to 0xFFFD00. With the Main BIOS Use block ending at 0xFFFC00, this means there is only 256 bytes available. This is generally enough for most cases, but C code may not optimize well and could create many nested calls or large stack frames which will quickly exhaust the stack. (See `docs/dev_in_c.md`.) If you find you need more stack space, you can move it in to the Free Use space. This would free up the 0xFFFC00 to 0xFFFD00 range for your own use as well. # Taxonomy & Terminology ## Groups The Main BIOS has a large number of calls available covering a wide range of functionality. The routines and their associated variables within the Main BIOS library can be roughly divided into the following groups: - System: Subroutines for system boot; these are generally unnecessary during runtime - Interrupts: Subroutines related to interrupts and interrupt handlers - Input: Subroutines related to controller input - VDP: Subroutines related to VDP usage (graphics) - Decompression: Subroutines to decompress data - Gate Array Communication: Subroutines related to the Gate Array comm registers - Unknown: Subroutines that are not yet fully understood - Misc: Everything else You are free to pick and choose individual routines to use, but keep in mind that some are interdependent or rely on components that may not work with your project architecture. (See the next section.) We have done our best to document the calls and their memory usage to help you decide what does and does not work for your project All library calls are listed by group in the reference section below. ## Components Many of the library functions work together within their group and may share RAM locations or expect certain configurations in order to operate. We refer to these shared pieces as components. It is important to analyze what components a given library call uses as some may require the use of other library calls or use of memory that you may be planning to otherwise use. For example, the VDP Register Cache is a component that is used in the DMA routines and in many of the graphics routines. This cache is stored in the Main BIOS Use block of RAM (discussed above), so you must ensure your own code does not use that space in memory. Not all components are data, though. The Default VRAM Layout is a component that defines the memory partitioning within VRAM that is expected by a number of functions. As such, for any calls that use this component, your VRAM layout must match. A full list of components is below in the reference section. ## Other Classifications ### "Free" Functions Some Main BIOS library calls do not use any RAM or special configurations at all (i.e. they have no "cost") and can be called no matter what your memory constraints are. This means even if you are not planning to use the Main BIOS Library at all, you can still make use of these calls without worry. Such calls will be marked as "Free" in the reference section below. ### Tiny Functions Some of the functions available are quite small, consisting of little more than a move to a memory location. It may be beneficial to examine the disassembly and copy the code directly into your program to save a stack push and jump, especially if you are making the call in a tight loop. Such calls will be marked as "Tiny" in the reference below. ## Broken Functions As discussed above, the Main BIOS library functions do not have any official documentation. While most have been fully reverse engineered, there are some that have aspects that are not well understood or appear to be buggy and broken. Such calls will be marked as "Broken" along with notes about them. They should, in general, not be used, though you are welcome to examine the disassembly to see if there's something we missed in our analysis. # Component Reference ## VBLANK Component The vertical blanking interrupt (VBLANK or VINT) is very important to developing on the Mega Drive (and any CRT based retro game system). This is the period in which the electron beam inside the CRT is returning to the upper left position after reaching the end of displaying all the rows of a single frame. It is during this time when much of the game logic and data I/O is processed. The Main BIOS provides generic VBLANK wait and handling routines. The handler takes care of a number of common tasks: sync GA comm registers to/from cache, copy the palette cache to CRAM, and update controller inputs. The wait routine takes care of random number generation. The VBLANK component is useful but requires a full commitment to using the Main BIOS library due to how many other components it uses. You should familiarize yourself with the components it uses and design your program around them if you want to use the VBLANK routines. Or rather, if you decide to use most of the Main BIOS library functionality to begin with, the VBLANK handler help tie it all together. The VBLANK handler also calls `BIOS_VBLANK_USER` which points to a user-defined function that performs your game-specific logic during the VBLANK interval. The VBLANK handler also uses `BIOS_VBLANK_HANDLER_FLAGS` which acts as both the "VBLANK occured" indicator and as a set of update flags. Only two bits are used by the handler: bit 0, which will copy the sprite list cache to VRAM when set, and bit 1, which will call `BIOS_VBLANK_USER` when set. The value is always reset to zero at the end of the handler code, so the wait routines check that this value is zero to indicate a VBLANK has completed. Note that, although it uses bit 0 of `BIOS_VBLANK_HANDLER_FLAGS`, `BIOS_COPY_SPRLIST` is not actually called in the VBLANK routine. You will need to include a call to that routine in your `BIOS_VBLANK_USER` function. There are two VBLANK wait routines which are mostly identical. These calls enter a tight loop waiting for VBLANK_FLAGS to be reset to 0 (which will be set when VBLANK occurs), and will update the random number generator on each iteration. The only difference between the two is that `BIOS_VBLANK_WAIT_DEFAULT` will set both VBLANK Update flags (copy sprite list and call `BIOS_VBLANK_USER`), while `BIOS_VBLANK_WAIT` will not set any flags beforehand. Please see the `gfx` example project which uses the VBLANK component. ## Fixed VRAM Layout Component The 64kb of VRAM is shared by tile graphics, name tables (tilemaps), the sprite table and the horizontal scroll table. How much space is allocated for each section is configurable, giving flexibility to the developer on how they choose to use the VDP. However, a number of Main BIOS library routines expect the VRAM to have a specific layout. This layout is defined like so: 0000 +----------------+ | Tile Graphics | | | | | A000 +----------------+ | Window | C000 +----------------+ | Plane A | E000 +----------------+ | Plane B | B800 +----------------+ | Sprite Table | BC00 +----------------+ | Horiz. Scroll | | Table | FFFF +----------------+ This is a pretty standard layout that would work well for many applications, but your usage may vary throughout your program. It is possible to change this layout so long as the the blocks specifically used by a certain call are in their expected location. For example, the sprite list update calls expect the sprite table to be at 0xB800, but it doesn't address anything else in VRAM, and thus the rest of the layout can be different so long as the sprite table is at 0xB800. For each call that expects this layout, we will mark which blocks are used/affected. This layout is set when using the default VDP register values in `BIOS_LOAD_DEFAULT_VDP_REGS`. ## VDP Register Cache Component Since the value of VDP registers cannot be read (except for the Status register), we must maintain a mirror of those values in RAM for reference in order to preserve settings when making bitwise changes. For example, when performing a DMA operation, we must first set bit #4 on Mode Register 2. Since we cannot do a bitwise operation and must set the whole register at once, we need to know the current value so we do not alter any other bit level settings. The cache is an array of 18 words (36 bytes), one for each of the first 18 registers. (The DMA register values are not maintained, as they need to be set on each DMA operation anyway.) It is defined as `BIOS_VDP_REG_CACHE` within Megadev. ## Plane Width Cache Component The width and height of planes can be adjusted in VDP Register 0x10 to one of three values. It is important to know the current width when working with tilemaps, as the nametable data is linear. That is, to arrive at the next line in the same column, we move forward by the width of the plane in bytes in nametable memory. Thus, the plane width must be cached. All of the nametable (tilemap) related functions use the plane width cache, which is a byte value defined as `BIOS_VDP_DEFAULT_PLANE_WIDTH`. Note that this value is the width *in bytes* rather than tiles. At two bytes per entry, this means the value should simply be double the width in tiles. I.E.: 32 tiles = 64 byte width, 64 tiles = 128 byte width, 128 tiles = 256 byte width. Also note that this value must be manually updated whenever changing the width setting in VDP Register 0x10! The only exception to this is when using `BIOS_LOAD_DEFAULT_VDP_REGS` which will update the plane width cache to match the default registers. ## DMA Component DMA transfers to VRAM are a central piece of Mega Drive games, but there are quirks when doing them with Mega CD hardware. The Main BIOS library has functions for all the DMA operations as well as a simple queue system. The VDP Register Cache component is required as Mode Register 2 is updated with each operation. ## Palette Cache Component Rather than making multiple updates to CRAM via the VDP ports, the color palette is mirrored in RAM and dumped to CRAM all at once during a blanking interval. The cache is an array of 64 words (128 bytes), a 1:1 copy of CRAM. Within Megadev, it is defined as `BIOS_PALETTE_CACHE` with each of the subpalettes defined as `BIOS_PALETTE0`, `BIOS_PALETTE1`, `BIOS_PALETTE2` and `BIOS_PALETTE3`. It resides in Work RAM from 0xFFFB80 to 0xFFFC00 (see the Main BIOS Use Block section above). The palette-related functions take a pointer to color data with a two byte header. The first byte is the offset into CRAM at which the colors should be loaded. This offset is in BYTES rather than entries. Each entry is 2 bytes so e.g. the second color of the second subpalette would be offset 34. The second byte is the number of colors to load, which is counted in ENTRIES rather than bytes. The color data follows immediately. ## Sprite Table Cache Component Similar to the Palette Cache component, the Sprite Table Cache is a mirror of the sprite table in VRAM. Changes are made in the cache and dumped all at once to VRAM during a blanking interval. The cache is an array of 80 sprite table entries (640 bytes), which is the maximum displayable on screen by the VDP. See also Fixed VRAM Layout component. ## VDP Update Flags Component Rather than unconditionally copying everything to the VDP on a blanking interval, we should only copy over data that had a change. This is done by maintaining a set of flags that indicate which parts need action and which do not need any updates. In the Boot ROM, this is a byte defined as `BIOS_VDP_UPDATE_FLAGS`. Only one bit is actually used by the library functions: bit 0, to indicate the palette cache should be copied to CRAM. This bit must be used if you plan to use palette related functions like fade in/out. The rest of the bits are free for you to use as needed. ## Entities Component An entity is any element appearing on screen as composite of multiple sprites with its own rendering state. While the term "entity" is not official, we feel it sufficiently describes how the concept is most often used: to represent a discrete "object" on the screen larger than a single sprite, usually as some interactive element like a stage boss. In most games (including the Main BIOS library), entities have state related to their position, velocity and x/y flipping, etc. Moreover, they contain a pointer to a function which is run on each update. The Entity struct represents the object and its state. TODO jmptble_offset is offset into BIOS_ENTITY_ROUTINES ptr to SpriteList sprite list is: byte 0 - number of sprites in list byte 1 - unknown each sprite in the list is 6 bytes, in the Sonic 1 format ( http://info.sonicretro.org/SCHG:Sonic_the_Hedgehog_(16-bit)/Object_Editing#Mappings_editing - 5 bytes) plus a padding byte at the end /** * @brief This appears to be a Sega "standard," as it is the mapping format * used in Sonic the Hedgehog as well as the Mega CD Boot ROM. Need to check * if it is used elsewhere in Sega first party games; it's likely that it is. * * In the Mega CD Boot ROM, the collection of mappings that make up an object * is a structure defined by a two byte header: byte 1 is the count of sprites * in the object *minus 1* (zero indexed), and thus the number of mappings in * the following array; byte 2 is shared flags that are set on all mappings as * they are processed (x/y flip; possibly other flags? need to revisit this in * the disassembly and take better notes); this is followed by the array of * 5 byte mappings, though each map is padding with an empty byte at the end, * to make them 6 bytes each (likely for CPU alignment) */ After much analysis and testing, the code interacts with the sprite list unknown byte mentioned above, but does do anything with it. Its value is copied to offset 0x19 within the sprobj as part of the `BIOS_DISP_SPROBJ` routine. If the h flip flag is set, it adds to this same offset. Aside form that, the value seems to have no effect on what is displayed and it's unclear for what it is intended. The sprobjs calls are used by the BIOS CD player and Wondermega Collection. ## Random Number Generator Component There is a simple multiply-with-carry psuedo random number generator available within the Main BIOS library. A random number can be obtained by reading the word value from `BIOS_RANDOM`. However, the `BIOS_PRNG` must be called on each VBLANK iteration in order to maintain a constantly random value. `BIOS_PRNG_MOD` can be used to get a value with a maximum range. ## Font & Text Print Component There is only one print routine, which take a pointer to the text and a pointer to a VRAM nametable address where it should be displayed. Unlike C strings, text must be terminated by 0xFF, while 0x00 marks a newline. There is a standard ASCII font in the Main BIOS data which can be used if you don't need/want your own. The functions `BIOS_LOAD_FONT` and `BIOS_LOAD_FONT_DEFAULTS` will load this font into VRAM for use with the print function. `BIOS_LOAD_FONT` takes a VDP pointer to the location in VRAM where the font should be loaded as well as a 1bpp color definition (see `BIOS_LOAD_1BPP_TILES`). You must also set the `BIOS_FONT_TILE_BASE` variable to the tile index of the first tile of the font within VRAM *minus 32*. The reason for this is because ASCII codes begin at 32, and the print function simply matches an ASCII character to a tile index. Since `BIOS_FONT_TILE_BASE` cannot be negative, this implies the font must be loaded at tile index 32 or later, but cannot be placed before index 32. When placed at index 32, `BIOS_FONT_TILE_BASE` will be 0. This is the configuration the BIOS works with and you can observe this by viewing the VRAM tiles while the "Produced by or under license..." screen is being displayed. The other font load function, `_FONT_LOAD_FONT_DEFAULTS` simplifies things by loading the font to tile index 32, setting `BIOS_FONT_TILE_BASE` to 0, and setting the 1bpp color definition to palette index #1. This is the simplest method to load the font and is useful in situations where you don't need to be meticulous about VRAM management. ## Predefined Comm Flag Semantics The ga_comflags register is intended to keep the two CPUs in sync by informing each other about their status. It is a 16 bit register, split into two bytes: the upper byte for the Main CPU and the lower byte for the Sub CPU. The flags do not have an any inherent semantic meaning and the developer is free to use any or none of the flags in their program. There are a few Main BIOS library functions that use these flags, however, which inherently assigns meaning to those bits. The problem here is that we don't know what those meanings are due to a lack of documentation. We can only guess based on the context in which they appear as we reverse engineer the code. This includes understanding not just the library calls that use these bits, but what must be done on the Sub CPU side to correctly read, set and clear bits in response. Thankfully, the built in software (namely the CD player) uses these calls, meaning we have usage examples on the Sub CPU side to look at. Moreover, of the retail games identified so far that use the Main BIOS library, most of them make use of these calls and exhibit a similarity in their implementation (to the point of being nearly identical) that suggests they were built from example code. At this point, we are still investigating and have only a rough idea of what the flags represent. Therefore, we do not recommend using the functions marked as using the Predefined Comm Flag Semantics component. However, **if you plan to use the built-in vblank handler (BIOS_VBLANK_HANDLER), keep in mind that it includes a call to one of these subroutines. Please see the notes for BIOS_COMM_SYNC.** NOTES: A fresh look at this suggests that bit 0 SET indicates that the comm registers have been updated and that a fresh copy to the local cache of the opposite CPU should be made, and that bit 1 SET indicates the the CPU is ready for the copy (and inversely, that bit 1 CLEAR indicates the CPU is busy (registers comms have not yet fully propagated?) and that a copy should not yet be made). # Library Call Reference ## System Group ### _BIOS_BIOS_ENTRY ### _BIOS_RESET ### _BIOS_INIT ### _BIOS_INIT_SP ### _BIOS_SEGA_LOGO ## Interrupts Group ### `BIOS_VBLANK_HANDLER` Components: VBLANK, GA Comm, Sprite Table Cache, Palette Cache, Input A generic VBLANK handler. Calls `BIOS_COMM_SYNC`, `BIOS_COPY_PAL` and `BIOS_READ_JOYPAD` on each iteration. If bit 1 of `BIOS_VBLANK_HANDLER_FLAGS` is set, `BIOS_VBLANK_USER` will also be called. `BIOS_VBLANK_USER` points to a user-defined routine with game-specific logic to be run during VBLANK. We recommend including a call to `BIOS_COPY_SPRLIST` in your VBLANK_USER routine. `BIOS_VBLANK_HANDLER` increments the `BIOS_VBLANK_COUNTER` variable by 1 on each iteration. It also uses the `_SKIP_GFX_UPDATES` variable. When this value is non-zero, it will skip the call to `BIOS_COPY_PAL` and `BIOS_VBLANK_USER` and skip the `BIOS_VBLANK_COUNTER` increment. ### `BIOS_SET_VBLANK` (Tiny) Sets the specified pointer as the VBLANK vector. ### `BIOS_VBLANK_WAIT` Sets the specified value to `BIOS_VBLANK_HANDLER_FLAGS` and waits for the next VBLANK occurance, which resets `BIOS_VBLANK_HANDLER_FLAGS` to zero. This means `BIOS_VBLANK_HANDLER_FLAGS` must be set to a non-zero value in order to actually wait for a VBLANK occurance. If you want to wait for VBLANK without triggering a sprite list or palette copy, simply set an unused bit. ### `BIOS_VBLANK_WAIT_DEFAULT` A wrapper for `BIOS_VBLANK_WAIT` that sets `BIOS_VBLANK_HANDLER_FLAGS` to 3 (bit 0 and 1 set) before waiting. This would be useful if you do not implement any extra `BIOS_VBLANK_HANDLER_FLAGS` and only use the two used by the library. In any other case, you should stick to `BIOS_VBLANK_WAIT` as it allows you to specify flags. ### `BIOS_SET_HBLANK` ### `BIOS_SET_HBLANK_WORK_RAM` ### `BIOS_DISABLE_HBLANK` ### `BIOS_TRIGGER_IFL2` ## Input Reads ### `BIOS_READ_JOYPAD` ### `BIOS_INPUT_REPEAT_DELAY` ### `BIOS_DETECT_CONTROLLER` ## VDP/Graphics ### `BIOS_DMA_FILL_CLEAR` Components: DMA, VDP Register Cache Clears VRAM at the specifed address for the given size (in words) using DMA. ### `BIOS_DMA_FILL` Components: DMA, VDP Register Cache Loads the specified value into VRAM at the specified address for the given size (in words) using DMA. ### `BIOS_DMA_XFER` Components: DMA, VDP Register Cache Performs a DMA transfer to VRAM. ### `BIOS_DMA_XFER_WORD_RAM` Components: DMA, VDP Register Cache Performs a DMA transfer to VRAM for source data in Word RAM. ### `BIOS_DMA_COPY` Components: DMA, VDP Register Cache Performs a DMA copy. ### `BIOS_DMA_QUEUE` Components: DMA, VDP Register Cache A simple DMA queue. Processes a list of DMA transfers from Word RAM. ### `BIOS_CLEAR_VRAM` Components: DMA, VDP Register Cache Clear all of VRAM and VSRAM via DMA Fill. Also clears VSRAM with a call to `BIOS_CLEAR_VSRAM`. ### `BIOS_CLEAR_TABLES` Components: Fixed VRAM Layout (Sprite List, Plane A, Plane B, Window), Sprite Table Cache Clears the nametables (tile mappings) and sprite table. Note that it only clears the first value in the sprite table, which sets the first sprite "next" value to 0 and prevents any sprites from displaying, but does not actually clear any memory in that region. ### `BIOS_CLEAR_VSRAM` Clears VSRAM. ### `BIOS_LOAD_DEFAULT_VDP_REGS` Components: Fixed VRAM Layout (All), VDP Register Cache, Plane Width Cache Loads the Main BIOS default VDP settings to the cache and to the registers. Also updates the `BIOS_VDP_DEFAULT_PLANE_WIDTH` cached value. Here is the default VDP data loaded by the function, in the order in which it appears in the data, with notes highlighting important settings on each register: 0x8004 Mode Register 1 - HBLANK disabled - Normal color mode 0x8124 Mode Register 2 - Mega Drive graphics mode - NTSC (TODO: confirm that this is different per region (it probably is)) - Vertical blank interrupt (VBLANK) enabled - Disable display 0x9011 Plane Size - 512x512 pixels (64x64 cells) 0x8B00 Mode Register 3 - Scroll mode: full screen 0x8C81 Mode Register 4 - 40 cell (320px) width 0x8328 Window nametable address - 0xA000 0x8230 Plane A nametable address - 0xC000 0x8407 Plane B nametable address - 0xE000 0x855C Sprite table address - 0xB800 0x8D2F Horizontal scroll table address - 0xBC00 0x8700 Background color - 0 0x8A00 Horizontal interrupt (HBLANK) counter - 0 0x8F02 VRAM auto-increment - 2 0x9100 Window plane X position - 0 0x9200 Window plane Y position - 0 ### `BIOS_LOAD_VDP_REGS` Components: VDP Reg Cache Loads a list of VDP settings to the cache and to registers. This list should be null terminated array of 16 bit values, with each value being the VDP control port register write format (i.e. the upper byte is the register index with the top bit set and the lower byte is the value to write). Note that this does NOT update the `BIOS_VDP_DEFAULT_PLANE_WIDTH` variable when setting register 0x10. ### `BIOS_VDP_FILL` (Tiny) Loads the specified value to VRAM at the specified address for the given size (in words). ### `BIOS_VDP_FILL_CLEAR` (Tiny) Clears VRAM at the specified address for the given size (in words). ### `BIOS_LOAD_MAP` Components: Plane Width Cache Loads a tilemap to VRAM. ### `BIOS_LOAD_MAP_TEMPLATE` Components: Plane Width Cache Loads a tilemap to VRAM with a template value applied to each map entry. ### `BIOS_PLANE_FILL` Components: Plane Width Cache Writes a given tilemap entry to VRAM with the given dimensions. ### `BIOS_VDP_DISP_ENABLE` Components: VDP Register Cache Enables VDP display (bit 6 on VDP register 1). ### `BIOS_VDP_DISP_DISABLE` Components: VDP Register Cache Disables VDP display (bit 6 on VDP register 1). ### `BIOS_LOAD_PAL` Components: Palette Cache Loads an array of colors to the palette cache. Does not update CRAM directly. ### `BIOS_LOAD_PAL_UPDATE` Components: Palette Cache, VDP Update Flags Loads an array of colors to the palette cache and sets the CRAM update flag. Does not update CRAM directly. ### `BIOS_COPY_PAL` Components: VDP Reg Cache, DMA, Palette Cache, VDP Update Flags Copies the palette cache to CRAM. ### `BIOS_PROCESS_ENTITIES` Update the state of an array of entitys. Please see the Entities section. ### `BIOS_DISP_SPROBJ` Display an entity. Please see the Entities section. ### `BIOS_COPY_SPRLIST` Components: Sprite Cache, VDP Register Cache, VBLANK Flags Copies the sprite cache to the sprite table in VRAM. ### `BIOS_LOAD_1BPP_TILES` Converts 1bpp formatted graphics data to 4bpp VDP format and copies to VRAM. It is a form of compression as, logically, 1bpp graphics only use 1/4 of the space of 4bpp graphics. It would be most often used for simple fonts which only need to use one color. In fact, the Boot ROM's internal font is 1bpp and uses this routine to convert it to standard Mega Drive format when loading. The size of a font is likely not a concern for games using only the standard western alphabet, but when you consider east Asian languages like Japanese, Chinese and Korean and their multitudes of glyphs, having a way to quickly load and convert a large set of characters is helpful. Of course, this is not strictly limited to fonts and you can use the routine however you'd like to convert 1bpp graphics to Mega Drive 4bpp tiles. The function takes a pointer to the 1bpp data, a vdp_addr formatted VRAM destination, the number of tiles and the color definition. The color definition requires some explanation. It is a 32 bit value that acts as a mapping for each possible pair of 1 bit values. The full value is divided into four bytes visualized like so: 00'0X'X0'XX Where X is the palette index of the color to be used. So, for example, if you want the 1bpp graphics to use the color in palette index 1, the value to use would be: 0x00011011 That should be enough information to implement in your code, but if you you want to understand why this value is necessary and formatted like it is, here is the algorithm in summary. Since the native VDP tile format is 4bpp, that means there are four bytes per tile row (8 pixels * 4 bits = 32 bits = 4 bytes). For 1bpp data, there is one byte per tile row (8 pixels * 1 bit = 8 bits = 1 byte). For every byte of 1bpp data, it rotates the value by 2 bits and masks those off. That 2 bit value is then used as a byte offset relative to the MSB of the 32 bit color definition, which contains an equivalent 4bpp 2 pixel representation of that value. For example, if 2 bits of 1bpp data are binary 10 (decimal 2), then it uses the value that is two bytes from the MSB of the color definition. That value is X0, which is appended to the output 4bpp data. Basically, for each possible pair of two bits, there is a corresponding pair of nibbles (4 bits) that matches it within the color definition. ### `BIOS_LOAD_STAMP_MAP` Components: Plane Width Cache Loads a tilemap to VRAM based on sequential tiles which are vertically oriented. ### `BIOS_LOAD_MAP_HORIZ` Properties: Plane Width Cache Loads a tilemap to VRAM based on sequential tiles which are horizontally oriented. ### `BIOS_BLANK_DISPLAY` Properties: VDP Reg Cache Sets the background color to black and disables the display. ### `BIOS_PAL_FADEOUT` Properties: VDP Update Flags, Palette Cache Fades a palette range to black. ### `BIOS_PAL_FADEIN` Properties: VDP Update Flags, Palette Cache, Other Memory Fades a palette to a target palette. ### `BIOS_SET_FADEIN_PAL` Properties: Other Memory Sets the target palette for fade in. ## Decompression ### `BIOS_GFX_DECOMP` ### `BIOS_GFX_DECOMP_RAM` ### `BIOS_MAP_DECOMP` ## GA CPU Communication - Components Functions related to inter-CPU communication via the Gate Array comm registers. ## GA CPU Communication - Functions ### `BIOS_CLEAR_COMM` Clears all Gate Array COMCMD and COMFLAGS registers and the COMCMD and COMFLAGS cache. ### `BIOS_COMM_SYNC` Components: Predefined Comm Flag Semantics Triggers INT2 on the Sub CPU via the IFL2 bit (for this reason, it should be called during VBLANK). Also syncs the COMCMD cache values to the GA registers and the COMSTAT values from registers to the cache. IFL2 is set on each call regardless, but the COMCMD/COMSTAT sync is dependent on bits 0 and 1 of Sub side COMFLAGS. If Sub side bit 0 is set, Main side's bit 0 will be set and bit 1 will be flipped. It will then loop waiting for Sub side bit 1 to either set or clear, depending on the state of Main's bit 0. When the state matches the expectation, it moves on to copying COMCMD cache to registers followed by COMSTAT registers to cache. As mentioned in the Predefined Comm Flag Semantics component description, we recommend not using this function until we have a better understanding of the flags system on both CPUs. Note that if you are using `BIOS_VBLANK_HANDLER` for your vblank handler, `BIOS_COMM_SYNC` is called as part of that subroutine, which is important as it takes care of the IFL2 bit. The best way to keep things flowing smoothly is to ensure bit 0 is always unset on the Sub side COMFLAGS. This will ensure that the COMCMD/COMSTAT sync is skipped and that a stuck loop is avoided. ### `BIOS_UK_COMM_CDINFO` Components: Predefined Comm Flag Semantics Copies various CD read status values sent from the Sub CPU via COMSTAT registers, including disc read absolute and relative timecodes. One use for getting this information in real time is to time the playback of CD audio with actions on the screen. Code that implements this call suggests it is mean to be used in conjunction with `BIOS_COMM_SYNC`, with the latter called at the start of VBLANK and `BIOS_UK_COMM_CDINFO` called at the end. As mentioned in the Predefined Comm Flag Semantics component description, we recommend not using this function until we have a better understanding of the flags system on both CPUs. ### `BIOS_UK_COMMFLAGS_RELATED` Components: Predefined Comm Flag Semantics Waits for bit 6 on Sub side COMFLAGS to set, then clears Main side COMFLAGS bit 2. As mentioned in the Predefined Comm Flag Semantics component description, we recommend not using this function until we have a better understanding of the flags system on both CPUs. ### `BIOS_SET_COMCMD0_1_CACHE` Copies the word value in D0 and D1 into COMCMD0 and COMCMD1 cache, respectively. Although this does not use the Predefined Comm Flag Semantics component directly, it is likely meant to be part of its system. Therefore we recommend reviewing its code closely to make sure it does exactly what you expect before using it. ### `BIOS_SET_COMCMD2_3_CACHE` Copies the word value in D0 and D1 into COMCMD2 and COMCMD3 cache, respectively. In addition, if the value in D0 is 1, it also sets bit 2 on Main side COMFLAGS. Although this does not use the Predefined Comm Flag Semantics component directly, it is likely meant to be part of its system. Therefore we recommend reviewing its code closely to make sure it does exactly what you expect before using it. ### `BIOS_SET_COMCMD4_5_CACHE` Copies the word value in D0 and D1 into COMCMD4 and COMCMD5 cache, respectively. Although this does not use the Predefined Comm Flag Semantics component directly, it is likely meant to be part of its system. Therefore we recommend reviewing its code closely to make sure it does exactly what you expect before using it. ### `BIOS_SET_COMCMD6_7_CACHE` Copies the word value in D0 and D1 into COMCMD6 and COMCMD7 cache, respectively. Although this does not use the Predefined Comm Flag Semantics component directly, it is likely meant to be part of its system. Therefore we recommend reviewing its code closely to make sure it does exactly what you expect before using it. ### `BIOS_SET_IFL2` Sets the IFL2 bit on ga_reg_memmode to trigger INT2 on the Sub side. Should be called during VBLANK only. ## Misc - Components ## Misc - Functions ### `BIOS_PRNG` Components: Random Number Generator Generates a new 16bit random number, stored in `BIOS_RANDOM`. ### `BIOS_PRNG_MOD` Components: Random Number Generator Generates a random number with a specificed maximum value, stored in a return register. ### `BIOS_CLEAR_RAM` Clears a region of RAM in 32bit iterations. ### `BIOS_LOAD_FONT` Components: Font & Print Component Load the internal Main BIOS font to VRAM. ### `BIOS_LOAD_FONT_DEFAULTS` Components: Font & Print Component Load the internal Main BIOS font to VRAM with default settings. ### `BIOS_PRINT` Components: Font & Print Component, Plane Width Cache Prints a string of ASCII text. The position of the text on screen is determined by the passed VDP address. ### `BIOS_TO_BCD` Converts a specified native value to binary coded decimal (BCD). ### `BIOS_TO_BCD_BYTE` Converts the specified 8bit value to binary coded decimal (BCD). ## Unknown Functions ### `BIOS_UNKNOWN_1F` ### `BIOS_UNKNOWN_24` ### `BIOS_UNKNOWN_35` ### `BIOS_UNKNOWN_36` ### `BIOS_UNKNOWN_37` ### `BIOS_UNKNOWN_38` ### `_BIOD_LOAD_TILEMAP_PARTIAL` d0.l - VDP ptr d1.w - width d2.w - height a1.l - ptr to pattern data ### `BIOS_UNKNOWN_3D` ### `BIOS_UNKNOWN_44` ### `BIOS_ADD_TIME_VALUES` ### `BIOS_UNKNOWN_46`