Skip to content

Commit

Permalink
[gba] cpu: Do not postpone timer IRQs, fixes nba-emu#40.
Browse files Browse the repository at this point in the history
  • Loading branch information
Frederic Meyer committed Aug 3, 2019
1 parent a6abea9 commit 28effa9
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 5 deletions.
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ set(COMPILE_FLAGS "${COMPILE_FLAGS} -Ofast")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COMPILE_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS} -std=c++1z")

#add_definitions(-pg)
#set(CMAKE_EXE_LINKER_FLAGS -pg)

add_subdirectory(src)
9 changes: 5 additions & 4 deletions src/gba/cpu/cpu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include "cpu.hpp"

#include <algorithm>
#include <climits>
#include <cstring>

Expand Down Expand Up @@ -143,10 +144,10 @@ void CPU::RunFor(int cycles) {
cpu.SignalIrq();
cpu.Run();
} else {
/* TODO: inaccurate due to timer interrupts. */
timers.Run(ticks_cpu_left);
ticks_cpu_left = 0;
break;
int advance = std::min(timers.GetCyclesUntilIrq(), ticks_cpu_left);

timers.Run(advance);
ticks_cpu_left -= advance;
}
}

Expand Down
20 changes: 20 additions & 0 deletions src/gba/cpu/timer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
#include "cpu.hpp"
#include "timer.hpp"

#include <climits>

using namespace GameBoyAdvance;

static constexpr int g_ticks_shift[4] = { 0, 6, 8, 10 };
Expand Down Expand Up @@ -92,6 +94,24 @@ void TimerController::RunFIFO(int id, int times) {
}
}

auto TimerController::GetCyclesUntilIrq() -> int {
int cycles = INT_MAX;

for (auto const& timer : this->timer) {
if (timer.control.interrupt &&
timer.control.enable &&
!timer.control.cascade)
{
int required = ((0x10000 - timer.counter) << timer.shift) - timer.cycles;

if (required < cycles)
cycles = required;
}
}

return cycles;
}

auto TimerController::Read(int id, int offset) -> std::uint8_t {
switch (offset) {
case 0: {
Expand Down
3 changes: 2 additions & 1 deletion src/gba/cpu/timer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class TimerController {

void Reset();
void Run(int cycles);
auto GetCyclesUntilIrq() -> int;
auto Read(int id, int offset) -> std::uint8_t;
void Write(int id, int offset, std::uint8_t value);

Expand All @@ -39,7 +40,7 @@ class TimerController {
void RunFIFO(int id, int times);

CPU* cpu;

struct Timer {
int id;

Expand Down

0 comments on commit 28effa9

Please sign in to comment.