diff --git a/README.md b/README.md index 7268912c3..2ba717dd9 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Seeking • Joypads • GameCube controllers • Mouse • Controller Pak • Rumble Pak • Transfer Pak • Bio Sensor • RTC +Joypads • GameCube controllers • Mouse • Controller Pak • Rumble Pak • Transfer Pak • Bio Sensor • RTC • GBA Link Cable diff --git a/examples/Makefile b/examples/Makefile index 521ad9981..24ede1f3c 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -11,6 +11,7 @@ EXAMPLES += customfont EXAMPLES += eepromfstest EXAMPLES += fontdemo EXAMPLES += fontgallery +EXAMPLES += gbalink EXAMPLES += gldemo EXAMPLES += helloworld EXAMPLES += joypadtest diff --git a/examples/gbalink/.gitignore b/examples/gbalink/.gitignore new file mode 100644 index 000000000..87ef66815 --- /dev/null +++ b/examples/gbalink/.gitignore @@ -0,0 +1 @@ +filesystem/ \ No newline at end of file diff --git a/examples/gbalink/Makefile b/examples/gbalink/Makefile new file mode 100644 index 000000000..0046cf33f --- /dev/null +++ b/examples/gbalink/Makefile @@ -0,0 +1,30 @@ +all: gbalink.z64 +.PHONY: all + +BUILD_DIR = build +# This example uses GBA Link Cable, which is a preview API +LIBDRAGON_PREVIEW = 2 +include $(N64_INST)/include/n64.mk + +OBJS = $(BUILD_DIR)/gbalink.o +assets_gba = $(wildcard assets/*.gba) + +assets_conv = $(addprefix filesystem/,$(notdir $(assets_gba))) + +filesystem/%.gba: assets/%.gba + @mkdir -p $(dir $@) + @echo " [MKASSET] $@" + $(N64_BINDIR)/mkasset -c 2 -w 256 -o filesystem/ $< + +$(BUILD_DIR)/gbalink.dfs: $(assets_conv) + +gbalink.z64: N64_ROM_TITLE = "GBA Link Cable" +gbalink.z64: $(BUILD_DIR)/gbalink.dfs + +$(BUILD_DIR)/gbalink.elf: $(OBJS) + +clean: + rm -rf $(BUILD_DIR) filesystem/ *.z64 +.PHONY: clean + +-include $(wildcard $(BUILD_DIR)/*.d) diff --git a/examples/gbalink/assets/gbarom_mb.gba b/examples/gbalink/assets/gbarom_mb.gba new file mode 100755 index 000000000..c54e48617 Binary files /dev/null and b/examples/gbalink/assets/gbarom_mb.gba differ diff --git a/examples/gbalink/gbalink.c b/examples/gbalink/gbalink.c new file mode 100644 index 000000000..8c759c374 --- /dev/null +++ b/examples/gbalink/gbalink.c @@ -0,0 +1,205 @@ +#include +#include +#include + + +#define GBA_ROM_PATH "rom:/gbarom_mb.gba" +#define GBA_CHALLENGE 0x64646464 +#define GBA_RESPONSE 0x6BA006BA + +#define CLAMP(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x))) + +static volatile bool identify_pending = false; +static volatile bool multiboot_pending = false; +static volatile bool multiboot_done = false; +static timer_link_t *progress_timer; +static volatile int gba_port; +static volatile uint32_t gba_controller_held; +static int x, y; + +typedef enum KEYPAD_BITS { + GBA_KEY_A = (1<<0), /*!< keypad A button */ + GBA_KEY_B = (1<<1), /*!< keypad B button */ + GBA_KEY_SELECT = (1<<2), /*!< keypad SELECT button */ + GBA_KEY_START = (1<<3), /*!< keypad START button */ + GBA_KEY_RIGHT = (1<<4), /*!< dpad RIGHT */ + GBA_KEY_LEFT = (1<<5), /*!< dpad LEFT */ + GBA_KEY_UP = (1<<6), /*!< dpad UP */ + GBA_KEY_DOWN = (1<<7), /*!< dpad DOWN */ + GBA_KEY_R = (1<<8), /*!< Right shoulder button */ + GBA_KEY_L = (1<<9), /*!< Left shoulder button */ +} KEYPAD_BITS; + +static void gba_link_multiboot_callback(int port, gba_link_multiboot_status_t status, void *ctx) { + multiboot_done = status == GBA_LINK_MULTIBOOT_OK; + multiboot_pending = false; + if (!multiboot_done) { + printf("Multi Boot FAILED: %d.\n", status); + } else { + printf("Multi Boot done\n"); + } + delete_timer(progress_timer); + timer_close(); +} + +static void print_progress(int ovfl) { + printf("Progress: %d %%\n", gba_link_multiboot_progress(gba_port)); +} + +static void gba_link_multiboot_detect_callback(int port, bool multiboot_ready, void *ctx) { + printf("Port %d: Multi Boot ready: %d\n", port, multiboot_ready); + if (multiboot_ready) { + multiboot_pending = true; + timer_init(); + progress_timer = new_timer(TIMER_TICKS(500*1000), TF_CONTINUOUS, print_progress); + // Send ROM via Multi Boot, GBA logo blinking green to yellow + gba_link_multiboot_start(port, GBA_ROM_PATH, GBA_LINK_MULTIBOOT_LOGO_COLOR_3_GREEN, GBA_LINK_MULTIBOOT_LOGO_SPEED_PLUS_1, gba_link_multiboot_callback, NULL); + printf("Starting GBA Multi Boot on port: %d.\n", port); + } + identify_pending = false; +} + +static void gba_link_read_callback(int port, const uint8_t data[JOYBUS_GBA_LINK_CABLE_DATA_SIZE], uint8_t gba_status, gba_link_io_status_t io_status, void *ctx) { + if (io_status == GBA_LINK_IO_STATUS_OK) { + // Received controller status + gba_controller_held = __builtin_bswap32(*(uint32_t*)data); + //printf("GBA controller: 0x%08lx\n", gba_controller_held); + } +} + +static bool gba_challenge_response(int port) { + uint32_t data = GBA_CHALLENGE;; + uint8_t gba_status; + gba_link_io_status_t io_status = gba_link_write(port, (uint8_t*)&data, &gba_status); + if (io_status != GBA_LINK_IO_STATUS_OK) { + return false; + } + for (int i=0; i<5; i++) { + io_status = gba_link_read(port, (uint8_t*)&data, &gba_status); + if (/*io_status == GBA_LINK_IO_STATUS_OK && */__builtin_bswap32(data) == GBA_RESPONSE) { + return true; + } + } + return false; +} + +int main(void) +{ + debug_init_emulog(); + debug_init_usblog(); + + dfs_init(DFS_DEFAULT_LOCATION); + + asset_init_compression(2); + + console_init(); + console_set_render_mode(RENDER_MANUAL); + console_set_debug(false); + + rdpq_init(); + rdpq_text_register_font(1, rdpq_font_load_builtin(FONT_BUILTIN_DEBUG_VAR)); + + joypad_init(); + + console_clear(); + printf("\n"); + printf("LibDragon GBA Link Cable Subsystem Test\n"); + printf("\n"); + console_render(); + + // Detect if GBA is already listening + for (gba_port = JOYPAD_PORT_2; gba_port <= JOYPAD_PORT_4; gba_port++) { + if (gba_link_is_connected(gba_port)) {// && (gba_link_get_status(gba_port) & JOYBUS_IDENTIFY_STATUS_GBA_SENDING)) { + printf("Found GBA Link Cable on port %d\n", gba_port); + console_render(); + + // Challenge-Response with GBA rom + if (!gba_challenge_response(gba_port)) { + printf("Failed challenge-response\n\n"); + console_render(); + break; + } + + // Wait for player to press A on the GBA + printf("Press A on GBA\n"); + console_render(); + uint32_t data; + uint8_t gba_status; + gba_link_io_status_t io_status; + do { + io_status = gba_link_read(gba_port, (uint8_t*)&data, &gba_status); + } while ((io_status == GBA_LINK_IO_STATUS_OK || io_status == GBA_LINK_IO_STATUS_DATA_NOT_READY) && !(__builtin_bswap32(data) & GBA_KEY_A)); + + if (__builtin_bswap32(data) & GBA_KEY_A) { + // GBA already running, skip multiboot + multiboot_done = true; + printf("Skipping Multi Boot\n"); + console_render(); + break; + } + } + } + + // Upload GBA rom over Multi Boot, if needed + if (!multiboot_done) { + gba_port = JOYPAD_PORT_1; + + printf("Plug the GBA via its Link Cable to controller port 2-4\n"); + printf("Power on the GBA with no game\n"); + printf("(or hold SELECT+START to prevent booting the cartridge game)\n"); + printf("Press A to detect GBA Link Cable and upload a Multi Boot rom\n"); + printf("\n"); + + while (!multiboot_done) { + joypad_poll(); + joypad_buttons_t pressed = joypad_get_buttons_pressed(JOYPAD_PORT_1); + + if (pressed.a && !identify_pending && !multiboot_pending) { + gba_port++; + if (gba_port > JOYPAD_PORT_4) { + gba_port = JOYPAD_PORT_2; + } + printf("Attempting GBA Multi Boot on port %d\n", gba_port); + identify_pending = true; + gba_link_multiboot_detect(gba_port, 3000, gba_link_multiboot_detect_callback, NULL); + } + + console_render(); + } + + // Wait for GBA ROM to be ready + while (!gba_challenge_response(gba_port)) {} + } + + // Once GBA rom is sent via Multi Boot, read GBA controller status over JoyBus + // GBA controls the text position + display_close(); + display_init( RESOLUTION_320x240, DEPTH_16_BPP, 2, GAMMA_NONE, FILTERS_DISABLED ); + x = 160; + y = 120; + while (1) { + // Acquire a free framebuffer for rendering + surface_t *disp = display_get(); + // Attach the framebuffer for use by rdpq + rdpq_attach(disp, NULL); + + // Clear the framebuffer with black + rdpq_clear((color_t){0, 0, 0, 0}); + + // Read from GBA + gba_link_read_async(gba_port, gba_link_read_callback, NULL); + + if (gba_controller_held & GBA_KEY_UP) + y = CLAMP(y - 2, 40, 200); + if (gba_controller_held & GBA_KEY_DOWN) + y = CLAMP(y + 2, 40, 200); + if (gba_controller_held & GBA_KEY_LEFT) + x = CLAMP(x - 2, 20, 220); + if (gba_controller_held & GBA_KEY_RIGHT) + x = CLAMP(x + 2, 20, 220); + + rdpq_text_print(NULL, 1, x, y, "Move me from GBA"); + + rdpq_detach_show(); + } +} diff --git a/examples/gbalink/gbarom/Makefile b/examples/gbalink/gbarom/Makefile new file mode 100644 index 000000000..99dfbb64e --- /dev/null +++ b/examples/gbalink/gbarom/Makefile @@ -0,0 +1,168 @@ +#--------------------------------------------------------------------------------- +# Clear the implicit built in rules +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- +ifeq ($(strip $(DEVKITARM)),) +$(error "Please set DEVKITARM in your environment. export DEVKITARM=devkitARM) +endif + +include $(DEVKITARM)/gba_rules + +#--------------------------------------------------------------------------------- +# TARGET is the name of the output, if this ends with _mb a multiboot image is generated +# BUILD is the directory where object files & intermediate files will be placed +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +#--------------------------------------------------------------------------------- +TARGET := $(shell basename $(CURDIR))_mb +BUILD := build +SOURCES := source +DATA := +GRAPHICS := gfx +INCLUDES := + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- +ARCH := -mthumb -mthumb-interwork + +CFLAGS := -g -Wall -O3\ + -mcpu=arm7tdmi -mtune=arm7tdmi\ + -fomit-frame-pointer\ + -ffast-math \ + $(ARCH) + +CFLAGS += $(INCLUDE) + +CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions + +ASFLAGS := $(ARCH) +LDFLAGS = -g $(ARCH) -Wl,-Map,$(notdir $@).map + +#--------------------------------------------------------------------------------- +# any extra libraries we wish to link with the project +#--------------------------------------------------------------------------------- +LIBS := -lgba + +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := $(LIBGBA) + +#--------------------------------------------------------------------------------- +# no real need to edit anything past this point unless you need to add additional +# rules for different file extensions +#--------------------------------------------------------------------------------- +ifneq ($(BUILD),$(notdir $(CURDIR))) +#--------------------------------------------------------------------------------- + +export OUTPUT := $(CURDIR)/$(TARGET) +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +export DEPSDIR := $(CURDIR)/$(BUILD) + +#--------------------------------------------------------------------------------- +# automatically build a list of object files for our project +#--------------------------------------------------------------------------------- +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) +BMPFILES := $(foreach dir,$(GRAPHICS),$(notdir $(wildcard $(dir)/*.bmp))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#--------------------------------------------------------------------------------- + export LD := $(CC) +#--------------------------------------------------------------------------------- +else +#--------------------------------------------------------------------------------- + export LD := $(CXX) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- + +export OFILES := $(addsuffix .o,$(BINFILES)) \ + $(BMPFILES:.bmp=.o) \ + $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) + +#--------------------------------------------------------------------------------- +# build a list of include paths +#--------------------------------------------------------------------------------- +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +#--------------------------------------------------------------------------------- +# build a list of library paths +#--------------------------------------------------------------------------------- +export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) + +.PHONY: $(BUILD) clean + +#--------------------------------------------------------------------------------- +$(BUILD): + @[ -d $@ ] || mkdir -p $@ + @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + +all : $(BUILD) +#--------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr $(BUILD) $(TARGET).elf $(TARGET).gba + +#--------------------------------------------------------------------------------- +else + +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- +$(OUTPUT).gba : $(OUTPUT).elf + +$(OUTPUT).elf : $(OFILES) + + +#--------------------------------------------------------------------------------- +# The bin2o rule should be copied and modified +# for each extension used in the data directories +#--------------------------------------------------------------------------------- + +#--------------------------------------------------------------------------------- +# This rule links in binary data with the .bin extension +#--------------------------------------------------------------------------------- +%.bin.o : %.bin +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + +#--------------------------------------------------------------------------------- +# This rule links in binary data with the .raw extension +#--------------------------------------------------------------------------------- +%.raw.o : %.raw +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + +#--------------------------------------------------------------------------------- +# This rule creates assembly source files using grit +# grit takes an image file and a .grit describing how the file is to be processed +# add additional rules like this for each image extension +# you use in the graphics folders +#--------------------------------------------------------------------------------- +%.s %.h : %.bmp %.grit +#--------------------------------------------------------------------------------- + grit $< -fts -o$* + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- diff --git a/examples/gbalink/gbarom/README.md b/examples/gbalink/gbarom/README.md new file mode 100644 index 000000000..2c6183096 --- /dev/null +++ b/examples/gbalink/gbarom/README.md @@ -0,0 +1,2 @@ +This folder contains the source for the Multi Boot GBA ROM. +Build it with the devkitPro GBA toolchain. \ No newline at end of file diff --git a/examples/gbalink/gbarom/source/main.c b/examples/gbalink/gbarom/source/main.c new file mode 100644 index 000000000..a03e7c99b --- /dev/null +++ b/examples/gbalink/gbarom/source/main.c @@ -0,0 +1,54 @@ +#include +#include + +#define GBA_CHALLENGE 0x64646464 +#define GBA_RESPONSE 0x6BA006BA + +/* Register REG_JSTAT: +* Bit 1 is SET and immediately RESET (?) when the console sends a Write command over Joybus. +* Bit 3 is SET when the GBA writes to REG_JOYTR (indicating that data is ready). +* Bit 3 is RESET when the console sends a Read command over Joybus. +*/ + +/* +* Register REG_HS_CTRL: +* Bit 1 is SET when the console sends a Write command over Joybus. +* Bit 2 is SET when the console sends a Read command over Joybus. +* The GBA acknowledges a Write or Read command by writing a 1 to the respective bit. +*/ +#define JOY_WRITE_ACK 2 +#define JOY_READ_ACK 4 + +int main(void) { + irqInit(); + + consoleDemoInit(); + iprintf("\x1b[3;2HGBA Link Cable Controller\n"); + + // Enable JOY BUS mode + REG_JOYTR = 0; + REG_HS_CTRL = JOY_READ_ACK | JOY_WRITE_ACK; + REG_RCNT = R_JOYBUS; + + while (true) { + // Handle Challenge-Response + if (REG_JOYRE == GBA_CHALLENGE && REG_HS_CTRL & JOY_WRITE_ACK) { + // Received challenge, prepare response and wait for read command + REG_JOYTR = GBA_RESPONSE; + iprintf("\x1b[5;2H Waiting for N64... \n"); + while (!(REG_HS_CTRL & JOY_READ_ACK)) {} + // Acknowledge write and read commands, and clear data + REG_HS_CTRL = JOY_READ_ACK | JOY_WRITE_ACK; + REG_JOYTR = 0; + } + + // Otherwise, always send held keys + u16 keys = (REG_KEYINPUT & 0x03ff) ^ 0x03ff; + REG_JOYTR = (u32) keys; + iprintf("\x1b[5;2H 0x%04x / 0x%08lx\n", keys, (u32) keys); + if(REG_HS_CTRL & JOY_READ_ACK) { + // Acknowledge read command + REG_HS_CTRL = JOY_READ_ACK; + } + } +} diff --git a/include/gba_link.h b/include/gba_link.h new file mode 100644 index 000000000..25403fa81 --- /dev/null +++ b/include/gba_link.h @@ -0,0 +1,165 @@ +/** + * @file gba_link.h + * @author tfmoe__ + * @brief GBA Link Cable subsystem + * @ingroup gba_link + */ + +#ifndef LIBDRAGON_GBA_LINK_H +#define LIBDRAGON_GBA_LINK_H + +#include +#include + +#include "joybus.h" +#include "preview.h" + +/** + * @defgroup gba_link GBA Link Cable Subsystem + * @ingroup peripherals + * @brief GBA Link Cable interface. + * @author tfmoe__ + * + * The Nintendo GameCube Game Boy Advance Cable (DOL-011) is an accessory to + * connect a GBA to a controller port on the GameCube. It allows in-game + * communication between a GBA game and a GameCube game. The GameCube can + * also leverage the Multi Boot feature to upload a rom to the GBA. + * + * Using a passive adapter, it is possible to connect the GBA Link Cable to + * a N64. + * + * The GBA Link Cable subsystem provides an interface for communicating with + * a GBA game. It also provides an implementation of Multi Boot to upload a + * GBA rom. + * + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + + +/** @brief GBA Link Cable read/write status values */ +typedef enum +{ + /** @brief GBA Link Cable data communcation was successful. */ + GBA_LINK_IO_STATUS_OK = 0, + /** @brief GBA Link Cable device is absent or did not respond. */ + GBA_LINK_IO_STATUS_ABSENT, + /** @brief GBA Link Cable's reported status indicates that GBA was not ready to send data. */ + GBA_LINK_IO_STATUS_DATA_NOT_READY, + /** @brief GBA Link Cable's reported status is unexpected for the current I/O operation. */ + GBA_LINK_IO_STATUS_UNEXPECTED_STATUS +} gba_link_io_status_t; + +/** + * @brief GBA read callback function type. + * + * This function is called upon completion of an async Joybus GBA Link + * read operation initiated by gba_link_read_async(). + * + * @param port The Joybus port the GBA is connected to. + * @param data The data received from the GBA. + * @param gba_status The status received from the GBA. + * @param io_status Indicates whether the operation was successful or not. + * @param ctx User-defined context pointer. + */ +typedef void (*gba_link_read_callback_t)(int port, const uint8_t data[JOYBUS_GBA_LINK_CABLE_DATA_SIZE], uint8_t gba_status, gba_link_io_status_t io_status, void *ctx); + +/** + * @brief GBA write callback function type. + * + * This function is called upon completion of an async Joybus GBA Link + * write operation initiated by gba_link_write_async(). + * + * @param port The Joybus port the GBA is connected to. + * @param gba_status The status received from the GBA. + * @param io_status Indicates whether the operation was successful or not. + * @param ctx User-defined context pointer. + */ +typedef void (*gba_link_write_callback_t)(int port, uint8_t gba_status, gba_link_io_status_t io_status, void *ctx); + +/** + * @brief Whether a GBA Link Cable is plugged in to a Joybus port. + * + * @param port The Joybus port number + * + * @retval true A GBA Link Cable is connected to the Joybus port. + * @retval false No GBA Link Cable is connected to the Joybus port. + */ +LIBDRAGON_PREVIEW_API +bool gba_link_is_connected(int port); + +/** + * @brief Get the last known GBA status for a specific port. + * + * This function returns the last known status for a specific Joybus port. + * + * @note Returns 0 if the given port is not connected to a GBA Link Cable. + * + * @param port The Joybus port number + * + * @return The last known status for the specified port. + */ +LIBDRAGON_PREVIEW_API +uint8_t gba_link_get_status(int port); + +/** + * @brief Asynchronously perform a Joybus GBA Link read command. + * + * @param port The controller port of the GBA Link to read from. + * @param callback A function pointer to call when the operation completes. + * @param ctx A user data pointer to pass into the callback function. + */ +LIBDRAGON_PREVIEW_API +void gba_link_read_async(int port, gba_link_read_callback_t callback, void *ctx); + +/** + * @brief Asynchronously perform a Joybus GBA Link write command. + * + * @param port The controller port of the GBA Link to write to. + * @param[in] data The data to write to the GBA Link. + * @param callback A function pointer to call when the operation completes. + * @param ctx A user data pointer to pass into the callback function. + */ +LIBDRAGON_PREVIEW_API +void gba_link_write_async(int port, const uint8_t *data, gba_link_write_callback_t callback, void *ctx); + +/** + * @brief Synchronously perform a Joybus GBA Link read command. + * + * @param port The controller port of the GBA Link to read from. + * @param[out] data The 4 bytes of data that was read from the GBA. + * @param[out] gba_status The status of the GBA as returned by it. + * + * @retval #GBA_LINK_IO_STATUS_OK The data was read successfully. + * @retval #GBA_LINK_IO_STATUS_ABSENT The data was not read successfully because the device is absent. + * @retval #GBA_LINK_IO_STATUS_DATA_NOT_READY The data was not read successfully because the device is not ready. + * @retval #GBA_LINK_IO_STATUS_UNEXPECTED_STATUS The data was not read successfully because the device is in an invalid state. + */ +LIBDRAGON_PREVIEW_API +gba_link_io_status_t gba_link_read(int port, uint8_t *data, uint8_t* gba_status); + +/** + * @brief Synchronously perform a Joybus GBA Link write command. + * + * @param port The controller port of the GBA Link to write to. + * @param[in] data The 4 bytes of data to write to the GBA. + * @param[out] gba_status The status of the GBA as returned by it. + * + * @retval #GBA_LINK_IO_STATUS_OK The data was written successfully. + * @retval #GBA_LINK_IO_STATUS_ABSENT The data was not written successfully because the device is absent. + * @retval #GBA_LINK_IO_STATUS_UNEXPECTED_STATUS The data was not written successfully because the device is in an invalid state. + */ +LIBDRAGON_PREVIEW_API +gba_link_io_status_t gba_link_write(int port, const uint8_t *data, uint8_t* gba_status); + + +#ifdef __cplusplus +} +#endif + +/** @} */ /* gba_link */ + +#endif /* LIBDRAGON_GBA_LINK_H */ diff --git a/include/gba_link_multiboot.h b/include/gba_link_multiboot.h new file mode 100644 index 000000000..d6ab7c4cb --- /dev/null +++ b/include/gba_link_multiboot.h @@ -0,0 +1,167 @@ +/** + * @file gba_link_multiboot.h + * @author tfmoe__ + * @brief GBA Link Cable support for Multi Boot + * @ingroup gba_link + */ + +#ifndef LIBDRAGON_GBA_LINK_MULTIBOOT_H +#define LIBDRAGON_GBA_LINK_MULTIBOOT_H + +#include + +#include "preview.h" + +/** + * @addtogroup gba_link + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + + +/** @brief GBA Multi Boot status values */ +typedef enum +{ + /** @brief GBA Multi Boot was successful. */ + GBA_LINK_MULTIBOOT_OK = 0, + /** @brief GBA Multi Boot failed because of an issue in I/O operations. */ + GBA_LINK_MULTIBOOT_BAD_IO, + /** @brief GBA Multi Boot failed because the GBA reported a status inconsistent with I/O operations. */ + GBA_LINK_MULTIBOOT_BAD_STATUS, + /** @brief GBA Multi Boot failed because the GBA reported a dummy byte inconsistent with uploaded data. */ + GBA_LINK_MULTIBOOT_BAD_DUMMY_BYTE, + /** @brief GBA Multi Boot failed because of an issue while reading file. */ + GBA_LINK_MULTIBOOT_BAD_FILE +} gba_link_multiboot_status_t; + +/** @brief GBA Multi Boot logo base color */ +typedef enum { + /** @brief Pink base color. + * @note Transitions to blue when combined with a positive speed. + * @note Transitions from blue when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_0_PINK = 0, + /** @brief Blue base color. + * @note Transitions to cyan when combined with a positive speed. + * @note Transitions from cyan when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_1_BLUE, + /** @brief Cyan base color. + * @note Transitions to green when combined with a positive speed. + * @note Transitions from green when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_2_CYAN, + /** @brief Green base color. + * @note Transitions to yellow when combined with a positive speed. + * @note Transitions from yellow when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_3_GREEN, + /** @brief Yellow base color. + * @note Transitions to red when combined with a positive speed. + * @note Transitions from red when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_4_YELLOW, + /** @brief Red base color. + * @note Transitions to pink when combined with a positive speed. + * @note Transitions from pink when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_5_RED, + /** @brief Pink base color. + * @note Transitions to white when combined with a positive speed. + * @note Transitions from white when combined with a negative speed. + */ + GBA_LINK_MULTIBOOT_LOGO_COLOR_6_PINK, +} gba_link_multiboot_logo_color_t; + +/** @brief GBA Multi Boot logo speed +* +* Null speed show base color only. +* Positive speeds animate the logo, transition from the base color. +* Negative speeds animate the logo, transition to the base color. +*/ +typedef enum { + GBA_LINK_MULTIBOOT_LOGO_SPEED_MINUS_4 = -4, + GBA_LINK_MULTIBOOT_LOGO_SPEED_MINUS_3, + GBA_LINK_MULTIBOOT_LOGO_SPEED_MINUS_2, + GBA_LINK_MULTIBOOT_LOGO_SPEED_MINUS_1, + GBA_LINK_MULTIBOOT_LOGO_SPEED_0, + GBA_LINK_MULTIBOOT_LOGO_SPEED_PLUS_1, + GBA_LINK_MULTIBOOT_LOGO_SPEED_PLUS_2, + GBA_LINK_MULTIBOOT_LOGO_SPEED_PLUS_3, + GBA_LINK_MULTIBOOT_LOGO_SPEED_PLUS_4, +} gba_link_multiboot_logo_speed_t; + +/** + * @brief GBA Multi Boot callback function type. + * + * This function is called upon completion of a Multi Boot rom upload operation + * initiated by gba_link_multiboot_start(). + * + * @param port The Joybus port the GBA is connected to. + * @param status Multiboot execution status + * @param ctx User-defined context pointer. + */ +typedef void (*gba_link_multiboot_callback_t)(int port, gba_link_multiboot_status_t status, void *ctx); + +/** + * @brief Starts the process of asynchronously uploading a rom via GBA Link Cable. + * The GBA on the given port must be ready for Multi Boot. + * + * @param port The Joybus port the GBA is connected to. + * @param filename Path to the GBA rom file to upload. + * @param logo_color Color setting for the GBA logo displayed during upload. + * @param logo_speed Speed setting for the GBA logo displayed during upload. + * @param callback A function pointer to call when the operation completes. + * @param ctx A user data pointer to pass into the callback function. + */ +LIBDRAGON_PREVIEW_API +void gba_link_multiboot_start(int port, const char* filename, gba_link_multiboot_logo_color_t logo_color, gba_link_multiboot_logo_speed_t logo_speed, gba_link_multiboot_callback_t callback, void *ctx); + + +/** + * @brief GBA Multi Boot detection callback function type. + * + * This function is called upon completion of an async detection operation + * initiated by gba_link_multiboot_detect(). + * + * @param port The Joybus port on which GBA detection happened. + * @param multiboot_ready Wheteher a GBA Link Cable is connected to the given port and ready for Multi Boot. + * @param ctx User-defined context pointer. + */ +typedef void (*gba_link_multiboot_detect_callback_t)(int port, bool multiboot_ready, void *ctx); + +/** + * @brief Asynchronously detects a GBA Link Cable ready for Multi Boot on the given port. + * + * Repeatedly emits reset and identify commands for a given time, checking the GBA status + * for Multi Boot readiness. + * + * @param port The Joybus port on which to detect GBA Link Cable. + * @param timeout Time (in ms) after which detection is aborted if no GBA Link Cable was identified. + * @param callback A function pointer to call when the operation completes. + * @param ctx A user data pointer to pass into the callback function. + */ +LIBDRAGON_PREVIEW_API +void gba_link_multiboot_detect(int port, int timeout, gba_link_multiboot_detect_callback_t callback, void *ctx); + +/** + * @brief Get the progress of a Multi Boot upload operation on the given port. + * + * @param port The Joybus port the GBA is connected to. + * + * @return The progess (in percent), or 0 if there is no Multi Boot operation happening. + */ +LIBDRAGON_PREVIEW_API +uint8_t gba_link_multiboot_progress(int port); + + +#ifdef __cplusplus +} +#endif + +/** @} */ /* gba_link */ + +#endif /* LIBDRAGON_GBA_LINK_MULTIBOOT_H */ diff --git a/include/joybus.h b/include/joybus.h index 932d80f19..79f907923 100644 --- a/include/joybus.h +++ b/include/joybus.h @@ -76,6 +76,10 @@ extern "C" { * @brief Size of a Joybus N64 accessory read/write payload in bytes. */ #define JOYBUS_ACCESSORY_DATA_SIZE 32 +/** + * @brief Size of a Joybus GBA Link Cable read/write payload in bytes. + */ +#define JOYBUS_GBA_LINK_CABLE_DATA_SIZE 4 /** @} */ /* JOYBUS_PAYLOAD_SIZES */ /** @@ -245,6 +249,26 @@ typedef uint16_t joybus_identifier_t; * @brief Joybus identify status bit for EEPROM devices that indicates a write is in-progress. */ #define JOYBUS_IDENTIFY_STATUS_EEPROM_BUSY 0x80 +/** + * @brief Joybus identify status byte mask for GBA Link Cable status. + */ +#define JOYBUS_IDENTIFY_STATUS_GBA_MASK 0x3A +/** + * @brief Joybus identify status byte mask for GBA Link Cable GPIO flag 1. + */ +#define JOYBUS_IDENTIFY_STATUS_GBA_GPIO1 0x20 +/** + * @brief Joybus identify status byte mask for GBA Link Cable GPIO flag 0. + */ +#define JOYBUS_IDENTIFY_STATUS_GBA_GPIO0 0x10 +/** + * @brief Joybus identify status byte mask for GBA Link Cable sending flag. + */ +#define JOYBUS_IDENTIFY_STATUS_GBA_SENDING 0x08 +/** + * @brief Joybus identify status byte mask for GBA Link Cable receiving flag. + */ +#define JOYBUS_IDENTIFY_STATUS_GBA_RECEIVING 0x02 /** @} */ /** @brief Joybus detection events enumeration */ diff --git a/include/libdragon.h b/include/libdragon.h index 88e115906..d42783271 100644 --- a/include/libdragon.h +++ b/include/libdragon.h @@ -40,6 +40,8 @@ #include "controller.h" #include "rtc.h" #include "bio_sensor.h" +#include "gba_link.h" +#include "gba_link_multiboot.h" #include "mempak.h" #include "cpak.h" #include "cpakfs.h" diff --git a/src/joybus/gba_link.c b/src/joybus/gba_link.c new file mode 100644 index 000000000..37928c188 --- /dev/null +++ b/src/joybus/gba_link.c @@ -0,0 +1,207 @@ +/** + * @file gba_link.c + * @author tfmoe__ + * @brief GBA Link Cable Subsystem + * @ingroup gba_link + */ + +#include +#include + +#include "gba_link.h" +#include "joybus_commands.h" +#include "joypad.h" + +/** + * @addtogroup gba_link + * @{ + */ + + +bool gba_link_is_connected(int port) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + return joybus_get_identifier(port, NULL) == JOYBUS_IDENTIFIER_GBA_LINK_CABLE; +} + +uint8_t gba_link_get_status(int port) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + uint8_t status; + if (joybus_get_identifier(port, &status) != JOYBUS_IDENTIFIER_GBA_LINK_CABLE) { + return 0; + } + return status; +} + +/** + * @brief Async read command context + */ +typedef struct +{ + int port; + gba_link_read_callback_t callback; + void *ctx; +} gba_link_cable_read_context_t; + +static void gba_link_read_callback(uint64_t *out_dwords, void *ctx) +{ + const uint8_t *out_bytes = (void *)out_dwords; + gba_link_cable_read_context_t* context = (void*)ctx; + joypad_port_t port = context->port; + + const joybus_cmd_gba_link_cable_read_port_t *cmdr = + (void *)&out_bytes[port + JOYBUS_COMMAND_METADATA_SIZE]; + + gba_link_io_status_t io_status = GBA_LINK_IO_STATUS_OK; + // Check for joybus error (no device) + if ((out_bytes[port+1] & 0x80) != 0) { + io_status = GBA_LINK_IO_STATUS_ABSENT; + } + // Check GBA status + if ((cmdr->recv.status & JOYBUS_IDENTIFY_STATUS_GBA_SENDING) == 0) { + io_status = GBA_LINK_IO_STATUS_DATA_NOT_READY; + } + + gba_link_read_callback_t callback = context->callback; + if (callback != NULL) { + // Command data may be misaligned, so we copy it to an aligned word + uint32_t copy; + memcpy(©, cmdr->recv.data, sizeof(cmdr->recv.data)); + callback(port, (uint8_t*)©, cmdr->recv.status, io_status, (void*)context->ctx); + } + free(context); +} + +void gba_link_read_async( + int port, + gba_link_read_callback_t callback, + void *ctx +) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + uint8_t input[JOYBUS_BLOCK_SIZE] = {0}; + joybus_cmd_gba_link_cable_read_port_t cmd = { .send = { + .command = JOYBUS_COMMAND_ID_GBA_LINK_CABLE_READ, + } }; + size_t i = port; + // Set the command metadata + input[i++] = sizeof(cmd.send); + input[i++] = sizeof(cmd.recv); + // Micro-optimization: Minimize copy length + const size_t recv_offset = offsetof(typeof(cmd), recv); + memcpy(&input[i], &cmd.send, recv_offset); + i += sizeof(cmd); + // Close out the Joybus operation block + input[i] = 0xFE; + input[sizeof(input) - 1] = 0x01; + // Execute the Joybus operation asynchronously + gba_link_cable_read_context_t* gba_link_read_context = calloc(1, sizeof(gba_link_cable_read_context_t)); + gba_link_read_context->port = port; + gba_link_read_context->callback = callback; + gba_link_read_context->ctx = ctx; + joybus_exec_async(input, gba_link_read_callback, (void*)gba_link_read_context); +} + +/** + * @brief Async write command context + */ +typedef struct +{ + int port; + gba_link_write_callback_t callback; + void *ctx; +} gba_link_cable_write_context_t; + +static void gba_link_write_callback(uint64_t *out_dwords, void *ctx) +{ + const uint8_t *out_bytes = (void *)out_dwords; + gba_link_cable_write_context_t* context = (void*)ctx; + joypad_port_t port = context->port; + + const joybus_cmd_gba_link_cable_write_port_t *cmdw = + (void *)&out_bytes[port + JOYBUS_COMMAND_METADATA_SIZE]; + + gba_link_io_status_t io_status = GBA_LINK_IO_STATUS_OK; + // Check for joybus error (no device) + if ((out_bytes[port+1] & 0x80) != 0) { + io_status = GBA_LINK_IO_STATUS_ABSENT; + } + // Check GBA status + if ((cmdw->recv.status & JOYBUS_IDENTIFY_STATUS_GBA_RECEIVING) == 0) { + io_status = GBA_LINK_IO_STATUS_UNEXPECTED_STATUS; + } + + gba_link_write_callback_t callback = context->callback; + if (callback != NULL) + callback(port, cmdw->recv.status, io_status, (void*)context->ctx); + free(context); +} + +void gba_link_write_async( + int port, + const uint8_t *data, + gba_link_write_callback_t callback, + void *ctx +) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + uint8_t input[JOYBUS_BLOCK_SIZE] = {0}; + joybus_cmd_gba_link_cable_write_port_t cmd = { .send = { + .command = JOYBUS_COMMAND_ID_GBA_LINK_CABLE_WRITE, + } }; + size_t i = port; + // Set the command metadata + input[i++] = sizeof(cmd.send); + input[i++] = sizeof(cmd.recv); + // Micro-optimization: Minimize copy length + const size_t data_offset = offsetof(typeof(cmd.send), data); + memcpy(&input[i], &cmd.send, data_offset); + memcpy(&input[i + data_offset], data, sizeof(cmd.send.data)); + i += sizeof(cmd); + // Close out the Joybus operation block + input[i] = 0xFE; + input[sizeof(input) - 1] = 0x01; + // Execute the Joybus operation asynchronously + gba_link_cable_write_context_t* gba_link_write_context = calloc(1, sizeof(gba_link_cable_write_context_t)); + gba_link_write_context->port = port; + gba_link_write_context->callback = callback; + gba_link_write_context->ctx = ctx; + joybus_exec_async(input, gba_link_write_callback, (void*)gba_link_write_context); +} + +gba_link_io_status_t gba_link_read(int port, uint8_t *data, uint8_t* gba_status) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + joybus_cmd_gba_link_cable_read_port_t cmd = { .send = { + .command = JOYBUS_COMMAND_ID_GBA_LINK_CABLE_READ, + } }; + // Execute the command + joybus_exec_cmd_struct(port, cmd); + // Copy the data from the command receive buffer + memcpy(data, cmd.recv.data, sizeof(cmd.recv.data)); + *gba_status = cmd.recv.status; + if ((*gba_status & JOYBUS_IDENTIFY_STATUS_GBA_SENDING) == 0) { + return GBA_LINK_IO_STATUS_DATA_NOT_READY; + } + return GBA_LINK_IO_STATUS_OK; +} + +gba_link_io_status_t gba_link_write(int port, const uint8_t *data, uint8_t* gba_status) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + joybus_cmd_gba_link_cable_write_port_t cmd = { .send = { + .command = JOYBUS_COMMAND_ID_GBA_LINK_CABLE_WRITE, + } }; + // Copy the data to the command send buffer + memcpy(cmd.send.data, data, sizeof(cmd.send.data)); + // Execute the command + joybus_exec_cmd_struct(port, cmd); + *gba_status = cmd.recv.status; + if ((*gba_status & JOYBUS_IDENTIFY_STATUS_GBA_RECEIVING) == 0) { + return GBA_LINK_IO_STATUS_UNEXPECTED_STATUS; + } + return GBA_LINK_IO_STATUS_OK; +} + +/** @} */ /* gba_link */ diff --git a/src/joybus/gba_link_multiboot.c b/src/joybus/gba_link_multiboot.c new file mode 100644 index 000000000..d43d25d98 --- /dev/null +++ b/src/joybus/gba_link_multiboot.c @@ -0,0 +1,429 @@ +/** + * @file gba_link_multiboot.c + * @author tfmoe__ + * @brief GBA Link Cable support for Multi Boot + * @ingroup gba_link + */ + +#include +#include + +#include "asset.h" +#include "interrupt.h" +#include "gba_link.h" +#include "gba_link_multiboot.h" +#include "joybus_commands.h" +#include "joypad.h" +#include "timer.h" + +/** + * @addtogroup gba_link + * @{ + */ + + +/** @brief Delay between two attempts to detect GBA Link ready for Multi Boot */ +#define IDENTIFY_RETRY_DELAY_US TIMER_TICKS(5000) + +/** @brief Payload length must be rounded up to the nearest 8-byte boundary */ +#define ROUND_UP_8(val) (((val) + 7) & ~7) + +// Keys extracted from secret string " by Kawasedo" +/** @brief Key: " by " */ +#define MAGIC_BY 0x20627920 +/** @brief Key: "Kawa" */ +#define MAGIC_KAWA 0x4b617761 +/** @brief Key: "sedo" */ +#define MAGIC_SEDO 0x7365646f + +/** @brief Calculate key B from payload length and logo settings */ +static uint32_t calc_key(uint32_t length, gba_link_multiboot_logo_speed_t speed, gba_link_multiboot_logo_color_t color) { + // Compute payload length in 8-byte blocks, past the minimum 512 bytes + length = (length - 0x200) >> 3; + // Compute logo settings + uint32_t logo = speed < 0 + ? (color << 3 | (3 - speed)) + : (speed > 0 + ? (color << 3 | (speed - 1)) + : (color | 0x38) + ); + // Mangle payload length + uint32_t mangled = (length & 0x4000) << 2 | (length & 0x3f80) << 1 | (length & 0x7f); + // Combine mangled length with logo settings + uint32_t key = (logo << 17) | mangled; + // Checksum + uint8_t checksum = ((key >> 16) + (key >> 8) + key) & 0x7f; + // Combine key with checksum and fixed bits + key = (checksum << 24) | 0x80808080 | key; + // XOR with the correct key + uint32_t xorkey = (key & 0x200) ? MAGIC_SEDO : MAGIC_KAWA; + return __builtin_bswap32(key) ^ xorkey; +} + +/** @brief Update the running CRC with latest payload word */ +static uint32_t update_crc(uint32_t crc, uint32_t val) { + for (int i = 0; i < 0x20; i++) { + if ((crc ^ val) & 1) { + crc >>= 1; + crc ^= 0xa1c1; + } else { + crc >>= 1; + } + val >>= 1; + } + return crc; +} + +/** @brief Cipher payload word and update session key */ +static uint32_t cipher_data(uint32_t data, int i, uint32_t* sessionkey) { + *sessionkey = (*sessionkey * __builtin_bswap32(MAGIC_KAWA)) + 1; + data ^= *sessionkey; + data ^= ((~(i + (0x20<<20))) + 1); + data ^= __builtin_bswap32(MAGIC_BY); + return data; +} + + +/** @brief Internal state for Multi Boot */ +typedef enum { + GBA_MULTIBOOT_IDLE = 0, + GBA_MULTIBOOT_CLEARTEXT, + GBA_MULTIBOOT_CIPHERTEXT, + GBA_MULTIBOOT_CRC, + GBA_MULTIBOOT_CHECK, + GBA_MULTIBOOT_DONE, +} multiboot_state_t; + +/** + * @brief Multi Boot context + */ +typedef struct +{ + FILE* file; + int length; + gba_link_multiboot_logo_color_t logo_color; + gba_link_multiboot_logo_speed_t logo_speed; + multiboot_state_t state; + uint32_t crc; + uint32_t dummy[8]; + uint32_t sessionkey; + int sent; + gba_link_multiboot_callback_t callback; + void *ctx; +} multiboot_context_t; + +/** @brief Per-port Multi Boot contexts */ +static multiboot_context_t multiboot_contexts[JOYPAD_PORT_COUNT]; + +/** @brief Terminate Multi Boot, execute callback with status, close file and clear context */ +static void terminate_multiboot(int port, gba_link_multiboot_status_t status, multiboot_context_t* context) { + gba_link_multiboot_callback_t callback = context->callback; + if (callback != NULL) + callback(port, status, (void*)context->ctx); + fclose(context->file); + memset(context, 0, sizeof(multiboot_context_t)); +} + +static void gba_link_write_callback(int port, uint8_t gba_status, gba_link_io_status_t io_status, void *ctx); + +static void gba_link_read_callback(int port, const uint8_t data[JOYBUS_GBA_LINK_CABLE_DATA_SIZE], uint8_t gba_status, gba_link_io_status_t io_status, void *ctx) { + multiboot_context_t* context = (void*) ctx; + // Handle I/O errors + if (io_status != GBA_LINK_IO_STATUS_OK) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_IO, context); + return; + } + switch (context->state) { + case GBA_MULTIBOOT_IDLE: { + // Check GBA status + if (gba_status != (JOYBUS_IDENTIFY_STATUS_GBA_GPIO0 | JOYBUS_IDENTIFY_STATUS_GBA_SENDING)) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_STATUS, context); + return; + } + // Compute session key from received data + context->sessionkey = *(uint32_t*)data; + context->sessionkey = context->sessionkey ^ MAGIC_SEDO; + context->sessionkey = __builtin_bswap32(context->sessionkey); + // Compute host key from payload length and palette configuration + uint32_t calc = calc_key(ROUND_UP_8(context->length), context->logo_speed, context->logo_color); + context->crc = 0x15a0; + context->sent = 0; + context->state = GBA_MULTIBOOT_CLEARTEXT; + gba_link_write_async(port, (uint8_t*) &calc, gba_link_write_callback, ctx); + break; + } + case GBA_MULTIBOOT_CLEARTEXT: + case GBA_MULTIBOOT_CIPHERTEXT: + case GBA_MULTIBOOT_CRC: + break; + case GBA_MULTIBOOT_CHECK: { + uint32_t d = __builtin_bswap32(*(uint32_t*)data); + if (d != context->dummy[4] && d != context->dummy[5] && d != context->dummy[6]) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_DUMMY_BYTE, context); + return; + } + context->state = GBA_MULTIBOOT_DONE; + terminate_multiboot(port, GBA_LINK_MULTIBOOT_OK, context); + break; + } + case GBA_MULTIBOOT_DONE: { + break; + } + } +} + +static void gba_link_write_callback(int port, uint8_t gba_status, gba_link_io_status_t io_status, void *ctx) { + multiboot_context_t* context = (void*) ctx; + // Handle I/O errors + if (io_status != GBA_LINK_IO_STATUS_OK) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_IO, context); + return; + } + switch (context->state) { + case GBA_MULTIBOOT_IDLE: + break; + case GBA_MULTIBOOT_CLEARTEXT: { + // Check GBA status + if (context->sent > 0 && !(gba_status & JOYBUS_IDENTIFY_STATUS_GBA_GPIO1)) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_STATUS, context); + return; + } + if ((gba_status & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0) != (~(context->sent<<2) & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0)) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_STATUS, context); + return; + } + uint8_t buf[JOYBUS_GBA_LINK_CABLE_DATA_SIZE]; + size_t nread; + if ((nread = fread(buf, sizeof(buf[0]), sizeof(buf), context->file)) != 0) { + gba_link_write_async(port, buf, gba_link_write_callback, ctx); + context->sent += 4; + if (context->sent == 0xc0) { + context->state = GBA_MULTIBOOT_CIPHERTEXT; + } + } else { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_FILE, context); + return; + } + break; + } + case GBA_MULTIBOOT_CIPHERTEXT: { + if ((gba_status & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0) != (~(context->sent<<2) & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0)) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_STATUS, context); + return; + } + // ROM data must be ciphered for the remaining of the payload + // CRC is updated for each packet sent + uint32_t d = 0; // If rounded-length is larger than file length, pad with zeroes + if (context->sent < context->length) { + uint8_t buf[JOYBUS_GBA_LINK_CABLE_DATA_SIZE]; + size_t nread; + if ((nread = fread(buf, sizeof(buf[0]), sizeof(buf), context->file)) != 0) { + d = __builtin_bswap32(*(uint32_t*)buf); + } else { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_FILE, context); + return; + } + } + uint32_t cipherText = __builtin_bswap32(cipher_data(d, context->sent, &context->sessionkey)); + context->crc = update_crc(context->crc, d); + // Collect dummy bytes to check against at the end of Multi Boot + if (context->sent == 0x1f8) { + context->dummy[0] = d; + context->dummy[2] = __builtin_bswap32(cipherText); + } else if (context->sent == 0x1fc) { + context->dummy[1] = d; + context->dummy[3] = __builtin_bswap32(cipherText); + context->dummy[4] = context->dummy[2] * context->dummy[3]; + context->dummy[5] = context->dummy[0] * context->dummy[1]; + context->dummy[6] = context->dummy[0] * context->dummy[3]; + } + gba_link_write_async(port, (uint8_t*) &cipherText, gba_link_write_callback, ctx); + context->sent += 4; + if (context->sent == ROUND_UP_8(context->length)) { + context->state = GBA_MULTIBOOT_CRC; + } + break; + } + case GBA_MULTIBOOT_CRC: { + if ((gba_status & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0) != (~(context->sent<<2) & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0)) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_STATUS, context); + return; + } + // Finalize and send CRC + context->crc |= (ROUND_UP_8(context->length) << 16); + context->crc = __builtin_bswap32(cipher_data(context->crc, context->sent, &context->sessionkey)); + gba_link_write_async(port, (uint8_t*) &context->crc, gba_link_write_callback, ctx); + context->state = GBA_MULTIBOOT_CHECK; + break; + } + case GBA_MULTIBOOT_CHECK: { + if ((gba_status & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0) != (~((context->sent+4)<<2) & JOYBUS_IDENTIFY_STATUS_GBA_GPIO0)) { + terminate_multiboot(port, GBA_LINK_MULTIBOOT_BAD_STATUS, context); + return; + } + gba_link_read_async(port, gba_link_read_callback, ctx); + break; + } + case GBA_MULTIBOOT_DONE: + break; + } +} + +void gba_link_multiboot_start( + int port, + const char *file_name, + gba_link_multiboot_logo_color_t logo_color, + gba_link_multiboot_logo_speed_t logo_speed, + gba_link_multiboot_callback_t callback, + void *ctx +) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + memset(&multiboot_contexts[port], 0, sizeof(multiboot_context_t)); + multiboot_contexts[port].callback = callback; + multiboot_contexts[port].ctx = ctx; + multiboot_contexts[port].file = asset_fopen(file_name, &multiboot_contexts[port].length); + multiboot_contexts[port].logo_color = logo_color; + multiboot_contexts[port].logo_speed = logo_speed; + gba_link_read_async(port, gba_link_read_callback, (void*)&multiboot_contexts[port]); +} + + +/** + * @brief Async detection context + */ +typedef struct +{ + int port; + bool pending; + uint8_t progress; + gba_link_multiboot_detect_callback_t callback; + timer_link_t *retry_timer; + timer_link_t *abort_timer; + void *ctx; +} gba_link_multiboot_detect_context_t; + +/** @brief Per-port detection contexts */ +static gba_link_multiboot_detect_context_t gba_link_multiboot_detect_contexts[JOYPAD_PORT_COUNT]; + +static void gba_link_multiboot_identify_callback(uint64_t *out_dwords, void *ctx); + +static void queue_joybus_input_reset_async(gba_link_multiboot_detect_context_t* context) { + joybus_cmd_reset_port_t cmd = { .send = { + .command = JOYBUS_COMMAND_ID_RESET, + } }; + // Allocate the Joybus operation block input and output buffers + uint8_t input[JOYBUS_BLOCK_SIZE] = {0}; + // Skip commands on ports before the desired port offset + size_t i = context->port; + // Set the command metadata + input[i++] = sizeof(cmd.send); + input[i++] = sizeof(cmd.recv); + // Copy the send_data into the input buffer + memcpy( &input[i], (void *)&cmd.send, sizeof(cmd.send) ); + i += sizeof(cmd.send) + sizeof(cmd.recv); + // Close out the Joybus operation block + input[i] = 0xFE; + input[sizeof(input) - 1] = 0x01; + joybus_exec_async(input, NULL, NULL); +} + +static void queue_joybus_input_identify_async(gba_link_multiboot_detect_context_t* context) { + joybus_cmd_identify_port_t cmd = { .send = { + .command = JOYBUS_COMMAND_ID_IDENTIFY, + } }; + // Allocate the Joybus operation block input and output buffers + uint8_t input[JOYBUS_BLOCK_SIZE] = {0}; + // Skip commands on ports before the desired port offset + size_t i = context->port; + // Set the command metadata + input[i++] = sizeof(cmd.send); + input[i++] = sizeof(cmd.recv); + // Copy the send_data into the input buffer + memcpy( &input[i], (void *)&cmd.send, sizeof(cmd.send) ); + i += sizeof(cmd.send) + sizeof(cmd.recv); + // Close out the Joybus operation block + input[i] = 0xFE; + input[sizeof(input) - 1] = 0x01; + joybus_exec_async(input, gba_link_multiboot_identify_callback, (void*)context); +} + +static void retry_identify(int ovfl, void *ctx) { + gba_link_multiboot_detect_context_t* context = (void*)ctx; + delete_timer(context->retry_timer); + timer_close(); + context->retry_timer = NULL; + queue_joybus_input_reset_async(context); + queue_joybus_input_identify_async(context); +} + +static void abort_identify(int ovfl, void *ctx) { + gba_link_multiboot_detect_context_t* context = (void*)ctx; + delete_timer(context->abort_timer); + timer_close(); + context->abort_timer = NULL; + context->pending = false; +} + +static void gba_link_multiboot_identify_callback(uint64_t *out_dwords, void *ctx) { + const uint8_t *out_bytes = (void *)out_dwords; + gba_link_multiboot_detect_context_t* context = (void*)ctx; + size_t i = context->port; + const joybus_cmd_identify_port_t *cmd = (void *)&out_bytes[i + JOYBUS_COMMAND_METADATA_SIZE]; + bool multiboot_ready = false; + if ((out_bytes[i+1] & 0x80) == 0 + && cmd->recv.identifier == JOYBUS_IDENTIFIER_GBA_LINK_CABLE + && cmd->recv.status == (JOYBUS_IDENTIFY_STATUS_GBA_GPIO0 | JOYBUS_IDENTIFY_STATUS_GBA_SENDING) + ) { + multiboot_ready = true; + context->pending = false; + } + + if (!context->pending) { + if (context->abort_timer != NULL) { + delete_timer(context->abort_timer); + timer_close(); + } + gba_link_multiboot_detect_callback_t callback = context->callback; + if (callback != NULL) + callback(context->port, multiboot_ready, (void*)context->ctx); + memset(context, 0, sizeof(gba_link_multiboot_detect_context_t)); + } else { + timer_init(); + context->retry_timer = new_timer_context(IDENTIFY_RETRY_DELAY_US, TF_ONE_SHOT, retry_identify, context); + } +} + +void gba_link_multiboot_detect(int port, int timeout, gba_link_multiboot_detect_callback_t callback, void *ctx) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + // Disabled during reset + if( exception_reset_time() > 0 ) { return; } + // Already in-progress + if (gba_link_multiboot_detect_contexts[port].pending) { return; } + + memset(&gba_link_multiboot_detect_contexts[port], 0, sizeof(gba_link_multiboot_detect_context_t)); + gba_link_multiboot_detect_contexts[port].port = port; + gba_link_multiboot_detect_contexts[port].pending = true; + gba_link_multiboot_detect_contexts[port].progress = 0; + gba_link_multiboot_detect_contexts[port].callback = callback; + gba_link_multiboot_detect_contexts[port].retry_timer = NULL; + gba_link_multiboot_detect_contexts[port].ctx = ctx; + // Set abort timer + timer_init(); + gba_link_multiboot_detect_contexts[port].abort_timer = new_timer_context(TIMER_TICKS(timeout * 1000), TF_ONE_SHOT, abort_identify, (void*)&gba_link_multiboot_detect_contexts[port]); + queue_joybus_input_reset_async(&gba_link_multiboot_detect_contexts[port]); + queue_joybus_input_identify_async(&gba_link_multiboot_detect_contexts[port]); +} + +uint8_t gba_link_multiboot_progress(int port) +{ + assert((port >= 0) && (port < JOYPAD_PORT_COUNT)); + if (multiboot_contexts[port].state == GBA_MULTIBOOT_IDLE) { + return 0; + } + return (100 * multiboot_contexts[port].sent) / multiboot_contexts[port].length; +} + + +/** @} */ /* gba_link */ diff --git a/src/joybus/joybus_commands.h b/src/joybus/joybus_commands.h index 1057c26a2..c360684e9 100644 --- a/src/joybus/joybus_commands.h +++ b/src/joybus/joybus_commands.h @@ -172,11 +172,25 @@ typedef joybus_cmd_n64_accessory_read_port_t joybus_cmd_64gb_link_cable_read_por /** * @brief "GBA Link Cable Read" Joybus command structure. * - * Identical to the "N64 Accessory Read" command but with a different command ID. - * * @see #JOYBUS_COMMAND_ID_GBA_LINK_CABLE_READ */ -typedef joybus_cmd_n64_accessory_read_port_t joybus_cmd_gba_link_cable_read_port_t; +typedef struct __attribute__((packed)) joybus_cmd_gba_link_cable_read_port_s +{ + /** @brief "GBA Link Cable Read" command send data */ + struct __attribute__((packed)) + { + /** @brief Joybus command ID (#JOYBUS_COMMAND_ID_GBA_LINK_CABLE_READ) */ + uint8_t command; + } send; + /** @brief "GBA Link Cable Read" command receive data */ + struct __attribute__((packed)) + { + /** @brief 4-byte payload of data read from the GBA. */ + uint8_t data[JOYBUS_GBA_LINK_CABLE_DATA_SIZE]; + /** @brief GBA status (lower 8 bits of JOYSTAT register). */ + uint8_t status; + } recv; +} joybus_cmd_gba_link_cable_read_port_t; /** * @brief "N64 Accessory Write" Joybus command structure. @@ -216,11 +230,25 @@ typedef joybus_cmd_n64_accessory_write_port_t joybus_cmd_64gb_link_cable_write_p /** * @brief "GBA Link Cable Write" Joybus command structure. * - * Identical to the "N64 Accessory Write" command but with a different command ID. - * * @see #JOYBUS_COMMAND_ID_GBA_LINK_CABLE_WRITE */ -typedef joybus_cmd_n64_accessory_write_port_t joybus_cmd_gba_link_cable_write_port_t; +typedef struct __attribute__((packed)) joybus_cmd_gba_link_cable_write_port_s +{ + /** @brief "GBA Link Cable Write" command send data */ + struct __attribute__((packed)) + { + /** @brief Joybus command ID (#JOYBUS_COMMAND_ID_GBA_LINK_CABLE_WRITE) */ + uint8_t command; + /** @brief 4-byte payload of data to write to the GBA. */ + uint8_t data[JOYBUS_GBA_LINK_CABLE_DATA_SIZE]; + } send; + /** @brief "GBA Link Cable Write" command receive data */ + struct __attribute__((packed)) + { + /** @brief GBA status (lower 8 bits of JOYSTAT register). */ + uint8_t status; + } recv; +} joybus_cmd_gba_link_cable_write_port_t; /** * @brief "Identify" Joybus command structure. diff --git a/src/joybus/libdragon.mk b/src/joybus/libdragon.mk index 8b324114e..b3208429e 100644 --- a/src/joybus/libdragon.mk +++ b/src/joybus/libdragon.mk @@ -8,6 +8,8 @@ LIBDRAGON_OBJS += \ $(BUILD_DIR)/joybus/cpakfs_fsck.o \ $(BUILD_DIR)/joybus/eeprom.o \ $(BUILD_DIR)/joybus/eepromfs.o \ + $(BUILD_DIR)/joybus/gba_link.o \ + $(BUILD_DIR)/joybus/gba_link_multiboot.o \ $(BUILD_DIR)/joybus/joybus_accessory.o \ $(BUILD_DIR)/joybus/joybus_rtc.o \ $(BUILD_DIR)/joybus/joybus.o \