RSS About
A photograph of a portion of a page from a printed out document about Game Boy DMA. The words "All of the memory space, except high RAM ($FF80-$FFFE), is not accessible during DMA" are highlighted.

Funny bugs: DMA myths

While I keep publishing articles about bugs in my emulator — and I do have a couple more of those in store — Goholint actually runs a lot of games pretty well these days1! It also runs many of them okay enough, with the occasional glitch or sound issue. Then, there are the games that freeze at startup or just show a blank screen.

And then, there’s Burai Fighter Deluxe.

A picture of the  Burai Fighter Deluxe Game Boy cartridge. On the label is a guy in a cheap sci-fi spacesuit firing its gun at a huge green serpent thing.
Would you like to see this run on Goholint? I do!

Cold hard crash

Burai Fighter has been one of my test games from the very beginning, for no other reason than I played it a lot as a kid and that would have made it easy to tell at a glance what was wrong with it.

Except I never even got that far. The furthest I got with that game was the end of the boot screen, and then the whole thing crashed:

$ ./goholint -rom burai-fighter-deluxe.gb
Goholint seems to have crashed (tried to execute invalid opcode FC). I'm sorry.

A: 0x3e - F: 0x00 - AF: 0x3e00
B: 0x00 - C: 0x00 - BC: 0x0000
D: 0x6e - E: 0x05 - DE: 0x6e05
H: 0x96 - L: 0x30 - HL: 0x9630
                    SP: 0xffec
                    PC: 0x01e1
Flags:
Z: 0 - N: 0 - H: 0 - C: 0

Oof. That’s definitely not supposed to happen!

I omitted the stack traces from the error message above because they’re not really that useful. The crash wasn’t caused by an out-of-bounds array access or a nil pointer. In that instance, the program self-destructed by executing this specific function:

func (op *opFc) Execute(c *CPU) (done bool) {
	panic("tried to execute invalid opcode FC")
}

This is what happens when Goholint encounters one of the eleven undefined opcodes in the Game Boy CPU’s instruction set. They are greyed out in the opcode table I linked to, and the Pan Docs say:

The following opcodes are invalid, and hard-lock the CPU until the console is powered off: $D3, $DB, $DD, $E3, $E4, $EB, $EC, $ED, $F4, $FC, and $FD.

I guess I could have handled those a little more gracefully, but to be fair, they are undefined opcodes, there is zero reason a working Game Boy title would ever attempt to execute one of these.

The real question is: how the fuck did my emulated Game Boy CPU ever end up trying to execute what must have been a random byte in the Burai Fighter ROM?

Track and trace

That got me stumped for a while. In the past few years, I have thrown a lot of test ROMs at Goholint. As far as they are concerned, it correctly implements all of the CPU instructions. JP works, CALL2, RST and RET work. So this had to be a higher-level bug, somewhere.

Unfortunately, whatever debug output I had didn’t help much. I could only tell that the crash happened when trying to execute the byte at address 0x01e0 in the ROM, which was indeed 0xfc. I had to figure out how the emulator got there in the first place.

I first tried finding out from the outside, attempting to step the CPU, see how far in the ROM it went before the crash, etc. This didn’t really go anywhere. I could tell that Goholint was doing something wrong, but I knew there was a bug anyway so it wasn’t clear just where things went off the rails.

So, as usual, I left Burai Fighter alone for the time being and focused on fixing other things in Goholint.

It’s only recently, when I did that article about writing a Game Boy ROM, that I discovered the Game Boy could get stuck in an infinite loop if you let it run past the boot ROM and execute only 0xff bytes.

It’s pretty straightforward: 0xff is the opcode for RST 38. What it does is the equivalent of an unconditional CALL to address 0x0038. If the byte at that address also happens to be 0xff, well, you can guess where this is going. The CPU just keeps jumping to that 0x0038 address endlessly3.

This felt like a potential hint. I tried debugging Burai Fighter again, this time enabling just enough debug output to know if RST was involved.

Guess what: it was!

That’s interesting because while 0xff is a totally valid instruction, the CPU can also encounter it in a few other cases. For instance, 0xff is the value you will get from an open bus. That is, unconnected memory. Like, when you don’t insert a cartridge in the Game Boy, anything it reads from the ROM address space is going to be 0xff — hence a black bar scrolling down instead of a logo.

Even more interesting is that 0xff is also the value the CPU gets if it’s trying to access video memory when it shouldn’t. Could it be that my PPU implementation had something fishy going on?

Just read the source code

At this point, I felt like I should stop trying to guess and just read what the program itself was actually doing.

This is easier said than done. Reading and interpreting binary code by hand is error prone at best. This is why we have nice tools like disassemblers!

A disassembler — like mgbdis, that I used here — takes a binary executable and turns it back into its source code, with some caveats. Like, usually, it can’t know what hasn’t made it into the final binary program, stuff like comments, variable names or, in the case of something originally written in assembly, label names4.

Still, it’s infinitely easier to read this:

Jump_000_0150:
    ld a, $01                                     ; $0150: $3e $01
    ld [$2180], a                                 ; $0152: $ea $80 $21
    di                                            ; $0155: $f3
    ld sp, $fffe                                  ; $0156: $31 $fe $ff

Rather than this:

$3e $01 $ea $80 $21 $f3 $31 $fe $ff

I’m not going to inflict the whole Burai Fighter assembly code on you. What the game does just after bootup isn’t very fancy. Clearing registers, waiting for a full frame to turn off the display, zeroing out video RAM… it should feel familiar by now!

But here’s what’s happening right after that:

    ld a, $80                                     ; $0176: $3e $80
    ldh [rDMA], a                                 ; $0178: $e0 $46
    call Call_000_0279                            ; $017a: $cd $79 $02

You’ll note in passing that the disassembler still knew some addresses to replace them with human-readable labels: it helpfully translated address 0xff46 into rDMA, the DMA register. But at this point, I got up from my chair yelling “HOW?!”

Wait, how what?

Okay, before I can explain, I’m afraid I need a quick digression because I haven’t talked about DMA before.

DMA stands for Direct Memory Access, it’s not specific to the Game Boy, and it’s a great way to copy large amounts of data quickly. I once mentioned that copying data in assembly was tedious, that it required a loop and counters and stuff. But it’s not only tedious, it’s also slow.

As an example, this is the kind of loop you would write to copy 256 bytes from some part of the memory to another:

    ld hl, $1000        ; Source address in HL (3 cycles).
    ld de, $8000        ; Destination address in DE (3 cycles).
copy:
    ld a, [hl+]         ; Load current source byte in A, increment HL (2 cycles).
    ld [de], a          ; Write byte to destination address [DE] (2 cycles).
    inc de              ; Point DE to next destination byte (2 cycles).
    bit 0, h            ; Check whether copy is done (2 cycles).
    jr z, copy          ; If not (H < 0x11), keep copying data (2 or 3 cycles).

I’m sure there are ways to write it a little more efficiently, but this is mostly how you copy data in assembly.

I indicated the duration of each operation in cycles5. One cycle takes roughly 1µs. The code above takes 6+(255×11)+10 cycles to run to completion6. If you ignore the setup and the last iteration of the loop, it takes 11 cycles to copy a single byte.

I’ll concede that an 11µs operation might not seem all that slow, but keep in mind that Game Boy code often has to be fast when it’s copying to video memory because it can only do that during short breaks in the PPU (HBlank, VBlank…)

That’s where DMA comes in. On the Game Boy, DMA will only take a single cycle to copy one byte. Eleven times faster than doing it by hand! Unsurprisingly, this mechanism was specifically designed so that a program could quickly copy data that changes often to video memory, so you can, say, update sprites between one frame and the next.

This means DMA comes with a catch: it will only copy exactly 160 bytes from a given source address, and you don’t get to pick the destination. DMA always copies data to the OAM (Object Attribute Memory), which is the zone in video RAM where sprite data lives. The Game Boy can display 40 sprites and each sprite’s attributes take 4 bytes of memory, so DMA can update all of them in a single run.

But remember, you normally can’t access video RAM while the PPU uses it. DMA doesn’t care! DMA has priority over all other components. And here’s the other catch, and the reason for my sudden outburst: when a DMA transfer is in progress, it takes over part of the memory.

Which part? See, this is where things get really weird. The Pan Docs — and some others — say this:

On DMG, during OAM DMA, the CPU can access only HRAM (memory at $FF80-$FFFE). For this reason, the programmer must copy a short procedure (see below) into HRAM, and use this procedure to start the transfer from inside HRAM, and wait until the transfer has finished.

Documentation about that specific topic is scarce but all the sources I’ve used to implement DMA mentioned this. So of course, I made sure that when a DMA transfer was in progress, the CPU would only be able to read and write from HRAM. Writing to any other address was ignored.

And reading from any other address? Well, the docs were unclear as to what data would be seen, so I went with a sensible default value: 0xff.

I’m still confused…

Okay, that quick digression was anything but, so let us go back to that infuriating little bit of code from earlier:

    ld a, $80                                     ; $0176: $3e $80
    ldh [rDMA], a                                 ; $0178: $e0 $46
    call Call_000_0279                            ; $017a: $cd $79 $02

Here, the program loads the value 0x80 into A, then copies it to the DMA register. This triggers a DMA transfer from 0x8000 to the OAM at 0xfe00. It’s done from the cartridge ROM, with no HRAM procedure of any kind to wait for it to complete or anything.

Which means that, from the emulator’s perspective, once DMA starts, the code no longer looks like it did above, but like this instead7:

    ld a, $80                                     ; $0176: $3e $80
    ldh [rDMA], a                                 ; $0178: $e0 $46
    rst $38                                       ; $017a: $ff
    rst $38                                       ; $017b: $ff
    rst $38                                       ; $017c: $ff

Worse yet, address 0x0038 is not in high RAM either, so during the whole DMA transfer, the CPU will only read 0xff there and jump to the same address again and again. However, DMA only lasts 160 cycles, so when it ends, the CPU finally resumes normal execution at address 0x0038. What’s even there?

RST_38::
    ld a, [$0afa]                                 ; $0038: $fa $fa $0a
    call nz, $01e0                                ; $003b: $c4 $e0 $01
    ret                                           ; $003e: $c9

Huh, that’s weird. It’s loading the byte at 0x0afa into A, then jumps to 0x01e0 if that byte is not zero. Both addresses point to the ROM itself. Whatever is at address 0x0afa is either zero or it isn’t (spoiler: it isn’t), but it shouldn’t change8 so testing its value feels strange.

But did you notice that 0x01e0 address? That’s where the crash occurred. Somewhere in that cartridge, for some reason, we are decoding a CALL instruction that jumps to a byte that a Game Boy cannot possibly execute!

Now, it’s entirely possible — and in fact quite probable — that what I have shown as assembly code above was actually just raw data in the first place. The disassembler can’t easily tell, it just translates bytes. Or maybe this could be some kind of piracy protection. But the sure thing is that the CPU should normally never get there.

Okay I get it now, so how?!

Yes, how?

So far, every bug in Goholint was obviously due to me not understanding the source material properly. But all the relevant docs I have read in the past 9 years say the same thing: the CPU can only access high RAM while a DMA transfer is in progress.

If that was actually true, then how do all the other emulators do it?

I checked the source code of a few of them. Some didn’t seem to do anything while DMA was running. I even used GameRoy to step through the beginning of Burai Fighter and confirm that the CALL at 0x017a was definitely executed. Moreover, Gekkio’s mooneye-gb suite of test ROMs includes several DMA timing tests. None of those ROMs ran on Goholint, for the same reason as above: the test code was clearly expecting at least some of the memory to be accessible even during DMA.

So, recently, I scoured the Internet again, this time looking specifically for documentation about DMA bus conflicts. I found one page describing Game Boy memory accesses and timings that mentioned how DMA took control of some part of the memory bus, but not all of it. That got me to start accepting that maybe I had been working off incorrect assumptions.

Another interesting piece of information I found was a terse reddit answer from 2016 by Gekkio himself:

The internal bus structure of Game Boy is not completely clear and there might be differences between models and/or CPU versions. But so far it looks like for OAM DMA there’s two buses that matter:

external bus: $0000-$7FFF, $A000-$FDFF
video ram bus: $8000-$9FFF

So bus conflicts happen if the CPU and OAM DMA are accessing the same bus at the same time.

This answer linked to comments on an issue in mooneye-gb’s repo that made it even clearer:

CPU is only able to access HIRAM during OAM DMA

This is a very common myth, and the truth is a lot more complicated. HIRAM is the only area which the CPU can access without any chance of conflicts. Other memory areas are still accessible but you might get a bus conflict and end up doing something unexpected.

That comment was written two years before I started writing Goholint and I only found it last month. I’m still somewhat baffled that this isn’t mentioned anywhere in modern-days Pan Docs.

And just like that, things suddenly made so much more sense!

If we go back to the beginning, we’ll see that Burai Fighter starts a DMA transfer between 0x8000 and 0xfe00. Both addresses are in video RAM! This means DMA should only need to access the video RAM bus, leaving the CPU free to access the rest of the memory and keep going about its business without reading spurious 0xff bytes and going into RST $38 cascades.

Armed with that newfound knowlegde, I was really excited to try and make it work. And maybe finally see the game run.

Gotta catch my bus!

Once again, now that I knew what the actual issue was, fixing it required surprisingly few changes to the code. I already had an object in Goholint that took care of DMA transfers and would restrict memory access while one was in progress. It sat between the CPU and the rest of the memory, and performed a simple check in its Read() and Write() methods:

// Read overrides the embedded Addressable method to only allow reading from
// high RAM if a DMA transfer is currently taking place.
func (d *DMAMemory) Read(addr uint16) uint8 {
	if d.DMA.isActive && (addr < 0xff80 || addr > 0xfffe) {
		return 0xff
	} else {
		return d.Addressable.Read(addr)
	}
}

// Write overrides the embedded Addressable method to only allow writing to high
// RAM if a DMA transfer is currently taking place.
func (d *DMAMemory) Write(addr uint16, value uint8) {
	if d.DMA.isActive && (addr < 0xff80 || addr > 0xfffe) {
		return
	} else {
		d.Addressable.Write(addr, value)
	}
}

I needed to change it so it would only block reads and writes if the target address belonged to a bus that DMA was using. I started with a simple enum to list relevant buses, and a function to return which bus was used by a given address.

// Bus identifiers returned by TargetBus. See TargetBus documentation for
// details.
type Bus int

const (
	ExternalBus Bus = iota // 0x0000-0x7fff, 0xa000-0xfdff
	VideoBus               // 0x8000-0x9fff, 0xfe00-0xfeff
	InternalBus            // 0xff00-0xffff
)

// TargetBus returns the identifier of the bus that contains the given address.
// We define the following buses based on available documentation (not 100%
// accurate but hopefully sufficient for our needs):
//
//   - External bus: 0x0000-0x7fff (ROM) and 0xa000-0xfdff (RAM + "echo" RAM)
//   - Video bus: 0x8000-0x9fff (VRAM) and 0xfe00-0xfeff (OAM)
//   - Internal bus: all other addresses (0xff00-0xffff, always reachable)
func TargetBus(addr uint16) Bus {
	switch {
	case addr < 0x8000:
		return ExternalBus
	case addr >= 0x8000 && addr < 0xa000:
		return VideoBus
	case addr >= 0xa000 && addr < 0xfe00:
		return ExternalBus
	case addr >= 0xfe00 && addr < 0xff00:
		return VideoBus
	default:
		return InternalBus
	}
}

Then it was just a matter of keeping track of which buses were involved in a DMA transfer. As I mentioned earlier, DMA always copies data to the OAM, which sits in video RAM, so that bus is always busy during DMA.

The source bus depends on which start address was written into the DMA register. I stored this in the DMA object itself whenever a transfer was started.

Finally, I simply had to compare those buses in Read() and Write():

// Read overrides the embedded Addressable method to block reads from buses that
// a DMA transfer is currently using. A DMA transfer always blocks the Video bus
// and will also block the External bus if transferring data from it.
func (d *DMAMemory) Read(addr uint16) uint8 {
	if d.DMA.isActive {
		bus := TargetBus(addr)
		if bus == VideoBus || (bus == d.DMA.srcBus) {
			return 0xff
		}
	}
	return d.Addressable.Read(addr)
}

// Write overrides the embedded Addressable method to block writes from buses that
// a DMA transfer is currently using. A DMA transfer always blocks the Video bus
// and will also block the External bus if transferring data from it.
func (d *DMAMemory) Write(addr uint16, value uint8) {
	if d.DMA.isActive {
		bus := TargetBus(addr)
		if bus == VideoBus || (bus == d.DMA.srcBus) {
			return
		}
	}
	d.Addressable.Write(addr, value)
}

And that, my friends, was enough to finally run the game9!

Might not look like much, but I've wanted to see this for literal years.

 

An animated GIF of a few seconds of gameplay where the protagonist shoots around and destroys a few enemies.
Pew pew.

So that was how. But why, tho?

In closing, I should address the elephant in the room: why even bother blocking memory while DMA is active? I could probably have just allowed any memory access regardless of DMA, and it should have worked!

Back when I first tested Burai Fighter, I actually did try that approach. It produced the same crash. I’m not sure why, because if I try disabling DMA checks in Goholint’s current code, it sure does work! My guess is that I must have had another bug back then that also caused the CPU to execute 0xff bytes, one that “got fixed at some point”, while I was working on other parts of the emulator.

Also, I really want Goholint to successfully run the full mooneye test suite someday. That includes emulating OAM corruption, which also relates to bus access conflicts, and the latest changes seemed to be a good first step in that direction.

In the end, I sort of feel silly for taking so long to find out such crucial information. Still, a game that previously didn’t run at all in my emulator now does, and if that’s not a win, I don’t know what is!

Thank you for reading!


  1. Have I mentioned it’s running Gargoyle’s Quest? I might take some small pride in that. ↩︎

  2. After a quick and shameful little fix, at least. Erm. ↩︎

  3. And since RST, like CALL, pushes the return address to the stack whenever you call it, the Game Boy also keeps attempting to write that return address across all the memory space. I’ll let you imagine how much fun it is when it writes over PPU registers. ↩︎

  4. It can still be done, using .sym files containing some metadata, but you have to provide those. I obviously didn’t have a list of the symbols from Burai Fighter. ↩︎

  5. I mean M-cycles here — a.k.a memory cycles. One M-cycle takes four T-cycles, what I’ve been calling ticks in my articles all along. For this example it’s not particularly relevant, I just want to have a number that we can easily compare. ↩︎

  6. 6 cycles to set up source and destination addresses. Then, for the first 255 iterations of the copy loop, 11 cycles for each byte copied, and for the last iteration only 10 cycles because JR Z evaluates its condition to false and does not take an extra cycle jumping back to the copy label. ↩︎

  7. Okay, technically, there is a one-cycle delay before DMA actually starts — Goholint actually implements it. But this just ends up looking like CALL $FFFF to the emulator, which jumps to 0xffff, which is also technically not in high RAM, so it reads 0xff there and gets stuck in that RST $38 loop anyway. ↩︎

  8. Actually, with the right combination of memory mapper, ROM banks and RAM banks, there is a way to map another area of a large enough ROM to the first 16KB of address space. I lost a lot of time investigating that, but Burai Fighter, while using the MBC1, is still not large enough that this could have been a possibility. ↩︎

  9. And then remember that it’s not such a great shooter in the first place. You’ll be better off playing R-Type or Parodius. At least the ring shot upgrade sounded exactly as horrible in Goholint as it did in my memory, so I’d say the game is running well! ↩︎