melonDS RSS https://melonds.kuribo64.net The latest news on melonDS. We're back up! -- by Arisotura https://melonds.kuribo64.net/comments.php?id=264 Fri, 23 Oct 2026 07:13:57 +0000
The recent PHP exploits prompted immediate action, considering that, well, every part of this site runs on PHP.

But now everything is fixed and good again!

My back is also recovering, so that's nice.]]>
https://melonds.kuribo64.net/comments.php?id=264
New horizons -- by Arisotura https://melonds.kuribo64.net/comments.php?id=263 Wed, 07 Oct 2026 19:11:08 +0000
Mostly, my brain needs the novelty.

But also, this may prove useful for melonDS. For example, figuring out coding styles and organization structures I like, that could address the shortcomings of melonDS.

I have to be honest, the melonDS codebase isn't in a good state. Not a state I like.

It feels like I've alienated myself (and others too) from melonDS, with all the refactoring.

There needs to be a cleaner directory structure, with subdirectories for specific parts of the core, rather than dumping everything into the src directory. You might notice I had started doing that with some of the new features (like for example DSP HLE).

The code itself needs to be cleaned up significantly, and kept consistent.

The frontend is a mess. I had begun cleaning it up, splitting specific functions to their own code files, and so on, but it's still far from being at a point where I like it.

There's the fact those tasks are just daunting. It feels demotivating to have to deal with a messy codebase, but so does trying to clean it up on the flight, when you lack an adequate plan.

So hopefully, working on something else may help me take a few steps back from melonDS and come up with a more solid plan.

There's also, of course, some of the emulator core that needs rewriting, cleanup, etc. The 3D rasterizer, the SD/MMC code, ...

Oh well.]]>
https://melonds.kuribo64.net/comments.php?id=263
blarg -- by Arisotura https://melonds.kuribo64.net/comments.php?id=262 Sun, 27 Sep 2026 20:25:13 +0000
Main reason for the lack of updates is, well, same old. Job taking up a lot of time. Emotional work taking up a bunch of the remaining time.

Desire for new projects, too. "Hey, this looks like an interesting problem, let's solve it!" - that's my brain in a nutshell.

Maybe a different emulator?

-

As far as melonDS is concerned, I'm most likely going to leave it aside until November. I'll hopefully be able to take a decision.

I atleast know what I don't want: I don't want to just abandon melonDS and leave it to whoever. At this point, it's a bit like a brand name, melonDS has a reputation within the scene... If it were to be picked up by the wrong kind of people, that could destroy its reputation.

But then again, that's life. Emulator projects come and go, like everything else.

We have DualSOUP, Jakly's attempt at cycle-accurate DS emulation. By its essence, it's already going beyond the structural limitations of melonDS. So, a very interesting project. There's potential to push the limits of DS emulation. And if it succeeds, it might even motivate a rewrite of melonDS to overcome the aforementioned structural limitations.

I think that if melonDS is to continue existing, there needs to be some changes to how it's run.

I need a way to offload the pressure I feel from this project. A way to make it not depend so much on my involvement, so that it doesn't halt if I decide to work on something else. So that I feel freer.

A way to deal with the aspects of project management I'm less good at (hi, issue and PR backlogs), so that I don't feel so much guilt from having those pile up.

I would need to expand the team, to involve the community more.

I guess I'd like to run some kind of recruitment drive. Issue is, I wouldn't know how to run such a thing. I'm not a recruiter by any means, and it's hard for me to trust other people with a project I consider mine.

I guess there would be various possible roles to fulfill. Development, whether focused more on the emulator core or on the frontend. Managing issues and PRs. User support on Discord or the forum. Managing the wiki, whenever I actually get that going. Maybe posting on this blog, too.

For now, those are just vague ideas. I most likely won't do anything of note until November. Either way, I'll keep you informed.]]>
https://melonds.kuribo64.net/comments.php?id=262
Motivation, motivation... -- by Arisotura https://melonds.kuribo64.net/comments.php?id=261 Sat, 18 Jul 2026 23:59:39 +0000
And I, well, didn't feel the desire to continue...

Maybe it's the nature of software development in itself. Unless you're working on a smaller, simpler project, you're never really done, and especially not with a project like melonDS. What started as a way to pass time has become a full commitment, in a way.

By comparison, my job has been a lot simpler, and better suited to my brain too. When you set out to repair something, it's a project with a clear end. Most of what I deal with is also fairly simple, but sometimes there are more complicated cases, requiring more time and research. For example, those HMI lamp ballasts I'm working on: they are quite complex. This has been an ongoing project for a while now.

Maybe it's the fact that the project still largely rests on my shoulders. While bigger projects like Dolphin or PCSX2 may have a bigger team and more of a workflow in place, things aren't really like that here...

I'll just quote Generic, because he put it well:
[18:55]Generìc "Yes, we can!": I think I stated this before, but how I see it melonDS never went through the professionalisation many other projects went through
[18:58]Generìc "Yes, we can!": just look at other projects (even with just a single maintainer) setting milestones, systematically "triaging" issues and so on
[19:00]Generìc "Yes, we can!": also tests
[19:01]Generìc "Yes, we can!": and throuroughly adoption of new fangled C++ features
[19:03]Generìc "Yes, we can!": if it wasn't for Nadia putting so much effort into the build system through the whole time, the codeblocks project file would still be the way to build melonDS

I feel bad about having so many issues, pull requests, etc, staying open and rotting in the backlog. At the same time, I just don't have the brain power to review every single PR alone.

And to make matters worse, now we have people submitting AI-generated code, which is problematic from several standpoints: code quality (AI tends to make a mess and not really understand what it's doing, and someone who's using AI isn't likely to understand those things any better), plagiarism, the usual ethical and environmental problems with AI too...

I like the idea of open source, but for a project of this caliber, it feels that we should have more of a system in place, with a bigger team, clearer roles... a proper organization.

One where different people with different skillsets and preferences can complement eachother. For example, while I enjoy researching the DS hardware, or figuring out why a game isn't working as it should, stuff like build systems can quickly feel very frustrating to me. As Generic put it, if it weren't for Nadia handling that work, we might not have nightly builds today, for example.

And it would be nice to have more of this... ideally, lack of involvement from me shouldn't feel like the project is stalled, like it does now.

I don't want to abandon melonDS. The project is going to be 10 years old, it's a lot of history, fun and less fun times, and I've grown to love it. At the same time, it's nice to work on other projects sometimes, and it would be nice to do so without the guilt of abandoning melonDS...

Maybe it's also the changing nature, I mean, what it's like to work on the project. The early days were a lot of hardware research, implementation, debugging; it was a lot of fun, as evidenced by the release rate I had, but I can't recapture that now. I still have ideas for melonDS features, but at this point it feels more like regular software development.

For a while, I've had the idea of adding a wiki to our site. The wiki would serve as a reference for user-facing things pertaining to melonDS: compatibility info, tutorials and FAQs for things like online play, and so on. It would also be one way to get the community involved: provided there is enough demand, we could have a sub-team dedicated to the wiki.

This became part of the bigger website work I want to do, but haven't yet had the motivation to start. I want to move the server to a better host. I want to make the blog easier to navigate, with categorization by date or by tags, maybe a search... I want to make it easier to use for those who post, too.

And it's like everything else. I have all those ideas, but it starts to feel "too much", too many big things to do, I don't know where to start and feel overwhelmed, and nothing gets done.


I've been all over the place here, but at this point I think I want to focus on one thing: trying to recruit more of the regulars into the team, and get some organization going. Or at the very least, finding ways to feel less pressure from this project...]]>
https://melonds.kuribo64.net/comments.php?id=261
Bit of plans -- by Arisotura https://melonds.kuribo64.net/comments.php?id=260 Sun, 21 Jun 2026 08:29:00 +0000
This will be for later though.

I didn't foresee how much time and energy starting this job would take me. Things are starting to even out now. Same story for my psyche, things are falling into place, but there's still work...

Anyway.

Plans.

I will try to finish the work I was doing with the new OpenGL renderer. It was mostly dealing with things like VRAM streaming, and adding a "Golden Sun hack".

I could also try and see if I can build something for 2D layer filtering, but I might postpone that.

When I'm satisfied with what I have, I'll release melonDS 1.2.

Sound good?]]>
https://melonds.kuribo64.net/comments.php?id=260
Expect slowdown -- by Arisotura https://melonds.kuribo64.net/comments.php?id=259 Sun, 10 May 2026 17:25:45 +0000
"I've been taking a bit of a break from melonDS lately... mental health reasons, a silly side project, the usual stuff."

More of the same stuff, but add to it that I've been getting started in this new job.

While it's been nice to have time to myself in order to deal with mental health matters, unemployment gets old after a while, so I was eager to finally start this job.

If you remember, I've had a foretaste of it back in December, too. I've seen my ADHD self thrive in that setting. The job is largely about repairing A/V equipment. This feels like a much better fit for my brain than a regular developer job. I like to code, but that's not all I do: I also like to build, repair things, and in general, understand how systems work (or design them). I consider code to be much of the same, but it's all inside a computer instead of being a physical object, so it lacks the "doing things with my hands" aspect.

A related example here: last year, I repaired buttons on a vacuum tube radio as part of a larger project. This is the kind of small project where I have a blast: using my brain to figure out a solution, actually implementing it with my hands, doing my best to adapt to how things actually work out... It makes me feel alive like nothing else.

But I digress. The flip side of this is that the longer work day and commute time leave me with less time at home. On the other hand, this job is a particular arrangement where I'll be working half of the year, which will definitely give me time for my personal projects, including melonDS. Just, won't be now. The first work period is going to be 6 months.

-

This also means having to balance work and mental health.

I feel better equipped to handle this, and I can envision the possibility of long term happiness. But there's still a long way to go. I also find this interesting. Probably because there's the same "figuring out how a system works" aspect, but with my own psyche. Instead of being cold logic, it's very emotion-driven.

I find the whole topic very interesting too! I would write about it (not here), I like to write about things and I feel that it could inspire other people, but I don't want to get too personal either.

-

This most likely means there won't be much progress on melonDS until November, atleast from me.

Part of me wants to figure out something for ARM9 timings. But realistically, I should focus on finishing what needs to be finished for melonDS 1.2. Polishing the OpenGL renderer. Maybe furthering the codebase cleanup. Those things.

I'll do my best.]]>
https://melonds.kuribo64.net/comments.php?id=259
A bit of a status update -- by Arisotura https://melonds.kuribo64.net/comments.php?id=258 Sun, 26 Apr 2026 17:52:24 +0000
Regardless, I've been rethinking my plans for melonDS.


I think I might postpone the timing work to melonDS 1.3. It's bigger than anticipated. I want to address some other issues, most notably finishing the new OpenGL renderer, and release melonDS 1.2. There's also some codebase cleanup I want to do.


Regarding the timing work, it's going to take some planning, and possibly a larger rework.

As I've said, the ARM7 is simple enough. Things are pretty much sequential, and the only extra complexity comes from main RAM burst termination delays.

The ARM9 is where it gets hard. We deal with mechanics like cache streaming, write buffering, ability to keep running code while the bus is in use... All sorts of mechanics which highlight the limits in melonDS's current model.


For example, take the LDM and STM instructions. They do multiple consecutive memory accesses in a row. They're commonly used to push registers to the stack and pop them back, or to quickly clear or copy large blocks of memory.

There are several issues arising from this. Depending on the base address, a LDM/STM instruction might cross the boundary between two memory regions, or two MPU regions on the ARM9. STM, when accessing I/O registers, might also cause a bus stall between two memory writes (for example, if it starts a DMA transfer...).

melonDS was built on top of a plain old interpreter. We read one instruction word from memory, we use a lookup table to figure out what we should do, we do it, then we move on to the next instruction, and so on. This model treats individual instructions as atomic: there is no way to account for all possibilities with LDM and STM, for example. Or atleast, not easily.


So an idea I have in mind is to try a different model for CPU emulation. A sort of cached interpreter.

The idea is to turn DS code into an intermediate representation which not only enables faster execution, but also gives us more freedom. For example, the aforementioned LDM/STM could be turned into discrete memory accesses, or optimized into larger accesses if possible.

Another reason would be timing calculations. Some of them, like interlocks, can be annoying to resolve, but only really need to be resolved once, so a cached interpreter could have them precalculated.

At this stage, this is only a basic idea, but it's something I want to experiment with.]]>
https://melonds.kuribo64.net/comments.php?id=258
New demo: Emulator Examination -- by Arisotura https://melonds.kuribo64.net/comments.php?id=257 Sun, 12 Apr 2026 13:25:22 +0000 Emulator Examination is a DS demo which has been released recently, and has been programmed by PoroCYon.

I figured this would be an opportunity to write about something other than CPU timings for once! But first, a video of this demo, comparing the hardware results against melonDS.



This demo bends the DS hardware in creative ways. You can read PoroCYon's writeup here, but I figured I would write about my perspective too.

First of all, this is a DSi demo, which limits the opportunities for emulator comparison. As of now, melonDS and NO$GBA are the only emulators with some degree of DSi support. The demo will still run on a DS, but you'll be limited to the first test, since this one isn't DSi-exclusive.

Now, let's see what we got here.


First, we have an eyesight test. At first, I had no real idea what was going on here. Basically, the PPU mode is changed in the middle of a scanline, which causes very specific glitches.

The interesting part is that this mirrors how hardware reverse-engineering works: doing unintended things with the hardware, observing the results and figuring out the logic behind them, can offer insight into how the hardware works beneath the surface. It can also confuse you to shit (hi, 3D GPU).

However, this effect is unlikely to ever work correctly in melonDS. Emulating it requires understanding and accurately modelling how the PPU works at a cycle level, while melonDS employs a scanline-based renderer. And since no games out there try to modify PPU registers during a scanline, there are no provisions for supporting that.

This would be right up Jakly's alley, with DualSOUP. fleroviux has done a lot of research on the GBA PPU's cycle-level operation, which will likely be helpful for this.


The second test displays an animated rainbow pattern on a monitor. What's causing melonDS to struggle so much with it?

My immediate observations were that: 1) it uses timer-driven NDMA transfers, and 2) it uses custom DSP code, hence the poor performance.

The first part wouldn't be very difficult to implement. I have never implemented this NDMA transfer mode because I haven't yet encountered a use case for them, and haven't yet gotten around to write test ROMs, but it's probably not very difficult - just not high priority.

The second part is where this stops. This is more racing-the-beam shenanigans: the DSP sets up a DMA transfer to the first entry of the BG palette, and that's how the rainbow effect is created. So even with proper support for timer-driven NDMA, it still wouldn't render properly on melonDS.


The third test simulates a basic hearing test: it produces beeps that match the little 3D animation. melonDS outputs nothing at all.

This one is cheeky. I had a feeling I knew what was going on there, and I was right.

I talked about the DSi audio hardware here. The DSi uses a TI audio amplifier slash touchscreen controller. This chip has quite a bunch of audio processing features, one of them being... making beeps. There's a bunch of registers for this: you set the desired length in samples, some values derived from the desired frequency, and it will output a sine wave.

When I looked at the console output in melonDS, I could see repeated accesses to unknown TSC registers, and sure enough, those are the beep registers.

It brings back memories: the Wii U gamepad uses a similar audio amplifier chip, and it also has those beep registers. When I started reverse-engineering the audio system there, I used those to validate that the audio amplifier was configured correctly.

Anyway, this is... interesting. On one hand, it would be interesting to try to emulate this. On the other hand, it wouldn't be terribly useful - nothing else ever uses the beep registers. But it's within the realm of what I consider feasible in melonDS.

In a similar vein, the current TSC support in melonDS is pretty lackluster, but once again, nothing ever changes the TSC configuration outside of specific situations (like entering DS mode). The TSC is configured once and everything else, like volume control, is done by other components. Even the audio frequency switch is implemented by changing the TSC input clock - none of the TSC configuration is affected.


The fourth and final test is a series of CPU tests. But wait, how could melonDS fail those so egregiously?

The DSi embeds a new wifi card based on the Atheros 6k chipset. Unlike the old DS wifi card, which is powered by a fixed-function chip, this Atheros wifi card is powered by an Xtensa CPU. Modern wifi cards work similarly: you have an embedded CPU functioning as the brain of the system, controlling the 802.11 radio, the power management systems, and the various other peripherals. This CPU runs firmware which exposes a high-level interface to the host driver, and handles all the complex low-level details.

In this case, our demo is running custom code on the wifi card's Xtensa CPU.

Hence why it's utterly and completely failing. It's interesting that they were able to even get past this test in the video-- when I tested the demo on melonDS 1.1, it would get stuck on the last subtest.

It's a bit of a shitty situation, here.

On one hand, it would be an interesting technical challenge to get this running.

On the other hand, I'm not looking forward to emulating the entire wifi card. And even if we ignore that, the DSP situation should tell you why the wifi card firmware is HLE'd.


Then we get to the credits screen, which uses more beam-racing to do a shimmer effect. Because of course.


All in all, I appreciate the display of creativity in how the hardware is used. It's always interesting to figure out how those things work.

At the same time, this shows the limits to emulation. It's a balancing act between what is fun and what is practical to do with a given approach.

For example, see the fourth test up there, the whole "running custom code on the wifi card" bit. If games were doing that on a regular basis, and with enough variety, it would make sense to emulate that entire CPU.

Compare to the DSP situation. We have low-level DSP emulation, but it's slow. Even if there could be room for optimization, there's only so much we can do when emulating an entire subsystem. On the flip side, all the games that use the DSP use a limited set of ucodes, which makes HLE feasible. The issue is that it fails to cover custom ucodes, like our demo here is using. For this, it would make sense to look into some sort of recompilation, JIT or AOT (ahead of time). While commercial games were constrained to a limited set of official ucodes, homebrew has no such limitation. HLE wouldn't be practical unless specific ucodes became common (for example, by becoming part of homebrew toolkits).

As far as the wifi card is concerned, it's a no-brainer: every game is going to use the same wifi firmware, which was already set up by the DSi firmware, so it just makes sense to HLE it.

So, basically, while there's room for improvement in melonDS, I doubt it will ever run this demo 100% correctly.]]>
https://melonds.kuribo64.net/comments.php?id=257
The timings saga, ep 2 -- by Arisotura https://melonds.kuribo64.net/comments.php?id=256 Thu, 09 Apr 2026 21:51:59 +0000
Maybe not. We can't get it 100% perfect without cycle accuracy. But we can get as close as possible, and then see how much leeway we have. It should be easier to figure this out with a more correct model. When your timing model is fundamentally inaccurate, you can tweak the numbers, but that's a game of whack-a-mole: it fixes some bugs and causes other bugs. This is what the "Enable Advanced Bus-level Timings" option in DeSmuME does. The cache timing constants in melonDS, if they could be modified by the end user, would yield similar results.

Fun fact, melonDS's current timing model is flawed. Due to a few bugs, it doesn't even work as intended. But even if it did, it would still be inaccurate.

DesperateProgrammer's cache PR, aka PR #1955, is a pretty solid base for cache emulation. I think it's a good sign that it alone has showed promising results, despite being based on the same fundamentally flawed timing model.

Anyway, enough talking. Let's see where we're at today.


So far, I'm mostly done with ARM7 timings. I've been collecting timing numbers, figuring out the logic behind those with Jakly's help (thanks there!), and implementing it. In my timing tests, melonDS yields the same numbers as hardware, so that's nice. It feels pretty satisfying when you figure out the logic and everything clicks into place.

I still need to doublecheck everything, and do actual real-world timing tests, to make sure I have everything right.

However, as far as CPU timings are concerned, the ARM7 is only the appetizer.

The timing model is fairly simple. The ARM7 doesn't have internal memory and only has one bus, and everything runs at the same frequency, so most timings are fairly straightforward.

Things get more complex when main RAM is involved.

To understand how this works, it's helpful to consider how the RAM itself works. There are atleast two possible RAM chips for the DS, as well as different, bigger RAM chips found in devkits and such. Since those are likely to have different limitations, the DS's memory controller needs to adhere to the lowest common denominator in order to ensure consistent operation.

GBAtek states that the access time for main RAM is 8 cycles, but the reality is more complicated. There is a setup time and a termination time. The former means that when accessing the RAM, there will be some latency before it begins to return data (or to accept data, when writing). At this point, it's possible to access multiple consecutive addresses in a burst. When ending a burst, there is a minimum delay before you can access the RAM again: that's the termination time.

The interesting part is that after a main RAM access, the ARM7 is free to do other things during the burst termination time, as long as it doesn't try to access main RAM again - in that case, it would have to wait.

There are also other limitations and edge cases. For example, there is a limit on how long a burst can last. In practice, though, this particular limitation only matters for DMA. On the ARM7, consecutive data fetches (ie. LDM) are limited to 16 words, which isn't enough to hit the burst limit. Code fetches can hit it under very specific circumstances which are highly unlikely to occur in real world situations. And it doesn't apply to the ARM9 at all.

That's about it, though. The other memory regions are pretty straightforward timings-wise.

There is only one thing that's really missing to ARM7-side timings, besides the holy grail of main RAM conention, and that is audio DMA. The audio hardware accesses memory periodically, either to read sample data or to write captured data. Those memory accesses will incur stalls on the ARM7, and probably on DMA too.

Audio memory accesses are done in bursts of 4 words, through the FIFO system. melonDS emulates this part already, but ignores the timing aspect of it. Emulating this bit correctly would require deeper research into how the audio hardware operates and when it accesses memory.

Of course, I don't know how truly important it is, but it's worth keeping in mind. There are also several timing-related issues on the ARM7 side in DSi mode: the faster SPI clock isn't supported yet, timings for SD transfers are a big fat guess, I2C transfers and AES operations are instant.


So now, let's get to the main course: the ARM9.

The ARM9 is much more important, since that's where all the game logic runs. It's also more complex.

I've been banging my head against the numbers I've collected from my timing tests, trying to figure out the logic behind them. Jakly has been very helpful here, too.

Atleast, we've figured out the logic behind memory read instructions. It appears that the ARM9 can try to initiate the next code fetch early, but this doesn't always work as intended - sometimes resulting in weird extra latency, because every bus access must go through buffering.

The ARM9 also introduces us to interlocks.

For example, if you run a LDR instruction (32-bit memory read) on the ARM7, the CPU will retrieve the data from memory, then spend one more cycle storing that data into the desired register.

The ARM9 works the same way, except it will attempt to save time by starting the next instruction before LDR is actually done storing its result. But what if the next instruction tries to use the same register that LDR is supposed to write to? That's an interlock - this next instruction will need to wait for LDR to actually finish.

This is something that will need a great deal of testing. Supposedly, the ARM9 has "fast paths" meant to avoid interlocks in certain situations, so we need to figure out where this applies.

Also, fun observation: sometimes the ARM9 is just as hacky as the rest of the console!

Take LDRD, for example. This is a new instruction that has been added to the ARM9. It functions as a 64-bit memory read: it reads two words from memory to a pair of registers.

I have observed LDRD's timing characteristic long and hard, and it is evident to me that LDRD is basically LDR with a second memory read duct-taped at the end. This also means that the second memory read is nonsequential, which makes it inefficient.

By comparison, its counterpart STRD (64-bit memory write) seems more sane.

In general, all the memory write instructions seem sane - they don't have to worry about interlocks. I think the rest isn't too difficult - the instructions that don't touch memory are pretty straightforward. I haven't yet looked into the CP15 (system coprocessor) operations, though.

The issue with the ARM9 is going to be everything pertaining to memory. The caches. The separate busses. All that. For example, the ARM9 can continue running during a DMA transfer as long as it doesn't try to use the external bus. melonDS's very crude implementation of bus stalls doesn't support that.


This also brings me to the JIT.

At this point, it's a balancing act. There is a feeling that the JIT hinders further accuracy improvements. Understandable... the JIT is fundamentally inaccurate. To get a speed benefit, the JIT needs to operate on large enough code blocks, which doesn't mesh well with the way melonDS's scheduler works.

On the other hand, it seems pretty evident to me that removing the JIT would be massively unpopular. I'm against it.

I need to get more familar with the JIT's inner workings. At this point, I know the basic idea of how a JIT works, but I've never actually written one, which is a bit ironic for someone in my position.

What interests me is to see how far we can go with timings in the JIT. I imagine that a lot of the overall CPU timing model could be handled at compile time. On the other hand, I don't think emulating the ARM9 caches in the JIT would work terribly well, performance wise. This makes me wonder how much performance there would be to gain from a cached interpreter approach.

Food for thought.]]>
https://melonds.kuribo64.net/comments.php?id=256
Actual status update on timings -- by Arisotura https://melonds.kuribo64.net/comments.php?id=255 Thu, 02 Apr 2026 14:49:28 +0000
Timings work is underway. I'm mostly done collecting numbers, minus stuff like CP15 operations and any special cases that might crop up. I started fixing up ARM7 timings.

Thing is, timings work isn't always easy. Collecting timing numbers is one thing, understanding the logic behind them is another thing entirely. Geometry engine timings, which I've worked on years ago, are a prime example of this: when you submit a display list to the geometry engine, the total execution time isn't simply the sum of each command's execution time. The reason for this is that the geometry engine has a pipeline: it can execute certain commands in parallel. It took me a lot of testing and number collecting to understand the logic behind it.

If the geometry engine, a simple 3D command processor, is already like that, you can imagine what a full-fledged CPU is going to be like. This is why CPU timings are an area of melonDS that has been more or less neglected for so long.

On the flip side, the DS isn't like older consoles such as the GameBoy or the NES, where games might rely on very precise timings in order to get the best out of the system's limited power, and they might crash if a certain event occurs 2 cycles too late. On the DS, from what I've seen, it's more about timings at the macro level, ie. how long a bigger operation takes. For example, consider a DMA transfer to copy a screen-sized bitmap, that is, 24576 words. A difference of 1 cycle in the initial DMA setup time doesn't matter, but a difference of 1 cycle per word transferred quickly adds up. Like here.


So, what are ARM7 timings like?

The ARM7 has a 3-stage pipeline, which means it can execute an instruction while decoding the next one and fetching the one after. So, for a lot of instructions, the execution time is capped by the access time for the memory region we're executing from. Some instructions may need more cycles to execute. Load and store instructions are also particular, since they access memory.

Different memory regions have different access times, depending on their data bus width and the type of memory access. Most of the available memory regions are integrated into the DS SoC, so they can be accessed in one cycle. VRAM has a 16-bit bus, so 32-bit accesses are broken into two 16-bit accesses and take two cycles.

External memory, however, has its own rules. There is a notion of nonsequential and sequential accesses. Basically, the memory being accessed may require a setup time for an initial access, but may be able to chain subsequent accesses in a faster way. The ARM7 makes use of this when fetching code: as long as a given instruction doesn't require extra cycles, the next one may be fetched in a sequential memory access, resulting in faster execution. Instructions like LDM and STM, which can load or store several words in a row, also make use of this.

Rules for the GBA slot ROM region are simple: the nonsequential and sequential access times are configured in EXMEMCNT. The data bus is 16-bit, so 32-bit accesses are broken down into two 16-bit accesses, where the second one is always sequential. The wifi card uses a similar interface, so the rules are the same.

Main RAM, however, is more complicated. To understand how the timings there work, you have to know how those RAM chips operate.

I mentioned my little Wii U gamepad project before, and it's relevant here: it involves a FPGA-based SPI FLASH emulator, which uses SDRAM to store firmware code. I first tried using spispy, but since it wasn't up to the task, I ended up making my own - including a simple SDRAM controller.

The DS and DSi use FCRAM, which is a bit different: from my understanding, you address FCRAM by sending the full address in one go, instead of having to send separate row and column addresses. Besides that, FCRAM seems to work in a fairly similar way.

For example, SDRAM supports burst modes: you send the address once and access several data units in a row (in my case, 16-bit units). Since burst accesses are typically constrained to a given memory block (which appears to be 32 bytes for the DS), a smart memory controller needs to know when to prepare the next burst ahead of time. There is also a delay to terminating a burst.

Furthermore, the DS also seems to have a hard limit on how long a main RAM burst can last. Presumably, since main RAM is shared, this serves to avoid having one side hogging it for too long.

So basically, when main RAM is involved, access times aren't just a matter of "how long does this particular access takes", the context around it has to be taken into consideration to some extent.


There is also, of course, the issue of main RAM contention: basically, when both ARM9 and ARM7 are trying to access main RAM at the same time, the memory controller will delay priorize one of the two, based on the EXMEMCNT priority setting. In practice, this setting seems to always be set to give priority to the ARM7.

The issue here is apparent if you consider how melonDS works. Basically, execution is split into bursts. The scheduler determines how long a burst should last: the length is based on the time until the next scheduled event, and capped at 64 cycles. The ARM9 is run for this many cycles, then the ARM7 is run until it has caught up, then scheduled events are executed if needed; rinse and repeat.

It is less accurate than running everything in a tight lockstep, but it's also way more efficient. In practice, DS games don't rely on extremely tight synchronization between the two CPUs, so doing things this way is fine.

However, it makes it impossible to model things such as main RAM contention. There is simply no way to tell whether the two CPUs are going to be accessing main RAM at the same time. It could be estimated based on heuristics, but that would be a big fat hack.

In practice, I don't yet know if anything relies on main RAM contention, besides the infamous DSi menu loader. That's a bit of a special case, since the ARM9 runs with caches off, and the two CPUs are actively competing for main RAM access. In most games, the ARM7 runs its code from internal WRAM, and the ARM9 has caches; however caches aren't perfect, and the sound hardware may be accessing main RAM too. I don't know how much main RAM contention matters in games, given this.


Then, since we're talking about the ARM9, there's this too.

Timings there are even more complicated. First, the ARM9 runs at 67 MHz, or 134 MHz on the DSi, but the bus still runs at 33 MHz. This means that when the ARM9 needs to access any memory outside of its own caches and TCM, additional delays are incurred: in hardware terms, crossing clock domains requires additional buffering.

Atleast, from what I've observed, setting the ARM9 clock to 67 MHz on the DSi yields identical timings to the DS, so there's that. However, setting it to 134 MHz results in several differences, so I have to figure out the logic behind that.

Then, the ARM9 is also a more complex beast in itself.

The caches can greatly help performance, considering how slow main RAM is. However, they also add complexity to the overall timings. For example, upon a cache miss, an entire cache line needs to be loaded, however the CPU may continue running while this happens, as long as it doesn't try to use the bus. That's what they call cache streaming. There's also a write buffer, which has its own mechanics too.

The ARM9 also has a longer pipeline, with 5 stages. This means some instructions may need more time to properly write their results to the CPU registers. Jakly said that there are special paths where a given instruction may send its result to the next instruction early if needed, but this doesn't cover every possible case.

For example, take the QADD instruction. It's a signed 32-bit addition with a sticky overflow flag. This instruction takes 1 cycle to execute, however it needs one extra cycle to actually write back its result to the destination register. So if the next instruction tries to use that register, it needs to wait one extra cycle.

I don't know all the details there. Jakly is more knowledgeable than I am, so I'll probably be relying on her to help figure out all the logic. The challenge is to implement it in a way that doesn't result in overbearing complexity and is optimizable to some extent.


As I said, at this point, I'm fixing up ARM7 timings. According to my tests, melonDS wasn't that far off, but the ARM7 still needs some fixes. I'll also need a lot more testing, in real world situations, not just specific instruction sequences repeated many times.

We'll also have to see what to do with the JIT. Surely, a lot of the overall timing model can be precomputed when compiling code blocks, so the JIT would have a decent advantage there. But I'm not sure about the more dynamic things, like the ARM9 caches. I'll have to see with Generic. But not before I've fininshed making all this work in the interpreter.

All in all, fun shit.]]>
https://melonds.kuribo64.net/comments.php?id=255