Compare commits

..

No commits in common. "7783c11facbd9cfc8f6faf11a2d7fee9355b9fb9" and "92417025e980296ca967991c55e5e00c53773fe3" have entirely different histories.

6 changed files with 147 additions and 277 deletions

3
.gitmodules vendored
View File

@ -7,6 +7,3 @@
[submodule "lib/known-folders"] [submodule "lib/known-folders"]
path = lib/known-folders path = lib/known-folders
url = https://github.com/ziglibs/known-folders url = https://github.com/ziglibs/known-folders
[submodule "lib/zig-datetime"]
path = lib/zig-datetime
url = https://github.com/frmdstryr/zig-datetime

View File

@ -13,12 +13,10 @@ pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions(); const mode = b.standardReleaseOptions();
const exe = b.addExecutable("zba", "src/main.zig"); const exe = b.addExecutable("zba", "src/main.zig");
// Known Folders (%APPDATA%, XDG, etc.) // Known Folders (%APPDATA%, XDG, etc.)
exe.addPackagePath("known_folders", "lib/known-folders/known-folders.zig"); exe.addPackagePath("known_folders", "lib/known-folders/known-folders.zig");
// DateTime Library
exe.addPackagePath("datetime", "lib/zig-datetime/src/main.zig");
// Bitfield type from FlorenceOS: https://github.com/FlorenceOS/ // Bitfield type from FlorenceOS: https://github.com/FlorenceOS/
// exe.addPackage(.{ .name = "bitfield", .path = .{ .path = "lib/util/bitfield.zig" } }); // exe.addPackage(.{ .name = "bitfield", .path = .{ .path = "lib/util/bitfield.zig" } });
exe.addPackagePath("bitfield", "lib/util/bitfield.zig"); exe.addPackagePath("bitfield", "lib/util/bitfield.zig");

@ -1 +0,0 @@
Subproject commit 5ec1c36cf3791b3c6c5b330357bdb6feb93979ba

View File

@ -51,7 +51,7 @@ sched: *Scheduler,
pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void { pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void {
self.* = .{ self.* = .{
.pak = try GamePak.init(allocator, cpu, paths.rom, paths.save), .pak = try GamePak.init(allocator, paths.rom, paths.save),
.bios = try Bios.init(allocator, paths.bios), .bios = try Bios.init(allocator, paths.bios),
.ppu = try Ppu.init(allocator, sched), .ppu = try Ppu.init(allocator, sched),
.apu = Apu.init(sched), .apu = Apu.init(sched),

View File

@ -1,7 +1,5 @@
const std = @import("std"); const std = @import("std");
const DateTime = @import("datetime").datetime.Datetime;
const Arm7tdmi = @import("../cpu.zig").Arm7tdmi;
const Bit = @import("bitfield").Bit; const Bit = @import("bitfield").Bit;
const Bitfield = @import("bitfield").Bitfield; const Bitfield = @import("bitfield").Bitfield;
const Backup = @import("backup.zig").Backup; const Backup = @import("backup.zig").Backup;
@ -16,7 +14,7 @@ allocator: Allocator,
backup: Backup, backup: Backup,
gpio: *Gpio, gpio: *Gpio,
pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_path: ?[]const u8) !Self { pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self {
const file = try std.fs.cwd().openFile(rom_path, .{}); const file = try std.fs.cwd().openFile(rom_path, .{});
defer file.close(); defer file.close();
@ -30,7 +28,7 @@ pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_pat
.allocator = allocator, .allocator = allocator,
.title = title, .title = title,
.backup = try Backup.init(allocator, kind, title, save_path), .backup = try Backup.init(allocator, kind, title, save_path),
.gpio = try Gpio.init(allocator, cpu, .Rtc), .gpio = try Gpio.init(allocator, .Rtc),
}; };
} }
@ -232,18 +230,23 @@ const Gpio = struct {
const Device = struct { const Device = struct {
ptr: ?*anyopaque, ptr: ?*anyopaque,
kind: Kind, // TODO: Make comptime known? // TODO: Maybe make this comptime known? Removes some if statements
kind: Kind,
const Kind = enum { Rtc, None }; const Kind = enum {
Rtc,
None,
};
fn step(self: *Device, value: u4) u4 { fn step(self: *Device, value: u4) void {
return switch (self.kind) { switch (self.kind) {
.Rtc => blk: { .Rtc => {
const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.ptr.?)); const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.ptr.?));
break :blk clock.step(Clock.Data{ .raw = value });
clock.step(Clock.GpioData{ .raw = value });
}, },
.None => value, .None => {},
}; }
} }
fn init(kind: Kind, ptr: ?*anyopaque) Device { fn init(kind: Kind, ptr: ?*anyopaque) Device {
@ -257,7 +260,7 @@ const Gpio = struct {
Control, Control,
}; };
fn init(allocator: Allocator, cpu: *Arm7tdmi, kind: Device.Kind) !*This { fn init(allocator: Allocator, kind: Device.Kind) !*This {
const self = try allocator.create(This); const self = try allocator.create(This);
self.* = .{ self.* = .{
@ -268,7 +271,7 @@ const Gpio = struct {
.device = switch (kind) { .device = switch (kind) {
.Rtc => blk: { .Rtc => blk: {
const clock = try allocator.create(Clock); const clock = try allocator.create(Clock);
clock.init(cpu, self); clock.init(self);
break :blk Device{ .kind = kind, .ptr = clock }; break :blk Device{ .kind = kind, .ptr = clock };
}, },
@ -291,13 +294,17 @@ const Gpio = struct {
} }
fn write(self: *This, comptime reg: Register, value: if (reg == .Control) u1 else u4) void { fn write(self: *This, comptime reg: Register, value: if (reg == .Control) u1 else u4) void {
log.debug("RTC: Wrote 0b{b:0>4} to {}", .{ value, reg });
// if (reg == .Data)
// log.err("original: 0b{b:0>4} masked: 0b{b:0>4} result: 0b{b:0>4}", .{ self.data, value & self.direction, self.data | (value & self.direction) });
switch (reg) { switch (reg) {
.Data => { .Data => {
const masked_value = value & self.direction; const masked_value = value & self.direction;
// The value which is actually stored in the GPIO register self.device.step(masked_value);
// might be modified by the device implementing the GPIO interface e.g. RTC reads self.data = masked_value;
self.data = self.device.step(masked_value);
}, },
.Direction => self.direction = value, .Direction => self.direction = value,
.Control => self.cnt = value, .Control => self.cnt = value,
@ -316,23 +323,22 @@ const Gpio = struct {
}; };
/// GBA Real Time Clock /// GBA Real Time Clock
pub const Clock = struct { const Clock = struct {
const This = @This(); const This = @This();
cmd: Command,
writer: Writer, writer: Writer,
reader: Reader,
state: State, state: State,
cnt: Control, cnt: Control,
year: u8, year: u8,
month: u5, month: u5,
day: u6, day: u6,
weekday: u3, day_of_week: u3,
hour: u6, hour: u6,
minute: u7, minute: u7,
second: u7, second: u7,
cpu: *Arm7tdmi,
gpio: *const Gpio, gpio: *const Gpio,
const Register = enum { const Register = enum {
@ -343,126 +349,108 @@ pub const Clock = struct {
const State = union(enum) { const State = union(enum) {
Idle, Idle,
Command, CommandInput,
Write: Register, Write: Register,
Read: Register, Read: Register,
}; };
const Reader = struct {
i: u4,
count: u8,
/// Reads a bit from RTC registers. Which bit it reads is dependent on
///
/// 1. The RTC State Machine, whitch tells us which register we're accessing
/// 2. A `count`, which keeps track of which byte is currently being read
/// 3. An index, which keeps track of which bit of the byte determined by `count` is being read
fn read(self: *Reader, clock: *const Clock, register: Register) u1 {
const idx = @intCast(u3, self.i);
defer self.i += 1;
// FIXME: What do I do about the unused bits?
return switch (register) {
.Control => @truncate(u1, switch (self.count) {
0 => clock.cnt.raw >> idx,
else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 1 byte)", .{ self.count, register }),
}),
.DateTime => @truncate(u1, switch (self.count) {
// Date
0 => clock.year >> idx,
1 => @as(u8, clock.month) >> idx,
2 => @as(u8, clock.day) >> idx,
3 => @as(u8, clock.weekday) >> idx,
// Time
4 => @as(u8, clock.hour) >> idx,
5 => @as(u8, clock.minute) >> idx,
6 => @as(u8, clock.second) >> idx,
else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 7 bytes)", .{ self.count, register }),
}),
.Time => @truncate(u1, switch (self.count) {
0 => @as(u8, clock.hour) >> idx,
1 => @as(u8, clock.minute) >> idx,
2 => @as(u8, clock.second) >> idx,
else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 3 bytes)", .{ self.count, register }),
}),
};
}
/// Is true when a Reader has read a u8's worth of bits
fn finished(self: *const Reader) bool {
return self.i >= 8;
}
/// Resets the index used to shift bits out of RTC registers
/// and `count`, which is used to keep track of which byte we're reading
/// is incremeneted
fn lap(self: *Reader) void {
self.i = 0;
self.count += 1;
}
/// Resets the state of a `Reader` in preparation for a future
/// read command
fn reset(self: *Reader) void {
self.i = 0;
self.count = 0;
}
};
const Writer = struct { const Writer = struct {
buf: u8, buf: u8,
i: u4, i: u4,
/// The Number of bytes written since last reset /// The Number of bytes written to since last reset
count: u8, count: u8,
/// Append a bit to the internal bit buffer (aka an integer)
fn push(self: *Writer, value: u1) void { fn push(self: *Writer, value: u1) void {
const idx = @intCast(u3, self.i); const idx = @intCast(u3, self.i);
self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx; self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx;
self.i += 1; self.i += 1;
} }
/// Takes the contents of the internal buffer and writes it to an RTC register
/// Where it writes to is dependent on:
///
/// 1. The RTC State Machine, whitch tells us which register we're accessing
/// 2. A `count`, which keeps track of which byte is currently being read
fn write(self: *const Writer, clock: *Clock, register: Register) void {
// FIXME: What do do about unused bits?
switch (register) {
.Control => switch (self.count) {
0 => clock.cnt.raw = (clock.cnt.raw & 0x80) | (self.buf & 0x7F), // Bit 7 read-only
else => std.debug.panic("Tried to write to byte #{} of {} (hint: there's only 1 byte)", .{ self.count, register }),
},
.DateTime, .Time => log.debug("RTC: Ignoring {} write", .{register}),
}
}
/// Is true when 8 bits have been shifted into the internal buffer
fn finished(self: *const Writer) bool {
return self.i >= 8;
}
/// Resets the internal buffer
/// resets the index used to shift bits into the internal buffer
/// increments `count` (which keeps track of byte offsets) by one
fn lap(self: *Writer) void { fn lap(self: *Writer) void {
self.buf = 0; self.buf = 0;
self.i = 0; self.i = 0;
self.count += 1; self.count += 1;
} }
/// Resets `Writer` to a clean state in preparation for a future write command
fn reset(self: *Writer) void { fn reset(self: *Writer) void {
self.buf = 0; self.buf = 0;
self.i = 0; self.i = 0;
self.count = 0; self.count = 0;
} }
fn isFinished(self: *const Writer) bool {
return self.i >= 8;
}
fn getCount(self: *const Writer) u8 {
return self.count;
}
fn getValue(self: *const Writer) u8 {
return self.buf;
}
}; };
const Data = extern union { const Command = struct {
buf: u8,
i: u4,
fn push(self: *Command, value: u1) void {
const idx = @intCast(u3, self.i);
self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx;
self.i += 1;
}
fn reset(self: *Command) void {
self.buf = 0;
self.i = 0;
}
fn isFinished(self: *const Command) bool {
return self.i >= 8;
}
fn getCommand(self: *const Command) u8 {
// If high Nybble does not contain 0x6, reverse the order of the nybbles.
// For some reason RTC commands can be LSB or MSB which is funny
return if (self.buf >> 4 & 0xF == 0x6) self.buf else (self.buf & 0xF) << 4 | (self.buf >> 4 & 0xF);
}
fn handleCommand(self: *const Command, rtc: *Clock) State {
log.info("RTC: Failed to handle Command 0b{b:0>8} aka 0x{X:0>2}", .{ self.buf, self.buf });
const command = self.getCommand();
const is_write = command & 1 == 0;
const rtc_register = @intCast(u3, command >> 1 & 0x7); // TODO: Make Truncate
if (is_write) {
return switch (rtc_register) {
0 => blk: {
rtc.reset();
break :blk .Idle;
},
1 => .{ .Write = .Control },
2 => .{ .Write = .DateTime },
3 => .{ .Write = .Time },
6 => blk: {
rtc.irq();
break :blk .Idle;
},
4, 5, 7 => .Idle,
};
} else {
return switch (rtc_register) {
1 => .{ .Read = .Control },
2 => .{ .Read = .DateTime },
3 => .{ .Read = .Time },
0, 4, 5, 6, 7 => .Idle, // Do Nothing
};
}
}
};
const GpioData = extern union {
sck: Bit(u8, 0), sck: Bit(u8, 0),
sio: Bit(u8, 1), sio: Bit(u8, 1),
cs: Bit(u8, 2), cs: Bit(u8, 2),
@ -485,196 +473,93 @@ pub const Clock = struct {
raw: u8, raw: u8,
}; };
fn init(ptr: *This, cpu: *Arm7tdmi, gpio: *const Gpio) void { fn init(ptr: *This, gpio: *const Gpio) void {
ptr.* = .{ ptr.* = .{
.cmd = .{ .buf = 0, .i = 0 },
.writer = .{ .buf = 0, .i = 0, .count = 0 }, .writer = .{ .buf = 0, .i = 0, .count = 0 },
.reader = .{ .i = 0, .count = 0 },
.state = .Idle, .state = .Idle,
.cnt = .{ .raw = 0 }, .cnt = .{ .raw = 0 },
.year = 0x01, .year = 0,
.month = 0x6, .month = 0,
.day = 0x13, .day = 0,
.weekday = 0x3, .day_of_week = 0,
.hour = 0x23, .hour = 0,
.minute = 0x59, .minute = 0,
.second = 0x59, .second = 0,
.cpu = cpu, .gpio = gpio,
.gpio = gpio, // Can't use Arm7tdmi ptr b/c not initialized yet
}; };
cpu.sched.push(.RealTimeClock, 1 << 24); // Every Second
} }
pub fn updateTime(self: *This) void { fn attachGpio(self: *This, gpio: *const Gpio) void {
self.cpu.sched.push(.RealTimeClock, 1 << 24); // Reschedule self.gpio = gpio;
const now = DateTime.now();
self.year = toBcd(u8, @intCast(u8, now.date.year - 2000));
self.month = toBcd(u5, now.date.month);
self.day = toBcd(u3, now.date.day);
self.weekday = toBcd(u3, (now.date.weekday() + 1) % 7); // API is Monday = 0, Sunday = 6. We want Sunday = 0, Saturday = 6
self.hour = toBcd(u6, now.time.hour);
self.minute = toBcd(u7, now.time.minute);
self.second = toBcd(u7, now.time.second);
} }
fn step(self: *This, value: Data) u4 { fn step(self: *This, value: GpioData) void {
const cache: Data = .{ .raw = self.gpio.data }; const cache: GpioData = .{ .raw = self.gpio.data };
return switch (self.state) { switch (self.state) {
.Idle => blk: { .Idle => {
// If SCK is high and CS rises, then prepare for Command
// FIXME: Maybe check incoming value to see if SCK is also high? // FIXME: Maybe check incoming value to see if SCK is also high?
if (cache.sck.read()) { if (cache.sck.read()) {
if (!cache.cs.read() and value.cs.read()) { if (!cache.cs.read() and value.cs.read()) {
log.debug("RTC: Entering Command Mode", .{}); log.err("RTC: Entering Command Mode", .{});
self.state = .Command; self.state = .CommandInput;
self.cmd.reset();
} }
} }
break :blk @truncate(u4, value.raw);
}, },
.Command => blk: { .CommandInput => {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state}); if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
// If SCK rises, sample SIO
if (!cache.sck.read() and value.sck.read()) { if (!cache.sck.read() and value.sck.read()) {
self.writer.push(@boolToInt(value.sio.read())); // If SCK rises, sample SIO
log.debug("RTC: Sampled 0b{b:0>1} from SIO", .{@boolToInt(value.sio.read())});
self.cmd.push(@boolToInt(value.sio.read()));
if (self.writer.finished()) { if (self.cmd.isFinished()) {
self.state = self.processCommand(self.writer.buf); self.state = self.cmd.handleCommand(self);
self.writer.reset();
log.debug("RTC: Switching to {}", .{self.state});
} }
} }
break :blk @truncate(u4, value.raw);
}, },
.Write => |register| blk: { State{ .Write = .Control } => {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state}); if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
// If SCK rises, sample SIO
if (!cache.sck.read() and value.sck.read()) { if (!cache.sck.read() and value.sck.read()) {
// If SCK rises, sample SIO
log.debug("RTC: Sampled 0b{b:0>1} from SIO", .{@boolToInt(value.sio.read())});
self.writer.push(@boolToInt(value.sio.read())); self.writer.push(@boolToInt(value.sio.read()));
const register_width: u32 = switch (register) { if (self.writer.isFinished()) {
.Control => 1,
.DateTime => 7,
.Time => 3,
};
if (self.writer.finished()) {
self.writer.write(self, register); // write inner buffer to RTC register
self.writer.lap(); self.writer.lap();
self.cnt.raw = self.writer.getValue();
if (self.writer.count == register_width) { // FIXME: Move this to a constant or something
if (self.writer.getCount() == 1) {
self.writer.reset(); self.writer.reset();
self.state = .Idle; self.state = .Idle;
} }
} }
} }
break :blk @truncate(u4, value.raw);
}, },
.Read => |register| blk: { else => {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state}); // TODO: Implement Read/Writes for Date/Time and Time and Control
var ret = value; log.err("RTC: Ignored request to handle {} command", .{self.state});
self.state = .Idle;
// if SCK rises, sample SIO
if (!cache.sck.read() and value.sck.read()) {
ret.sio.write(self.reader.read(self, register) == 0b1);
const register_width: u32 = switch (register) {
.Control => 1,
.DateTime => 7,
.Time => 3,
};
if (self.reader.finished()) {
self.reader.lap();
if (self.reader.count == register_width) {
self.reader.reset();
self.state = .Idle;
}
}
}
break :blk @truncate(u4, ret.raw);
}, },
}; }
} }
fn reset(self: *This) void { fn reset(self: *This) void {
// mGBA and NBA only zero the control register. We will do the same // mGBA and NBA only zero the control register
log.debug("RTC: Reset (control register was zeroed)", .{}); // we'll do the same
self.cnt.raw = 0; self.cnt.raw = 0;
log.info("RTC: Reset executed (control register was zeroed)", .{});
} }
fn irq(self: *This) void { fn irq(_: *const This) void {
// TODO: Confirm that this is the right behaviour // TODO: Force GamePak IRQ
log.debug("RTC: Force GamePak IRQ", .{}); log.err("RTC: TODO: Force GamePak IRQ", .{});
self.cpu.bus.io.irq.game_pak.set();
self.cpu.handleInterrupt();
}
fn processCommand(self: *This, raw_command: u8) State {
const command = blk: {
// If High Nybble is 0x6, no need to switch the endianness
if (raw_command >> 4 & 0xF == 0x6) break :blk raw_command;
// Turns out reversing the order of bits isn't trivial at all
// https://stackoverflow.com/questions/2602823/in-c-c-whats-the-simplest-way-to-reverse-the-order-of-bits-in-a-byte
var ret = raw_command;
ret = (ret & 0xF0) >> 4 | (ret & 0x0F) << 4;
ret = (ret & 0xCC) >> 2 | (ret & 0x33) << 2;
ret = (ret & 0xAA) >> 1 | (ret & 0x55) << 1;
break :blk ret;
};
log.debug("RTC: Handling Command 0x{X:0>2} [0b{b:0>8}]", .{ command, command });
const is_write = command & 1 == 0;
const rtc_register = @truncate(u3, command >> 1 & 0x7);
if (is_write) {
return switch (rtc_register) {
0 => blk: {
self.reset();
break :blk .Idle;
},
1 => .{ .Write = .Control },
2 => .{ .Write = .DateTime },
3 => .{ .Write = .Time },
6 => blk: {
self.irq();
break :blk .Idle;
},
4, 5, 7 => .Idle,
};
} else {
return switch (rtc_register) {
1 => .{ .Read = .Control },
2 => .{ .Read = .DateTime },
3 => .{ .Read = .Time },
0, 4, 5, 6, 7 => .Idle, // Do Nothing
};
}
} }
}; };
fn toBcd(comptime T: type, value: u8) T {
var input = value;
var ret: u8 = 0;
var shift: u3 = 0;
while (input > 0) {
ret |= (input % 10) << (shift << 2);
shift += 1;
input /= 10;
}
return @truncate(T, ret);
}

View File

@ -2,7 +2,6 @@ const std = @import("std");
const Bus = @import("Bus.zig"); const Bus = @import("Bus.zig");
const Arm7tdmi = @import("cpu.zig").Arm7tdmi; const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
const Clock = @import("bus/GamePak.zig").Clock;
const Order = std.math.Order; const Order = std.math.Order;
const PriorityQueue = std.PriorityQueue; const PriorityQueue = std.PriorityQueue;
@ -61,13 +60,6 @@ pub const Scheduler = struct {
3 => cpu.bus.apu.ch4.channelTimerOverflow(late), 3 => cpu.bus.apu.ch4.channelTimerOverflow(late),
} }
}, },
.RealTimeClock => {
const device = &cpu.bus.pak.gpio.device;
if (device.kind != .Rtc or device.ptr == null) return;
const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), device.ptr.?));
clock.updateTime();
},
.FrameSequencer => cpu.bus.apu.tickFrameSequencer(late), .FrameSequencer => cpu.bus.apu.tickFrameSequencer(late),
.SampleAudio => cpu.bus.apu.sampleAudio(late), .SampleAudio => cpu.bus.apu.sampleAudio(late),
.HBlank => cpu.bus.ppu.handleHBlankEnd(cpu, late), // The end of a HBlank .HBlank => cpu.bus.ppu.handleHBlankEnd(cpu, late), // The end of a HBlank
@ -126,5 +118,4 @@ pub const EventKind = union(enum) {
SampleAudio, SampleAudio,
FrameSequencer, FrameSequencer,
ApuChannel: u2, ApuChannel: u2,
RealTimeClock,
}; };