From 434a0dfac9e756433028847e58ea4263cccb706c Mon Sep 17 00:00:00 2001 From: paoda Date: Fri, 19 Aug 2022 00:25:30 +0200 Subject: [PATCH 01/14] tmp: incomplete impl of GPIO + RTC --- src/core/bus/GamePak.zig | 416 ++++++++++++++++++++++++++++++++++++++- src/main.zig | 1 + 2 files changed, 408 insertions(+), 9 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index b208f75..0908ee3 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -1,5 +1,7 @@ const std = @import("std"); +const Bit = @import("bitfield").Bit; +const Bitfield = @import("bitfield").Bitfield; const Backup = @import("backup.zig").Backup; const Allocator = std.mem.Allocator; const log = std.log.scoped(.GamePak); @@ -10,6 +12,7 @@ title: [12]u8, buf: []u8, allocator: Allocator, backup: Backup, +gpio: Gpio, pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self { const file = try std.fs.cwd().openFile(rom_path, .{}); @@ -19,17 +22,36 @@ pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) const title = parseTitle(file_buf); const kind = Backup.guessKind(file_buf) orelse .None; - const pak = Self{ + var pak = Self{ .buf = file_buf, .allocator = allocator, .title = title, .backup = try Backup.init(allocator, kind, title, save_path), + .gpio = Gpio.init(allocator, .Rtc), }; pak.parseHeader(); return pak; } +/// Configures any GPIO Device that may be enabled +/// +/// Fundamentally, this just passes a pointer to the initialized GPIO struct to whatever heap allocated GPIO Device struct +/// we happen to be using +/// +/// WARNIG: As far as I know, this method must be called in main() or else we'll have a dangling pointer issue +/// Despite using the General Purpose Allocator, Zig doesn't prevent me from doing this :sadface: +pub fn setupGpio(self: *Self) void { + switch (self.gpio.device.kind) { + .Rtc => { + const ptr = self.gpio.device.ptr orelse @panic("RTC ptr is missing despite GPIO Device Kind"); + const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr)); + Clock.init(clock, &self.gpio); + }, + .None => {}, + } +} + fn parseHeader(self: *const Self) void { const title = parseTitle(self.buf); const code = self.buf[0xAC..0xB0]; @@ -60,6 +82,7 @@ inline fn isLarge(self: *const Self) bool { pub fn deinit(self: *Self) void { self.backup.deinit(); + self.gpio.deinit(self.allocator); self.allocator.free(self.buf); self.* = undefined; } @@ -83,6 +106,35 @@ pub fn read(self: *Self, comptime T: type, address: u32) T { } } + if (self.gpio.cnt == 1) { + // GPIO Can be read from + // We assume that this will only be true when a ROM actually does want something from GPIO + + switch (T) { + u32 => switch (address) { + // TODO: Do I even need to implement these? + 0x0800_00C4 => std.debug.panic("Handle 32-bit GPIO Data/Direction Reads", .{}), + 0x0800_00C6 => std.debug.panic("Handle 32-bit GPIO Direction/Control Reads", .{}), + 0x0800_00C8 => std.debug.panic("Handle 32-bit GPIO Control Reads", .{}), + else => {}, + }, + u16 => switch (address) { + // FIXME: What do 16-bit GPIO Reads look like? + 0x0800_00C4 => return self.gpio.read(.Data), + 0x0800_00C6 => return self.gpio.read(.Direction), + 0x0800_00C8 => return self.gpio.read(.Control), + else => {}, + }, + u8 => switch (address) { + 0x0800_00C4 => return self.gpio.read(.Data), + 0x0800_00C6 => return self.gpio.read(.Direction), + 0x0800_00C8 => return self.gpio.read(.Control), + else => {}, + }, + else => @compileError("GamePak[GPIO]: Unsupported read width"), + } + } + return switch (T) { u32 => (@as(T, self.get(addr + 3)) << 24) | (@as(T, self.get(addr + 2)) << 16) | (@as(T, self.get(addr + 1)) << 8) | (@as(T, self.get(addr))), u16 => (@as(T, self.get(addr + 1)) << 8) | @as(T, self.get(addr)), @@ -141,17 +193,23 @@ pub fn write(self: *Self, comptime T: type, word_count: u16, address: u32, value switch (T) { u32 => switch (address) { - 0x0800_00C4 => log.debug("Wrote {} 0x{X:} to I/O Port Data and Direction", .{ T, value }), - 0x0800_00C6 => log.debug("Wrote {} 0x{X:} to I/O Port Direction and Control", .{ T, value }), - else => {}, + 0x0800_00C4 => { + self.gpio.write(.Data, @truncate(u4, value)); + self.gpio.write(.Direction, @truncate(u4, value >> 16)); + }, + 0x0800_00C6 => { + self.gpio.write(.Direction, @truncate(u4, value)); + self.gpio.write(.Control, @truncate(u1, value >> 16)); + }, + else => log.err("Wrote {} 0x{X:0>8} to 0x{X:0>8}, Unhandled", .{ T, value, address }), }, u16 => switch (address) { - 0x0800_00C4 => log.debug("Wrote {} 0x{X:} to I/O Port Data", .{ T, value }), - 0x0800_00C6 => log.debug("Wrote {} 0x{X:} to I/O Port Direction", .{ T, value }), - 0x0800_00C8 => log.debug("Wrote {} 0x{X:} to I/O Port Control", .{ T, value }), - else => {}, + 0x0800_00C4 => self.gpio.write(.Data, @truncate(u4, value)), + 0x0800_00C6 => self.gpio.write(.Direction, @truncate(u4, value)), + 0x0800_00C8 => self.gpio.write(.Control, @truncate(u1, value)), + else => log.err("Wrote {} 0x{X:0>4} to 0x{X:0>8}, Unhandled", .{ T, value, address }), }, - u8 => log.debug("Wrote {} 0x{X:} to 0x{X:0>8}, Ignored.", .{ T, value, address }), + u8 => log.debug("Wrote {} 0x{X:0>2} to 0x{X:0>8}, Ignored.", .{ T, value, address }), else => @compileError("GamePak: Unsupported write width"), } } @@ -183,3 +241,343 @@ test "OOB Access" { std.debug.assert(pak.get(4) == 0x02); // 0x0002 std.debug.assert(pak.get(5) == 0x00); } + +/// GPIO Register Implementation +const Gpio = struct { + const This = @This(); + + data: u4, + direction: u4, + cnt: u1, + + device: Device, + + const Device = struct { + ptr: ?*anyopaque, + // TODO: Maybe make this comptime known? Removes some if statements + kind: Kind, + + const Kind = enum { + Rtc, + None, + }; + + fn step(self: *Device, value: u4) void { + switch (self.kind) { + .Rtc => { + const ptr = self.ptr orelse @panic("Device.ptr should != null when Device.kind == .Rtc"); + const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr)); + + clock.step(Clock.GpioData{ .raw = value }); + }, + .None => {}, + } + } + + fn init(kind: Kind, ptr: ?*anyopaque) Device { + return .{ .kind = kind, .ptr = ptr }; + } + }; + + const Register = enum { + Data, + Direction, + Control, + }; + + fn init(allocator: Allocator, kind: Device.Kind) This { + return .{ + .data = 0b0000, + .direction = 0b1111, // TODO: What is GPIO Direction set to by default? + .cnt = 0b0, + + .device = switch (kind) { + .Rtc => blk: { + const ptr = allocator.create(Clock) catch @panic("Failed to allocate RTC struct on heap"); + break :blk Device{ .kind = kind, .ptr = ptr }; + }, + .None => Device{ .kind = kind, .ptr = null }, + }, + }; + } + + fn deinit(self: This, allocator: Allocator) void { + switch (self.device.kind) { + .Rtc => { + const ptr = self.device.ptr orelse @panic("Device.ptr should != null when Device.kind == .Rtc"); + allocator.destroy(@ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr))); + }, + .None => {}, + } + } + + 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) { + .Data => { + const masked_value = value & self.direction; + + self.device.step(masked_value); + self.data = masked_value; + }, + .Direction => self.direction = value, + .Control => self.cnt = value, + } + } + + fn read(self: *const This, comptime reg: Register) if (reg == .Control) u1 else u4 { + if (self.cnt == 0) return 0; + + return switch (reg) { + .Data => self.data & ~self.direction, + .Direction => self.direction, + .Control => self.cnt, + }; + } +}; + +/// GBA Real Time Clock +const Clock = struct { + const This = @This(); + + cmd: Command, + writer: Writer, + state: State, + cnt: Control, + + year: u8, + month: u5, + day: u6, + day_of_week: u3, + hour: u6, + minute: u7, + second: u7, + + gpio: *const Gpio, + + const Register = enum { + Control, + DateTime, + Time, + }; + + const State = union(enum) { + Idle, + CommandInput, + Write: Register, + Read: Register, + }; + + const Writer = struct { + buf: u8, + i: u4, + + /// The Number of bytes written to since last reset + count: u8, + + fn push(self: *Writer, 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 lap(self: *Writer) void { + self.buf = 0; + self.i = 0; + self.count += 1; + } + + fn reset(self: *Writer) void { + self.buf = 0; + self.i = 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 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(u4, 0), + sio: Bit(u4, 1), + cs: Bit(u4, 2), + raw: u4, + }; + + const Control = extern union { + /// Unknown, value should be preserved though + unk: Bit(u8, 1), + /// Per-minute IRQ + /// If set, fire a Gamepak IRQ every 30s, + irq: Bit(u8, 3), + /// 12/24 Hour Bit + /// If set, 12h mode + /// If cleared, 24h mode + mode: Bit(u8, 6), + /// Read-Only, bit cleared on read + /// If is set, means that there has been a failure / time has been lost + off: Bit(u8, 7), + raw: u8, + }; + + fn init(ptr: *This, gpio: *const Gpio) void { + ptr.* = .{ + .cmd = .{ .buf = 0, .i = 0 }, + .writer = .{ .buf = 0, .i = 0, .count = 0 }, + .state = .Idle, + .cnt = .{ .raw = 0 }, + .year = 0, + .month = 0, + .day = 0, + .day_of_week = 0, + .hour = 0, + .minute = 0, + .second = 0, + .gpio = gpio, + }; + } + + fn attachGpio(self: *This, gpio: *const Gpio) void { + self.gpio = gpio; + } + + fn step(self: *This, value: GpioData) void { + const cache: GpioData = .{ .raw = self.gpio.data }; + + switch (self.state) { + .Idle => { + // If SCK is high and CS rises, then prepare for Command + // FIXME: Maybe check incoming value to see if SCK is also high? + if (cache.sck.read()) { + if (!cache.cs.read() and value.cs.read()) { + log.err("RTC: Entering Command Mode", .{}); + self.state = .CommandInput; + self.cmd.reset(); + } + } + }, + .CommandInput => { + if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state}); + + 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.cmd.push(@boolToInt(value.sio.read())); + + if (self.cmd.isFinished()) { + self.state = self.cmd.handleCommand(self); + } + } + }, + State{ .Write = .Control } => { + if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state}); + + 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())); + + if (self.writer.isFinished()) { + self.writer.lap(); + self.cnt.raw = self.writer.getValue(); + + // FIXME: Move this to a constant or something + if (self.writer.getCount() == 1) { + self.writer.reset(); + self.state = .Idle; + } + } + } + }, + else => { + // TODO: Implement Read/Writes for Date/Time and Time and Control + log.err("RTC: Ignored request to handle {} command", .{self.state}); + self.state = .Idle; + }, + } + } + + fn reset(self: *This) void { + // mGBA and NBA only zero the control register + // we'll do the same + self.cnt.raw = 0; + log.info("RTC: Reset executed (control register was zeroed)", .{}); + } + + fn irq(_: *const This) void { + // TODO: Force GamePak IRQ + log.err("RTC: TODO: Force GamePak IRQ", .{}); + } +}; diff --git a/src/main.zig b/src/main.zig index 100eed8..7b1a6cb 100644 --- a/src/main.zig +++ b/src/main.zig @@ -52,6 +52,7 @@ pub fn main() anyerror!void { if (paths.bios == null) cpu.fastBoot(); try bus.init(allocator, &scheduler, &cpu, paths); + bus.pak.setupGpio(); // FIXME: Can I not call this in main()? defer bus.deinit(); var gui = Gui.init(bus.pak.title, width, height); From 617f7f469060c620d163ff93cc0491998f1ae05c Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Mon, 5 Sep 2022 01:37:33 -0300 Subject: [PATCH 02/14] fix: update GpioData extern union u4's are no longer supported in extern unions :\ --- src/core/bus/GamePak.zig | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 0908ee3..3193e05 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -469,10 +469,10 @@ const Clock = struct { }; const GpioData = extern union { - sck: Bit(u4, 0), - sio: Bit(u4, 1), - cs: Bit(u4, 2), - raw: u4, + sck: Bit(u8, 0), + sio: Bit(u8, 1), + cs: Bit(u8, 2), + raw: u8, }; const Control = extern union { From 1c52c0bf91ff9392e615031b8dc8fbe256d8fd55 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 9 Sep 2022 18:25:02 -0300 Subject: [PATCH 03/14] chore: shorten `orelse @panic` to `.?` --- src/core/bus/GamePak.zig | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 3193e05..893101b 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -44,8 +44,7 @@ pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) pub fn setupGpio(self: *Self) void { switch (self.gpio.device.kind) { .Rtc => { - const ptr = self.gpio.device.ptr orelse @panic("RTC ptr is missing despite GPIO Device Kind"); - const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr)); + const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.gpio.device.ptr.?)); Clock.init(clock, &self.gpio); }, .None => {}, @@ -265,8 +264,7 @@ const Gpio = struct { fn step(self: *Device, value: u4) void { switch (self.kind) { .Rtc => { - const ptr = self.ptr orelse @panic("Device.ptr should != null when Device.kind == .Rtc"); - const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr)); + const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.ptr.?)); clock.step(Clock.GpioData{ .raw = value }); }, @@ -304,8 +302,7 @@ const Gpio = struct { fn deinit(self: This, allocator: Allocator) void { switch (self.device.kind) { .Rtc => { - const ptr = self.device.ptr orelse @panic("Device.ptr should != null when Device.kind == .Rtc"); - allocator.destroy(@ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr))); + allocator.destroy(@ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.device.ptr.?))); }, .None => {}, } From 92417025e980296ca967991c55e5e00c53773fe3 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 02:10:20 -0300 Subject: [PATCH 04/14] fix: properly resovle stack UAF --- src/core/bus/GamePak.zig | 63 +++++++++++++++------------------------- src/main.zig | 1 - 2 files changed, 24 insertions(+), 40 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 893101b..383d5c0 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -12,50 +12,30 @@ title: [12]u8, buf: []u8, allocator: Allocator, backup: Backup, -gpio: Gpio, +gpio: *Gpio, pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self { const file = try std.fs.cwd().openFile(rom_path, .{}); defer file.close(); const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos()); - const title = parseTitle(file_buf); + const title = file_buf[0xA0..0xAC].*; const kind = Backup.guessKind(file_buf) orelse .None; + logHeader(file_buf, &title); - var pak = Self{ + return .{ .buf = file_buf, .allocator = allocator, .title = title, .backup = try Backup.init(allocator, kind, title, save_path), - .gpio = Gpio.init(allocator, .Rtc), + .gpio = try Gpio.init(allocator, .Rtc), }; - pak.parseHeader(); - - return pak; } -/// Configures any GPIO Device that may be enabled -/// -/// Fundamentally, this just passes a pointer to the initialized GPIO struct to whatever heap allocated GPIO Device struct -/// we happen to be using -/// -/// WARNIG: As far as I know, this method must be called in main() or else we'll have a dangling pointer issue -/// Despite using the General Purpose Allocator, Zig doesn't prevent me from doing this :sadface: -pub fn setupGpio(self: *Self) void { - switch (self.gpio.device.kind) { - .Rtc => { - const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.gpio.device.ptr.?)); - Clock.init(clock, &self.gpio); - }, - .None => {}, - } -} - -fn parseHeader(self: *const Self) void { - const title = parseTitle(self.buf); - const code = self.buf[0xAC..0xB0]; - const maker = self.buf[0xB0..0xB2]; - const version = self.buf[0xBC]; +fn logHeader(buf: []const u8, title: *const [12]u8) void { + const code = buf[0xAC..0xB0]; + const maker = buf[0xB0..0xB2]; + const version = buf[0xBC]; log.info("Title: {s}", .{title}); if (version != 0) log.info("Version: {}", .{version}); @@ -63,10 +43,6 @@ fn parseHeader(self: *const Self) void { if (lookupMaker(maker)) |c| log.info("Maker: {s}", .{c}) else log.info("Maker Code: {s}", .{maker}); } -fn parseTitle(buf: []u8) [12]u8 { - return buf[0xA0..0xAC].*; -} - fn lookupMaker(slice: *const [2]u8) ?[]const u8 { const id = @as(u16, slice[1]) << 8 | @as(u16, slice[0]); return switch (id) { @@ -82,6 +58,7 @@ inline fn isLarge(self: *const Self) bool { pub fn deinit(self: *Self) void { self.backup.deinit(); self.gpio.deinit(self.allocator); + self.allocator.destroy(self.gpio); self.allocator.free(self.buf); self.* = undefined; } @@ -283,29 +260,37 @@ const Gpio = struct { Control, }; - fn init(allocator: Allocator, kind: Device.Kind) This { - return .{ + fn init(allocator: Allocator, kind: Device.Kind) !*This { + const self = try allocator.create(This); + + self.* = .{ .data = 0b0000, - .direction = 0b1111, // TODO: What is GPIO Direction set to by default? + .direction = 0b1111, // TODO: What is GPIO DIrection set to by default? .cnt = 0b0, .device = switch (kind) { .Rtc => blk: { - const ptr = allocator.create(Clock) catch @panic("Failed to allocate RTC struct on heap"); - break :blk Device{ .kind = kind, .ptr = ptr }; + const clock = try allocator.create(Clock); + clock.init(self); + + break :blk Device{ .kind = kind, .ptr = clock }; }, .None => Device{ .kind = kind, .ptr = null }, }, }; + + return self; } - fn deinit(self: This, allocator: Allocator) void { + fn deinit(self: *This, allocator: Allocator) void { switch (self.device.kind) { .Rtc => { allocator.destroy(@ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.device.ptr.?))); }, .None => {}, } + + self.* = undefined; } fn write(self: *This, comptime reg: Register, value: if (reg == .Control) u1 else u4) void { diff --git a/src/main.zig b/src/main.zig index 7b1a6cb..100eed8 100644 --- a/src/main.zig +++ b/src/main.zig @@ -52,7 +52,6 @@ pub fn main() anyerror!void { if (paths.bios == null) cpu.fastBoot(); try bus.init(allocator, &scheduler, &cpu, paths); - bus.pak.setupGpio(); // FIXME: Can I not call this in main()? defer bus.deinit(); var gui = Gui.init(bus.pak.title, width, height); From c977f3f965da21f309132cb068c316030ee82af7 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 03:54:44 -0300 Subject: [PATCH 05/14] feat: implement force irqs for GPIO/RTC --- src/core/Bus.zig | 2 +- src/core/bus/GamePak.zig | 39 ++++++++++++++++++++------------------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/core/Bus.zig b/src/core/Bus.zig index 2a89e72..893b9bf 100644 --- a/src/core/Bus.zig +++ b/src/core/Bus.zig @@ -51,7 +51,7 @@ sched: *Scheduler, pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void { self.* = .{ - .pak = try GamePak.init(allocator, paths.rom, paths.save), + .pak = try GamePak.init(allocator, cpu, paths.rom, paths.save), .bios = try Bios.init(allocator, paths.bios), .ppu = try Ppu.init(allocator, sched), .apu = Apu.init(sched), diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 383d5c0..2f8934f 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -1,5 +1,6 @@ const std = @import("std"); +const Arm7tdmi = @import("../cpu.zig").Arm7tdmi; const Bit = @import("bitfield").Bit; const Bitfield = @import("bitfield").Bitfield; const Backup = @import("backup.zig").Backup; @@ -14,7 +15,7 @@ allocator: Allocator, backup: Backup, gpio: *Gpio, -pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self { +pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_path: ?[]const u8) !Self { const file = try std.fs.cwd().openFile(rom_path, .{}); defer file.close(); @@ -28,7 +29,7 @@ pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) .allocator = allocator, .title = title, .backup = try Backup.init(allocator, kind, title, save_path), - .gpio = try Gpio.init(allocator, .Rtc), + .gpio = try Gpio.init(allocator, cpu, .Rtc), }; } @@ -242,8 +243,7 @@ const Gpio = struct { switch (self.kind) { .Rtc => { const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.ptr.?)); - - clock.step(Clock.GpioData{ .raw = value }); + clock.step(Clock.Data{ .raw = value }); }, .None => {}, } @@ -260,7 +260,7 @@ const Gpio = struct { Control, }; - fn init(allocator: Allocator, kind: Device.Kind) !*This { + fn init(allocator: Allocator, cpu: *Arm7tdmi, kind: Device.Kind) !*This { const self = try allocator.create(This); self.* = .{ @@ -271,7 +271,7 @@ const Gpio = struct { .device = switch (kind) { .Rtc => blk: { const clock = try allocator.create(Clock); - clock.init(self); + clock.init(cpu, self); break :blk Device{ .kind = kind, .ptr = clock }; }, @@ -339,6 +339,7 @@ const Clock = struct { minute: u7, second: u7, + cpu: *Arm7tdmi, gpio: *const Gpio, const Register = enum { @@ -418,8 +419,8 @@ const Clock = struct { } 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(); + log.info("RTC: Failed to handle Command 0b{b:0>8} aka 0x{X:0>2}", .{ command, command }); const is_write = command & 1 == 0; const rtc_register = @intCast(u3, command >> 1 & 0x7); // TODO: Make Truncate @@ -450,7 +451,7 @@ const Clock = struct { } }; - const GpioData = extern union { + const Data = extern union { sck: Bit(u8, 0), sio: Bit(u8, 1), cs: Bit(u8, 2), @@ -473,7 +474,7 @@ const Clock = struct { raw: u8, }; - fn init(ptr: *This, gpio: *const Gpio) void { + fn init(ptr: *This, cpu: *Arm7tdmi, gpio: *const Gpio) void { ptr.* = .{ .cmd = .{ .buf = 0, .i = 0 }, .writer = .{ .buf = 0, .i = 0, .count = 0 }, @@ -486,16 +487,13 @@ const Clock = struct { .hour = 0, .minute = 0, .second = 0, - .gpio = gpio, + .cpu = cpu, + .gpio = gpio, // Can't use Arm7tdmi ptr b/c not initialized yet }; } - fn attachGpio(self: *This, gpio: *const Gpio) void { - self.gpio = gpio; - } - - fn step(self: *This, value: GpioData) void { - const cache: GpioData = .{ .raw = self.gpio.data }; + fn step(self: *This, value: Data) void { + const cache: Data = .{ .raw = self.gpio.data }; switch (self.state) { .Idle => { @@ -558,8 +556,11 @@ const Clock = struct { log.info("RTC: Reset executed (control register was zeroed)", .{}); } - fn irq(_: *const This) void { - // TODO: Force GamePak IRQ - log.err("RTC: TODO: Force GamePak IRQ", .{}); + fn irq(self: *This) void { + // TODO: Confirm that this is the right behaviour + + log.debug("RTC: Force GamePak IRQ", .{}); + self.cpu.bus.io.irq.game_pak.set(); + self.cpu.handleInterrupt(); } }; From 089c5fa02571ba30901c148884a9342bf3ddf103 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 07:09:22 -0300 Subject: [PATCH 06/14] feat: implement RTC Read/Writes --- src/core/bus/GamePak.zig | 274 +++++++++++++++++++++++++++++---------- 1 file changed, 209 insertions(+), 65 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 2f8934f..1ce7f5c 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -231,22 +231,18 @@ const Gpio = struct { const Device = struct { ptr: ?*anyopaque, - // TODO: Maybe make this comptime known? Removes some if statements - kind: Kind, + kind: Kind, // TODO: Make comptime known? - const Kind = enum { - Rtc, - None, - }; + const Kind = enum { Rtc, None }; - fn step(self: *Device, value: u4) void { - switch (self.kind) { - .Rtc => { + fn step(self: *Device, value: u4) u4 { + return switch (self.kind) { + .Rtc => blk: { const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.ptr.?)); - clock.step(Clock.Data{ .raw = value }); + break :blk clock.step(Clock.Data{ .raw = value }); }, - .None => {}, - } + .None => value, + }; } fn init(kind: Kind, ptr: ?*anyopaque) Device { @@ -294,17 +290,13 @@ const Gpio = struct { } 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) { .Data => { const masked_value = value & self.direction; - self.device.step(masked_value); - self.data = masked_value; + // The value which is actually stored in the GPIO register + // might be modified by the device implementing the GPIO interface e.g. RTC reads + self.data = self.device.step(masked_value); }, .Direction => self.direction = value, .Control => self.cnt = value, @@ -328,6 +320,7 @@ const Clock = struct { cmd: Command, writer: Writer, + reader: Reader, state: State, cnt: Control, @@ -355,49 +348,162 @@ const Clock = struct { 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 => { + log.err("RTC: {} is only 1 byte wide", .{register}); + @panic("Out-of-bounds RTC read"); + }, + }), + .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.day_of_week) >> idx, + + // Time + 4 => @as(u8, clock.hour) >> idx, + 5 => @as(u8, clock.minute) >> idx, + 6 => @as(u8, clock.second) >> idx, + else => { + log.err("RTC: {} is only 7 bytes wide", .{register}); + @panic("Out-of-bounds RTC read"); + }, + }), + .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 => { + log.err("RTC: {} is only 3 bytes wide", .{register}); + @panic("Out-of-bounds RTC read"); + }, + }), + }; + } + + /// 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 { buf: u8, i: u4, - /// The Number of bytes written to since last reset + /// The Number of bytes written since last reset count: u8, + /// Append a bit to the internal bit buffer (aka an integer) fn push(self: *Writer, value: u1) void { const idx = @intCast(u3, self.i); self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx; 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 = self.buf, + else => { + log.err("RTC :{} is only 1 byte wide", .{register}); + @panic("Out-of-bounds RTC write"); + }, + }, + .DateTime => switch (self.count) { + // Date + 0 => clock.year = @truncate(@TypeOf(clock.year), self.buf), + 1 => clock.month = @truncate(@TypeOf(clock.month), self.buf), + 2 => clock.day = @truncate(@TypeOf(clock.day), self.buf), + 3 => clock.day_of_week = @truncate(@TypeOf(clock.day_of_week), self.buf), + + // Time + 4 => clock.hour = @truncate(@TypeOf(clock.hour), self.buf), + 5 => clock.minute = @truncate(@TypeOf(clock.minute), self.buf), + 6 => clock.second = @truncate(@TypeOf(clock.second), self.buf), + else => { + log.err("RTC :{} is only 1 byte wide", .{register}); + @panic("Out-of-bounds RTC write"); + }, + }, + .Time => switch (self.count) { + // Time + 0 => clock.hour = @truncate(@TypeOf(clock.hour), self.buf), + 1 => clock.minute = @truncate(@TypeOf(clock.minute), self.buf), + 2 => clock.second = @truncate(@TypeOf(clock.second), self.buf), + else => { + log.err("RTC :{} is only 1 byte wide", .{register}); + @panic("Out-of-bounds RTC write"); + }, + }, + } + } + + /// 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 { self.buf = 0; self.i = 0; self.count += 1; } + /// Resets `Writer` to a clean state in preparation for a future write command fn reset(self: *Writer) void { self.buf = 0; self.i = 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 Command = struct { buf: u8, i: u4, - fn push(self: *Command, value: u1) void { + fn write(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; @@ -413,17 +519,25 @@ const Clock = struct { } 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); + // If High Nybble is 0x6, no need to switch the endianness + if (self.buf >> 4 & 0xF == 0x6) return self.buf; + + // 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 = self.buf; + ret = (ret & 0xF0) >> 4 | (ret & 0x0F) << 4; + ret = (ret & 0xCC) >> 2 | (ret & 0x33) << 2; + ret = (ret & 0xAA) >> 1 | (ret & 0x55) << 1; + + return ret; } fn handleCommand(self: *const Command, rtc: *Clock) State { const command = self.getCommand(); - log.info("RTC: Failed to handle Command 0b{b:0>8} aka 0x{X:0>2}", .{ command, command }); + log.debug("RTC: Handling Command 0x{X:0>2} [0b{b:0>8}]", .{ command, command }); const is_write = command & 1 == 0; - const rtc_register = @intCast(u3, command >> 1 & 0x7); // TODO: Make Truncate + const rtc_register = @truncate(u3, command >> 1 & 0x7); if (is_write) { return switch (rtc_register) { @@ -478,6 +592,7 @@ const Clock = struct { ptr.* = .{ .cmd = .{ .buf = 0, .i = 0 }, .writer = .{ .buf = 0, .i = 0, .count = 0 }, + .reader = .{ .i = 0, .count = 0 }, .state = .Idle, .cnt = .{ .raw = 0 }, .year = 0, @@ -492,74 +607,103 @@ const Clock = struct { }; } - fn step(self: *This, value: Data) void { + fn step(self: *This, value: Data) u4 { const cache: Data = .{ .raw = self.gpio.data }; - switch (self.state) { - .Idle => { - // If SCK is high and CS rises, then prepare for Command + return switch (self.state) { + .Idle => blk: { // FIXME: Maybe check incoming value to see if SCK is also high? if (cache.sck.read()) { if (!cache.cs.read() and value.cs.read()) { - log.err("RTC: Entering Command Mode", .{}); + log.debug("RTC: Entering Command Mode", .{}); self.state = .CommandInput; self.cmd.reset(); } } + + break :blk @truncate(u4, value.raw); }, - .CommandInput => { + .CommandInput => blk: { 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 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())); + self.cmd.write(@boolToInt(value.sio.read())); if (self.cmd.isFinished()) { self.state = self.cmd.handleCommand(self); + log.debug("RTC: Switching to {}", .{self.state}); } } + + break :blk @truncate(u4, value.raw); }, - State{ .Write = .Control } => { + .Write => |register| blk: { 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 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())); - if (self.writer.isFinished()) { - self.writer.lap(); - self.cnt.raw = self.writer.getValue(); + const register_width: u32 = switch (register) { + .Control => 1, + .DateTime => 7, + .Time => 3, + }; - // FIXME: Move this to a constant or something - if (self.writer.getCount() == 1) { + if (self.writer.finished()) { + self.writer.write(self, register); // write inner buffer to RTC register + self.writer.lap(); + + if (self.writer.count == register_width) { self.writer.reset(); self.state = .Idle; } } } + + break :blk @truncate(u4, value.raw); }, - else => { - // TODO: Implement Read/Writes for Date/Time and Time and Control - log.err("RTC: Ignored request to handle {} command", .{self.state}); - self.state = .Idle; + .Read => |register| blk: { + if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state}); + var ret = value; + + // 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 { - // mGBA and NBA only zero the control register - // we'll do the same + // mGBA and NBA only zero the control register. We will do the same + log.debug("RTC: Reset (control register was zeroed)", .{}); + self.cnt.raw = 0; - log.info("RTC: Reset executed (control register was zeroed)", .{}); } fn irq(self: *This) void { // TODO: Confirm that this is the right behaviour - log.debug("RTC: Force GamePak IRQ", .{}); + self.cpu.bus.io.irq.game_pak.set(); self.cpu.handleInterrupt(); } From 3857c44e68305199ff31630243f2fa0ede9213af Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 07:25:32 -0300 Subject: [PATCH 07/14] chore: use Clock.Writer for Command parsing, delete Clock.Command --- src/core/bus/GamePak.zig | 127 ++++++++++++++++----------------------- 1 file changed, 52 insertions(+), 75 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 1ce7f5c..198944d 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -318,7 +318,6 @@ const Gpio = struct { const Clock = struct { const This = @This(); - cmd: Command, writer: Writer, reader: Reader, state: State, @@ -343,7 +342,7 @@ const Clock = struct { const State = union(enum) { Idle, - CommandInput, + Command, Write: Register, Read: Register, }; @@ -499,72 +498,6 @@ const Clock = struct { } }; - const Command = struct { - buf: u8, - i: u4, - - fn write(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 is 0x6, no need to switch the endianness - if (self.buf >> 4 & 0xF == 0x6) return self.buf; - - // 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 = self.buf; - ret = (ret & 0xF0) >> 4 | (ret & 0x0F) << 4; - ret = (ret & 0xCC) >> 2 | (ret & 0x33) << 2; - ret = (ret & 0xAA) >> 1 | (ret & 0x55) << 1; - - return ret; - } - - fn handleCommand(self: *const Command, rtc: *Clock) State { - const command = self.getCommand(); - 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: { - 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 Data = extern union { sck: Bit(u8, 0), sio: Bit(u8, 1), @@ -590,7 +523,6 @@ const Clock = struct { fn init(ptr: *This, cpu: *Arm7tdmi, gpio: *const Gpio) void { ptr.* = .{ - .cmd = .{ .buf = 0, .i = 0 }, .writer = .{ .buf = 0, .i = 0, .count = 0 }, .reader = .{ .i = 0, .count = 0 }, .state = .Idle, @@ -616,22 +548,23 @@ const Clock = struct { if (cache.sck.read()) { if (!cache.cs.read() and value.cs.read()) { log.debug("RTC: Entering Command Mode", .{}); - self.state = .CommandInput; - self.cmd.reset(); + self.state = .Command; } } break :blk @truncate(u4, value.raw); }, - .CommandInput => blk: { + .Command => blk: { 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()) { - self.cmd.write(@boolToInt(value.sio.read())); + self.writer.push(@boolToInt(value.sio.read())); + + if (self.writer.finished()) { + self.state = self.processCommand(self.writer.buf); + self.writer.reset(); - if (self.cmd.isFinished()) { - self.state = self.cmd.handleCommand(self); log.debug("RTC: Switching to {}", .{self.state}); } } @@ -707,4 +640,48 @@ const Clock = struct { 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 + }; + } + } }; From d6b182f245dac8dfae75006c07a42cccc73e1587 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 07:34:42 -0300 Subject: [PATCH 08/14] fix: ignore RTC Time/DateTime writes this falls in-line with better emulators --- src/core/bus/GamePak.zig | 51 ++++++---------------------------------- 1 file changed, 7 insertions(+), 44 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 198944d..031dbf1 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -364,10 +364,7 @@ const Clock = struct { return switch (register) { .Control => @truncate(u1, switch (self.count) { 0 => clock.cnt.raw >> idx, - else => { - log.err("RTC: {} is only 1 byte wide", .{register}); - @panic("Out-of-bounds RTC read"); - }, + 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 @@ -380,19 +377,13 @@ const Clock = struct { 4 => @as(u8, clock.hour) >> idx, 5 => @as(u8, clock.minute) >> idx, 6 => @as(u8, clock.second) >> idx, - else => { - log.err("RTC: {} is only 7 bytes wide", .{register}); - @panic("Out-of-bounds RTC read"); - }, + 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 => { - log.err("RTC: {} is only 3 bytes wide", .{register}); - @panic("Out-of-bounds RTC read"); - }, + else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 3 bytes)", .{ self.count, register }), }), }; } @@ -441,38 +432,10 @@ const Clock = struct { // FIXME: What do do about unused bits? switch (register) { .Control => switch (self.count) { - 0 => clock.cnt.raw = self.buf, - else => { - log.err("RTC :{} is only 1 byte wide", .{register}); - @panic("Out-of-bounds RTC write"); - }, - }, - .DateTime => switch (self.count) { - // Date - 0 => clock.year = @truncate(@TypeOf(clock.year), self.buf), - 1 => clock.month = @truncate(@TypeOf(clock.month), self.buf), - 2 => clock.day = @truncate(@TypeOf(clock.day), self.buf), - 3 => clock.day_of_week = @truncate(@TypeOf(clock.day_of_week), self.buf), - - // Time - 4 => clock.hour = @truncate(@TypeOf(clock.hour), self.buf), - 5 => clock.minute = @truncate(@TypeOf(clock.minute), self.buf), - 6 => clock.second = @truncate(@TypeOf(clock.second), self.buf), - else => { - log.err("RTC :{} is only 1 byte wide", .{register}); - @panic("Out-of-bounds RTC write"); - }, - }, - .Time => switch (self.count) { - // Time - 0 => clock.hour = @truncate(@TypeOf(clock.hour), self.buf), - 1 => clock.minute = @truncate(@TypeOf(clock.minute), self.buf), - 2 => clock.second = @truncate(@TypeOf(clock.second), self.buf), - else => { - log.err("RTC :{} is only 1 byte wide", .{register}); - @panic("Out-of-bounds RTC write"); - }, + 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}), } } @@ -628,7 +591,7 @@ const Clock = struct { fn reset(self: *This) void { // mGBA and NBA only zero the control register. We will do the same - log.debug("RTC: Reset (control register was zeroed)", .{}); + log.debug("RTC: Reset (control register was zeroed)", .{}); self.cnt.raw = 0; } From 3fc3366c8ab2d2439b096f6fc08f6e6987f0406b Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 09:32:52 -0300 Subject: [PATCH 09/14] chore: import datetime library + default time for RTC --- .gitmodules | 3 +++ build.zig | 4 +++- lib/zig-datetime | 1 + src/core/bus/GamePak.zig | 45 ++++++++++++++++++++++++++++++++-------- 4 files changed, 43 insertions(+), 10 deletions(-) create mode 160000 lib/zig-datetime diff --git a/.gitmodules b/.gitmodules index 9dda538..2c14e46 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,3 +7,6 @@ [submodule "lib/known-folders"] path = lib/known-folders url = https://github.com/ziglibs/known-folders +[submodule "lib/zig-datetime"] + path = lib/zig-datetime + url = https://github.com/frmdstryr/zig-datetime diff --git a/build.zig b/build.zig index 5cdd799..e93d00c 100644 --- a/build.zig +++ b/build.zig @@ -13,10 +13,12 @@ pub fn build(b: *std.build.Builder) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("zba", "src/main.zig"); - // Known Folders (%APPDATA%, XDG, etc.) 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/ // exe.addPackage(.{ .name = "bitfield", .path = .{ .path = "lib/util/bitfield.zig" } }); exe.addPackagePath("bitfield", "lib/util/bitfield.zig"); diff --git a/lib/zig-datetime b/lib/zig-datetime new file mode 160000 index 0000000..5ec1c36 --- /dev/null +++ b/lib/zig-datetime @@ -0,0 +1 @@ +Subproject commit 5ec1c36cf3791b3c6c5b330357bdb6feb93979ba diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 031dbf1..ec2f28b 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -1,4 +1,5 @@ const std = @import("std"); +const DateTime = @import("datetime").datetime.Datetime; const Arm7tdmi = @import("../cpu.zig").Arm7tdmi; const Bit = @import("bitfield").Bit; @@ -326,7 +327,7 @@ const Clock = struct { year: u8, month: u5, day: u6, - day_of_week: u3, + weekday: u3, hour: u6, minute: u7, second: u7, @@ -371,7 +372,7 @@ const Clock = struct { 0 => clock.year >> idx, 1 => @as(u8, clock.month) >> idx, 2 => @as(u8, clock.day) >> idx, - 3 => @as(u8, clock.day_of_week) >> idx, + 3 => @as(u8, clock.weekday) >> idx, // Time 4 => @as(u8, clock.hour) >> idx, @@ -490,18 +491,30 @@ const Clock = struct { .reader = .{ .i = 0, .count = 0 }, .state = .Idle, .cnt = .{ .raw = 0 }, - .year = 0, - .month = 0, - .day = 0, - .day_of_week = 0, - .hour = 0, - .minute = 0, - .second = 0, + .year = 0x01, + .month = 0x6, + .day = 0x13, + .weekday = 0x3, + .hour = 0x23, + .minute = 0x59, + .second = 0x59, .cpu = cpu, .gpio = gpio, // Can't use Arm7tdmi ptr b/c not initialized yet }; } + fn updateRealTime(self: *This) void { + 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 { const cache: Data = .{ .raw = self.gpio.data }; @@ -648,3 +661,17 @@ const Clock = struct { } } }; + +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); +} From 7783c11facbd9cfc8f6faf11a2d7fee9355b9fb9 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 09:54:31 -0300 Subject: [PATCH 10/14] feat: put RTC Sync on Scheduler TODO: Database to see what games have what GPIO devices --- src/core/bus/GamePak.zig | 9 ++++++--- src/core/scheduler.zig | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index ec2f28b..f41a18a 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -316,7 +316,7 @@ const Gpio = struct { }; /// GBA Real Time Clock -const Clock = struct { +pub const Clock = struct { const This = @This(); writer: Writer, @@ -501,11 +501,14 @@ const Clock = struct { .cpu = cpu, .gpio = gpio, // Can't use Arm7tdmi ptr b/c not initialized yet }; + + cpu.sched.push(.RealTimeClock, 1 << 24); // Every Second } - fn updateRealTime(self: *This) void { - const now = DateTime.now(); + pub fn updateTime(self: *This) void { + self.cpu.sched.push(.RealTimeClock, 1 << 24); // Reschedule + 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); diff --git a/src/core/scheduler.zig b/src/core/scheduler.zig index 8a4b517..af6989c 100644 --- a/src/core/scheduler.zig +++ b/src/core/scheduler.zig @@ -2,6 +2,7 @@ const std = @import("std"); const Bus = @import("Bus.zig"); const Arm7tdmi = @import("cpu.zig").Arm7tdmi; +const Clock = @import("bus/GamePak.zig").Clock; const Order = std.math.Order; const PriorityQueue = std.PriorityQueue; @@ -60,6 +61,13 @@ pub const Scheduler = struct { 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), .SampleAudio => cpu.bus.apu.sampleAudio(late), .HBlank => cpu.bus.ppu.handleHBlankEnd(cpu, late), // The end of a HBlank @@ -118,4 +126,5 @@ pub const EventKind = union(enum) { SampleAudio, FrameSequencer, ApuChannel: u2, + RealTimeClock, }; From 12c138364d31a5cbebc1eb710dc8d2edc51a0588 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 16 Sep 2022 10:59:41 -0300 Subject: [PATCH 11/14] fix: RTC day is 6 bits wide, not 3 --- src/core/bus/GamePak.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index f41a18a..b75d934 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -511,7 +511,7 @@ pub const Clock = struct { 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.day = toBcd(u6, 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); From a2e702c366698738528465a855e8c62d86b95de1 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Sat, 17 Sep 2022 09:07:31 -0300 Subject: [PATCH 12/14] fix: account for lateness in RTC scheduler event --- src/core/bus/GamePak.zig | 4 ++-- src/core/scheduler.zig | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index b75d934..7bfde15 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -505,8 +505,8 @@ pub const Clock = struct { cpu.sched.push(.RealTimeClock, 1 << 24); // Every Second } - pub fn updateTime(self: *This) void { - self.cpu.sched.push(.RealTimeClock, 1 << 24); // Reschedule + pub fn updateTime(self: *This, late: u64) void { + self.cpu.sched.push(.RealTimeClock, (1 << 24) -| late); // Reschedule const now = DateTime.now(); self.year = toBcd(u8, @intCast(u8, now.date.year - 2000)); diff --git a/src/core/scheduler.zig b/src/core/scheduler.zig index af6989c..4c96c3b 100644 --- a/src/core/scheduler.zig +++ b/src/core/scheduler.zig @@ -66,7 +66,7 @@ pub const Scheduler = struct { if (device.kind != .Rtc or device.ptr == null) return; const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), device.ptr.?)); - clock.updateTime(); + clock.updateTime(late); }, .FrameSequencer => cpu.bus.apu.tickFrameSequencer(late), .SampleAudio => cpu.bus.apu.sampleAudio(late), From 19d78b929236415c865eee25e29f26d1560fb43a Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Sat, 17 Sep 2022 20:23:49 -0300 Subject: [PATCH 13/14] feat: auto-detect RTC in commercial ROMS --- src/core/bus/GamePak.zig | 25 ++++++++++++++++++++++--- src/core/bus/backup.zig | 4 ++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 7bfde15..43667ef 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -22,7 +22,9 @@ pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_pat const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos()); const title = file_buf[0xA0..0xAC].*; - const kind = Backup.guessKind(file_buf) orelse .None; + const kind = Backup.guessKind(file_buf); + const device = guessDevice(file_buf); + logHeader(file_buf, &title); return .{ @@ -30,10 +32,26 @@ pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_pat .allocator = allocator, .title = title, .backup = try Backup.init(allocator, kind, title, save_path), - .gpio = try Gpio.init(allocator, cpu, .Rtc), + .gpio = try Gpio.init(allocator, cpu, device), }; } +/// Searches the ROM to see if it can determine whether the ROM it's searching uses +/// any GPIO device, like a RTC for example. +fn guessDevice(buf: []const u8) Gpio.Device.Kind { + // Try to Guess if ROM uses RTC + const needle = "RTC_V"; // I was told SIIRTC_V, though Pokemen Firered (USA) is a false negative + + var i: usize = 0; + while ((i + needle.len) < buf.len) : (i += 1) { + if (std.mem.eql(u8, needle, buf[i..(i + needle.len)])) return .Rtc; + } + + // TODO: Detect other GPIO devices + + return .None; +} + fn logHeader(buf: []const u8, title: *const [12]u8) void { const code = buf[0xAC..0xB0]; const maker = buf[0xB0..0xB2]; @@ -258,8 +276,9 @@ const Gpio = struct { }; fn init(allocator: Allocator, cpu: *Arm7tdmi, kind: Device.Kind) !*This { - const self = try allocator.create(This); + log.info("Device: {}", .{kind}); + const self = try allocator.create(This); self.* = .{ .data = 0b0000, .direction = 0b1111, // TODO: What is GPIO DIrection set to by default? diff --git a/src/core/bus/backup.zig b/src/core/bus/backup.zig index 09d6b91..f89a0cc 100644 --- a/src/core/bus/backup.zig +++ b/src/core/bus/backup.zig @@ -61,7 +61,7 @@ pub const Backup = struct { return backup; } - pub fn guessKind(rom: []const u8) ?Kind { + pub fn guessKind(rom: []const u8) Kind { for (backup_kinds) |needle| { const needle_len = needle.str.len; @@ -71,7 +71,7 @@ pub const Backup = struct { } } - return null; + return .None; } pub fn deinit(self: *Self) void { From 50adb5fbac6588dcfe9cf7f3b12e2b62d4b0b76d Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Sat, 17 Sep 2022 20:27:17 -0300 Subject: [PATCH 14/14] feat: add option to force-enable RTC --- src/core/bus/GamePak.zig | 4 +++- src/core/emu.zig | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/bus/GamePak.zig b/src/core/bus/GamePak.zig index 43667ef..ed90aba 100644 --- a/src/core/bus/GamePak.zig +++ b/src/core/bus/GamePak.zig @@ -6,6 +6,8 @@ const Bit = @import("bitfield").Bit; const Bitfield = @import("bitfield").Bitfield; const Backup = @import("backup.zig").Backup; const Allocator = std.mem.Allocator; + +const force_rtc = @import("../emu.zig").force_rtc; const log = std.log.scoped(.GamePak); const Self = @This(); @@ -23,7 +25,7 @@ pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_pat const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos()); const title = file_buf[0xA0..0xAC].*; const kind = Backup.guessKind(file_buf); - const device = guessDevice(file_buf); + const device = if (force_rtc) .Rtc else guessDevice(file_buf); logHeader(file_buf, &title); diff --git a/src/core/emu.zig b/src/core/emu.zig index 6040d61..3559efd 100644 --- a/src/core/emu.zig +++ b/src/core/emu.zig @@ -18,6 +18,7 @@ const sync_video: RunKind = .LimitedFPS; // Configure Video Sync pub const win_scale = 3; // 1x, 2x, 3x, etc. Window Scaling pub const cpu_logging = false; // Enable detailed CPU logging pub const allow_unhandled_io = true; // Only relevant in Debug Builds +pub const force_rtc = false; // 228 Lines which consist of 308 dots (which are 4 cycles long) const cycles_per_frame: u64 = 228 * (308 * 4); //280896