new bootloader

This commit is contained in:
Polprzewodnikowy 2021-12-04 19:34:34 +01:00
parent 4a3108e1de
commit 523c32d66c
31 changed files with 24771 additions and 663 deletions

6
.gitignore vendored
View File

@ -1,4 +1,4 @@
**/.DS_Store
**/.vscode **/.vscode
*.bak **/*.bak
*.zip **/*.zip
.DS_Store

View File

@ -169,13 +169,12 @@ module n64_flashram (
end end
endcase endcase
end end
end else begin
if (bus.address[1] && flashram_state == FS_STATUS) begin
flashram_status[B_ERASE_BUSY] <= bus.wdata[B_ERASE_BUSY];
flashram_status[B_WRITE_BUSY] <= bus.wdata[B_WRITE_BUSY];
end
end end
// else begin
// if (bus.address[1] && flashram_state == FS_STATUS) begin
// flashram_status[B_ERASE_DONE] <= bus.wdata[B_ERASE_DONE];
// flashram_status[B_WRITE_DONE] <= bus.wdata[B_WRITE_DONE];
// end
// end
end end
end end
end end

View File

@ -297,7 +297,7 @@ module n64_pi (
first_write_op <= 1'b1; first_write_op <= 1'b1;
load_starting_address <= 1'b1; load_starting_address <= 1'b1;
starting_id <= next_id; starting_id <= next_id;
starting_address <= {starting_address[31:16], n64_pi_ad_input[15:1], 1'b0} + next_offset; starting_address <= {starting_address[31:16], n64_pi_ad_input[15:1], 1'b0};
end end
if (write_op) begin if (write_op) begin
@ -314,7 +314,10 @@ module n64_pi (
bus.write <= 1'b1; bus.write <= 1'b1;
if (load_starting_address) begin if (load_starting_address) begin
bus.id <= starting_id; bus.id <= starting_id;
bus.address <= starting_address; bus.address <= starting_address + next_offset;
if (starting_id == sc64::ID_N64_FLASHRAM) begin
bus.address <= starting_address;
end
load_starting_address <= 1'b0; load_starting_address <= 1'b0;
end end
bus.wdata <= write_fifo_rdata; bus.wdata <= write_fifo_rdata;
@ -324,18 +327,16 @@ module n64_pi (
bus.write <= 1'b0; bus.write <= 1'b0;
if (load_starting_address) begin if (load_starting_address) begin
bus.id <= starting_id; bus.id <= starting_id;
bus.address <= starting_address + next_offset;
if (starting_id == sc64::ID_N64_FLASHRAM && cfg.flashram_read_mode) begin if (starting_id == sc64::ID_N64_FLASHRAM && cfg.flashram_read_mode) begin
bus.id <= sc64::ID_N64_SDRAM; bus.id <= sc64::ID_N64_SDRAM;
end end
bus.address <= starting_address;
load_starting_address <= 1'b0; load_starting_address <= 1'b0;
end end
end end
end else begin end else if (bus.ack) begin
if (bus.ack) begin bus.request <= 1'b0;
bus.request <= 1'b0; bus.address <= bus.address + 2'd2;
bus.address <= bus.address + 2'd2;
end
end end
if (end_op) begin if (end_op) begin

View File

@ -6,20 +6,32 @@ OBJDUMP = $(TOOLCHAIN)objdump
SIZE = $(TOOLCHAIN)size SIZE = $(TOOLCHAIN)size
FLAGS = -march=vr4300 -mtune=vr4300 -falign-functions=32 $(USER_FLAGS) FLAGS = -march=vr4300 -mtune=vr4300 -falign-functions=32 $(USER_FLAGS)
CFLAGS = -Os -Wall -ffunction-sections -fdata-sections -ffreestanding -G 0 -MMD -MP CFLAGS = -Os -Wall -ffunction-sections -fdata-sections -ffreestanding -MMD -MP
ASFLAGS = -Wa,-I$(N64_INST)/mips64-elf/lib ASFLAGS = -Wa,-I$(N64_INST)/mips64-elf/lib
LDFLAGS = -lc -nostartfiles -Wl,--gc-sections LDFLAGS = -lc -nostartfiles -Wl,--gc-sections
SRC_DIR = src SRC_DIR = src
BUILD_DIR = build BUILD_DIR = build
SRC_FILES = startup.S main.c sys.c sc64.c syscalls.c crc32.c SRC_FILES = \
startup.S \
boot.c \
crc32.c \
init.c \
main.c \
sc64.c \
sys.c \
syscalls.c \
fatfs/diskio.c \
fatfs/ff.c \
fatfs/ffsystem.c \
fatfs/ffunicode.c
SRCS = $(addprefix $(SRC_DIR)/, $(SRC_FILES)) SRCS = $(addprefix $(SRC_DIR)/, $(SRC_FILES))
OBJS = $(addprefix $(BUILD_DIR)/, $(notdir $(patsubst %,%.o,$(SRCS)))) OBJS = $(addprefix $(BUILD_DIR)/, $(notdir $(patsubst %,%.o,$(SRCS))))
DEPS = $(OBJS:.o=.d) DEPS = $(OBJS:.o=.d)
VPATH = $(SRC_DIR) VPATH = $(SRC_DIR) $(SRC_DIR)/fatfs
$(@info $(shell mkdir -p ./$(BUILD_DIR) &> /dev/null)) $(@info $(shell mkdir -p ./$(BUILD_DIR) &> /dev/null))
@ -31,7 +43,7 @@ $(BUILD_DIR)/%.c.o: %.c
$(BUILD_DIR)/n64boot.elf: $(OBJS) N64.ld $(BUILD_DIR)/n64boot.elf: $(OBJS) N64.ld
$(CXX) $(FLAGS) $(LDFLAGS) -TN64.ld $(OBJS) -o $@ $(CXX) $(FLAGS) $(LDFLAGS) -TN64.ld $(OBJS) -o $@
@$(OBJDUMP) -D $@ > $(BUILD_DIR)/n64boot.lst @$(OBJDUMP) -S $@ > $(BUILD_DIR)/n64boot.lst
$(BUILD_DIR)/n64boot.bin: $(BUILD_DIR)/n64boot.elf $(BUILD_DIR)/n64boot.bin: $(BUILD_DIR)/n64boot.elf
@$(OBJCOPY) -O binary $< $@ @$(OBJCOPY) -O binary $< $@

187
sw/n64/src/boot.c Normal file
View File

@ -0,0 +1,187 @@
#include "boot.h"
#include "crc32.h"
#include "sc64.h"
#include "sys.h"
extern uint32_t ipl2 __attribute__((section(".data")));
typedef struct {
const uint32_t crc32;
const uint8_t seed;
const uint8_t version;
} ipl3_crc32_t;
static const ipl3_crc32_t ipl3_crc32[] = {
{ .crc32 = 0x587BD543, .seed = 0xAC, .version = 0 }, // CIC5101
{ .crc32 = 0x6170A4A1, .seed = 0x3F, .version = 1 }, // CIC6101
{ .crc32 = 0x009E9EA3, .seed = 0x3F, .version = 1 }, // CIC7102
{ .crc32 = 0x90BB6CB5, .seed = 0x3F, .version = 0 }, // CICx102
{ .crc32 = 0x0B050EE0, .seed = 0x78, .version = 0 }, // CICx103
{ .crc32 = 0x98BC2C86, .seed = 0x91, .version = 0 }, // CICx105
{ .crc32 = 0xACC8580A, .seed = 0x85, .version = 0 }, // CICx106
{ .crc32 = 0x0C965795, .seed = 0xDD, .version = 0 }, // JP 64DD
{ .crc32 = 0x10C68B18, .seed = 0xDD, .version = 0 }, // JP 64DD dev
{ .crc32 = 0x0E018159, .seed = 0xDD, .version = 0 }, // JP 64DD retail
{ .crc32 = 0x8FEBA21E, .seed = 0xDE, .version = 0 }, // US 64DD retail
};
bool boot_get_tv_type (boot_info_t *info) {
io32_t *device_base_address = ROM_CART;
if (info->device_type == BOOT_DEVICE_TYPE_DD) {
device_base_address = ROM_DDIPL;
}
char region = ((pi_io_read(&device_base_address[15]) >> 8) & 0xFF);
switch (region) {
case 'D':
case 'F':
case 'H':
case 'I':
case 'P':
case 'S':
case 'W':
case 'X':
case 'Y':
info->tv_type = BOOT_TV_TYPE_PAL;
break;
case '7':
case 'A':
case 'C':
case 'E':
case 'J':
case 'K':
case 'N':
case 'U':
info->tv_type = BOOT_TV_TYPE_NTSC;
break;
case 'B':
info->tv_type = BOOT_TV_TYPE_MPAL;
break;
default:
LOG_E("Unknown region: [0x%02X]\r\n", region);
return false;
}
return true;
}
bool boot_get_cic_seed_version (boot_info_t *info) {
io32_t *device_base_address = ROM_CART;
if (info->device_type == BOOT_DEVICE_TYPE_DD) {
device_base_address = ROM_DDIPL;
}
uint32_t ipl3[1008];
io32_t *ipl3_src = &device_base_address[16];
uint32_t *ipl3_dst = ipl3;
for (int i = 0; i < sizeof(ipl3); i += sizeof(uint32_t)) {
*ipl3_dst++ = pi_io_read(ipl3_src++);
}
uint32_t crc32 = crc32_calculate(ipl3, sizeof(ipl3));
for (int i = 0; i < sizeof(ipl3_crc32) / sizeof(ipl3_crc32_t); i++) {
if (ipl3_crc32[i].crc32 == crc32) {
info->cic_seed = ipl3_crc32[i].seed;
info->version = ipl3_crc32[i].version;
return true;
}
}
LOG_E("Unknown IPL3 CRC32: [0x%08lX]\r\n", crc32);
return false;
}
void boot (boot_info_t *info) {
c0_set_status(C0_SR_CU1 | C0_SR_CU0 | C0_SR_FR);
OS_INFO->mem_size_6105 = OS_INFO->mem_size;
while (!(io_read(&SP->SR) & SP_SR_HALT));
io_write(&SP->SR, SP_SR_CLR_INTR | SP_SR_SET_HALT);
while (io_read(&SP->DMA_BUSY));
io_write(&PI->SR, PI_SR_CLR_INTR | PI_SR_RESET);
io_write(&VI->V_INTR, 0x3FF);
io_write(&VI->H_LIMITS, 0);
io_write(&VI->CURR_LINE, 0);
io_write(&AI->MADDR, 0);
io_write(&AI->LEN, 0);
io32_t *device_base_address = ROM_CART;
if (info->device_type == BOOT_DEVICE_TYPE_DD) {
device_base_address = ROM_DDIPL;
}
uint32_t pi_config = pi_io_read(device_base_address);
io_write(&PI->DOM[0].LAT, pi_config & 0xFF);
io_write(&PI->DOM[0].PWD, pi_config >> 8);
io_write(&PI->DOM[0].PGS, pi_config >> 16);
io_write(&PI->DOM[0].RLS, pi_config >> 20);
if (io_read(&DPC->SR) & DPC_SR_XBUS_DMEM_DMA) {
while (io_read(&DPC->SR) & DPC_SR_PIPE_BUSY);
}
uint32_t *ipl2_src = &ipl2;
io32_t *ipl2_dst = SP_MEM->IMEM;
for (int i = 0; i < 8; i++) {
io_write(&ipl2_dst[i], ipl2_src[i]);
}
io32_t *ipl3_src = device_base_address;
io32_t *ipl3_dst = SP_MEM->DMEM;
uint32_t tmp;
for (int i = 16; i < 1024; i++) {
tmp = pi_io_read(&ipl3_src[i]);
io_write(&ipl3_dst[i], tmp);
}
uint32_t boot_device = (info->device_type & 0x01);
uint32_t tv_type = (info->tv_type & 0x03);
uint32_t reset_type = (info->reset_type & 0x01);
uint32_t cic_seed = (info->cic_seed & 0xFF);
uint32_t version = (info->version & 0x01);
void (*entry_point)(void) = (void (*)(void)) UNCACHED(&SP_MEM->DMEM[16]);
void *stack_pointer = (void *) UNCACHED(&SP_MEM->IMEM[1020]);
__asm__ volatile (
".set noat \n"
".set noreorder \n"
"lw $t3, %[entry_point] \n"
"lw $s3, %[boot_device] \n"
"lw $s4, %[tv_type] \n"
"lw $s5, %[reset_type] \n"
"lw $s6, %[cic_seed] \n"
"lw $s7, %[version] \n"
"lw $sp, %[stack_pointer] \n"
"jr $t3 \n"
"nop \n"
:
: [entry_point] "R" (entry_point),
[boot_device] "R" (boot_device),
[tv_type] "R" (tv_type),
[reset_type] "R" (reset_type),
[cic_seed] "R" (cic_seed),
[version] "R" (version),
[stack_pointer] "R" (stack_pointer)
: "t3", "s3", "s4", "s5", "s6", "s7"
);
while (1);
}

57
sw/n64/src/boot.h Normal file
View File

@ -0,0 +1,57 @@
#ifndef BOOT_H__
#define BOOT_H__
#include <stdbool.h>
#include <stdint.h>
typedef enum {
BOOT_DEVICE_TYPE_ROM = 0,
BOOT_DEVICE_TYPE_DD = 1,
} boot_device_type_t;
typedef enum {
BOOT_RESET_TYPE_COLD = 0,
BOOT_RESET_TYPE_NMI = 1,
} boot_reset_type_t;
typedef enum {
BOOT_TV_TYPE_PAL = 0,
BOOT_TV_TYPE_NTSC = 1,
BOOT_TV_TYPE_MPAL = 2,
} boot_tv_type_t;
typedef struct {
boot_device_type_t device_type;
boot_reset_type_t reset_type;
boot_tv_type_t tv_type;
uint8_t cic_seed;
uint8_t version;
} boot_info_t;
typedef struct {
uint32_t tv_type;
uint32_t device_type;
uint32_t device_base;
uint32_t reset_type;
uint32_t cic_id;
uint32_t version;
uint32_t mem_size;
uint8_t app_nmi_buffer[64];
uint32_t __reserved_1[37];
uint32_t mem_size_6105;
} os_info_t;
#define OS_INFO_BASE (0x80000300UL)
#define OS_INFO ((os_info_t *) OS_INFO_BASE)
bool boot_get_tv_type (boot_info_t *info);
bool boot_get_cic_seed_version (boot_info_t *info);
void boot (boot_info_t *info);
#endif

View File

@ -37,14 +37,14 @@ static const uint32_t crc32_table[256] = {
}; };
uint32_t crc32_calculate(void *buffer, size_t length) { uint32_t crc32_calculate (void *buffer, size_t length) {
uint32_t crc32 = 0xFFFFFFFF; uint32_t crc32 = 0xFFFFFFFFUL;
uint8_t *byte_pointer = (uint8_t *) buffer; uint8_t *byte_pointer = (uint8_t *) (buffer);
while (length--) { while (length--) {
crc32 = (crc32 >> 8) ^ crc32_table[(crc32 & 0xFF) ^ (*byte_pointer++)]; crc32 = (crc32 >> 8) ^ crc32_table[(crc32 & 0xFF) ^ (*byte_pointer++)];
} }
return ~crc32; return ~(crc32);
} }

View File

@ -2,10 +2,11 @@
#define CRC32_H__ #define CRC32_H__
#include "sys.h" #include <stddef.h>
#include <stdint.h>
uint32_t crc32_calculate(void *buffer, size_t length); uint32_t crc32_calculate (void *buffer, size_t length);
#endif #endif

View File

@ -0,0 +1,359 @@
----------------------------------------------------------------------------
Revision history of FatFs module
----------------------------------------------------------------------------
R0.00 (February 26, 2006)
Prototype.
R0.01 (April 29, 2006)
The first release.
R0.02 (June 01, 2006)
Added FAT12 support.
Removed unbuffered mode.
Fixed a problem on small (<32M) partition.
R0.02a (June 10, 2006)
Added a configuration option (_FS_MINIMUM).
R0.03 (September 22, 2006)
Added f_rename().
Changed option _FS_MINIMUM to _FS_MINIMIZE.
R0.03a (December 11, 2006)
Improved cluster scan algorithm to write files fast.
Fixed f_mkdir() creates incorrect directory on FAT32.
R0.04 (February 04, 2007)
Added f_mkfs().
Supported multiple drive system.
Changed some interfaces for multiple drive system.
Changed f_mountdrv() to f_mount().
R0.04a (April 01, 2007)
Supported multiple partitions on a physical drive.
Added a capability of extending file size to f_lseek().
Added minimization level 3.
Fixed an endian sensitive code in f_mkfs().
R0.04b (May 05, 2007)
Added a configuration option _USE_NTFLAG.
Added FSINFO support.
Fixed DBCS name can result FR_INVALID_NAME.
Fixed short seek (<= csize) collapses the file object.
R0.05 (August 25, 2007)
Changed arguments of f_read(), f_write() and f_mkfs().
Fixed f_mkfs() on FAT32 creates incorrect FSINFO.
Fixed f_mkdir() on FAT32 creates incorrect directory.
R0.05a (February 03, 2008)
Added f_truncate() and f_utime().
Fixed off by one error at FAT sub-type determination.
Fixed btr in f_read() can be mistruncated.
Fixed cached sector is not flushed when create and close without write.
R0.06 (April 01, 2008)
Added fputc(), fputs(), fprintf() and fgets().
Improved performance of f_lseek() on moving to the same or following cluster.
R0.07 (April 01, 2009)
Merged Tiny-FatFs as a configuration option. (_FS_TINY)
Added long file name feature. (_USE_LFN)
Added multiple code page feature. (_CODE_PAGE)
Added re-entrancy for multitask operation. (_FS_REENTRANT)
Added auto cluster size selection to f_mkfs().
Added rewind option to f_readdir().
Changed result code of critical errors.
Renamed string functions to avoid name collision.
R0.07a (April 14, 2009)
Septemberarated out OS dependent code on reentrant cfg.
Added multiple sector size feature.
R0.07c (June 21, 2009)
Fixed f_unlink() can return FR_OK on error.
Fixed wrong cache control in f_lseek().
Added relative path feature.
Added f_chdir() and f_chdrive().
Added proper case conversion to extended character.
R0.07e (November 03, 2009)
Septemberarated out configuration options from ff.h to ffconf.h.
Fixed f_unlink() fails to remove a sub-directory on _FS_RPATH.
Fixed name matching error on the 13 character boundary.
Added a configuration option, _LFN_UNICODE.
Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
R0.08 (May 15, 2010)
Added a memory configuration option. (_USE_LFN = 3)
Added file lock feature. (_FS_SHARE)
Added fast seek feature. (_USE_FASTSEEK)
Changed some types on the API, XCHAR->TCHAR.
Changed .fname in the FILINFO structure on Unicode cfg.
String functions support UTF-8 encoding files on Unicode cfg.
R0.08a (August 16, 2010)
Added f_getcwd(). (_FS_RPATH = 2)
Added sector erase feature. (_USE_ERASE)
Moved file lock semaphore table from fs object to the bss.
Fixed f_mkfs() creates wrong FAT32 volume.
R0.08b (January 15, 2011)
Fast seek feature is also applied to f_read() and f_write().
f_lseek() reports required table size on creating CLMP.
Extended format syntax of f_printf().
Ignores duplicated directory separators in given path name.
R0.09 (September 06, 2011)
f_mkfs() supports multiple partition to complete the multiple partition feature.
Added f_fdisk().
R0.09a (August 27, 2012)
Changed f_open() and f_opendir() reject null object pointer to avoid crash.
Changed option name _FS_SHARE to _FS_LOCK.
Fixed assertion failure due to OS/2 EA on FAT12/16 volume.
R0.09b (January 24, 2013)
Added f_setlabel() and f_getlabel().
R0.10 (October 02, 2013)
Added selection of character encoding on the file. (_STRF_ENCODE)
Added f_closedir().
Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO)
Added forced mount feature with changes of f_mount().
Improved behavior of volume auto detection.
Improved write throughput of f_puts() and f_printf().
Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write().
Fixed f_write() can be truncated when the file size is close to 4GB.
Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect value on error.
R0.10a (January 15, 2014)
Added arbitrary strings as drive number in the path name. (_STR_VOLUME_ID)
Added a configuration option of minimum sector size. (_MIN_SS)
2nd argument of f_rename() can have a drive number and it will be ignored.
Fixed f_mount() with forced mount fails when drive number is >= 1. (appeared at R0.10)
Fixed f_close() invalidates the file object without volume lock.
Fixed f_closedir() returns but the volume lock is left acquired. (appeared at R0.10)
Fixed creation of an entry with LFN fails on too many SFN collisions. (appeared at R0.07)
R0.10b (May 19, 2014)
Fixed a hard error in the disk I/O layer can collapse the directory entry.
Fixed LFN entry is not deleted when delete/rename an object with lossy converted SFN. (appeared at R0.07)
R0.10c (November 09, 2014)
Added a configuration option for the platforms without RTC. (_FS_NORTC)
Changed option name _USE_ERASE to _USE_TRIM.
Fixed volume label created by Mac OS X cannot be retrieved with f_getlabel(). (appeared at R0.09b)
Fixed a potential problem of FAT access that can appear on disk error.
Fixed null pointer dereference on attempting to delete the root direcotry. (appeared at R0.08)
R0.11 (February 09, 2015)
Added f_findfirst(), f_findnext() and f_findclose(). (_USE_FIND)
Fixed f_unlink() does not remove cluster chain of the file. (appeared at R0.10c)
Fixed _FS_NORTC option does not work properly. (appeared at R0.10c)
R0.11a (September 05, 2015)
Fixed wrong media change can lead a deadlock at thread-safe configuration.
Added code page 771, 860, 861, 863, 864, 865 and 869. (_CODE_PAGE)
Removed some code pages actually not exist on the standard systems. (_CODE_PAGE)
Fixed errors in the case conversion teble of code page 437 and 850 (ff.c).
Fixed errors in the case conversion teble of Unicode (cc*.c).
R0.12 (April 12, 2016)
Added support for exFAT file system. (_FS_EXFAT)
Added f_expand(). (_USE_EXPAND)
Changed some members in FINFO structure and behavior of f_readdir().
Added an option _USE_CHMOD.
Removed an option _WORD_ACCESS.
Fixed errors in the case conversion table of Unicode (cc*.c).
R0.12a (July 10, 2016)
Added support for creating exFAT volume with some changes of f_mkfs().
Added a file open method FA_OPEN_APPEND. An f_lseek() following f_open() is no longer needed.
f_forward() is available regardless of _FS_TINY.
Fixed f_mkfs() creates wrong volume. (appeared at R0.12)
Fixed wrong memory read in create_name(). (appeared at R0.12)
Fixed compilation fails at some configurations, _USE_FASTSEEK and _USE_FORWARD.
R0.12b (September 04, 2016)
Made f_rename() be able to rename objects with the same name but case.
Fixed an error in the case conversion teble of code page 866. (ff.c)
Fixed writing data is truncated at the file offset 4GiB on the exFAT volume. (appeared at R0.12)
Fixed creating a file in the root directory of exFAT volume can fail. (appeared at R0.12)
Fixed f_mkfs() creating exFAT volume with too small cluster size can collapse unallocated memory. (appeared at R0.12)
Fixed wrong object name can be returned when read directory at Unicode cfg. (appeared at R0.12)
Fixed large file allocation/removing on the exFAT volume collapses allocation bitmap. (appeared at R0.12)
Fixed some internal errors in f_expand() and f_lseek(). (appeared at R0.12)
R0.12c (March 04, 2017)
Improved write throughput at the fragmented file on the exFAT volume.
Made memory usage for exFAT be able to be reduced as decreasing _MAX_LFN.
Fixed successive f_getfree() can return wrong count on the FAT12/16 volume. (appeared at R0.12)
Fixed configuration option _VOLUMES cannot be set 10. (appeared at R0.10c)
R0.13 (May 21, 2017)
Changed heading character of configuration keywords "_" to "FF_".
Removed ASCII-only configuration, FF_CODE_PAGE = 1. Use FF_CODE_PAGE = 437 instead.
Added f_setcp(), run-time code page configuration. (FF_CODE_PAGE = 0)
Improved cluster allocation time on stretch a deep buried cluster chain.
Improved processing time of f_mkdir() with large cluster size by using FF_USE_LFN = 3.
Improved NoFatChain flag of the fragmented file to be set after it is truncated and got contiguous.
Fixed archive attribute is left not set when a file on the exFAT volume is renamed. (appeared at R0.12)
Fixed exFAT FAT entry can be collapsed when write or lseek operation to the existing file is done. (appeared at R0.12c)
Fixed creating a file can fail when a new cluster allocation to the exFAT directory occures. (appeared at R0.12c)
R0.13a (October 14, 2017)
Added support for UTF-8 encoding on the API. (FF_LFN_UNICODE = 2)
Added options for file name output buffer. (FF_LFN_BUF, FF_SFN_BUF).
Added dynamic memory allocation option for working buffer of f_mkfs() and f_fdisk().
Fixed f_fdisk() and f_mkfs() create the partition table with wrong CHS parameters. (appeared at R0.09)
Fixed f_unlink() can cause lost clusters at fragmented file on the exFAT volume. (appeared at R0.12c)
Fixed f_setlabel() rejects some valid characters for exFAT volume. (appeared at R0.12)
R0.13b (April 07, 2018)
Added support for UTF-32 encoding on the API. (FF_LFN_UNICODE = 3)
Added support for Unix style volume ID. (FF_STR_VOLUME_ID = 2)
Fixed accesing any object on the exFAT root directory beyond the cluster boundary can fail. (appeared at R0.12c)
Fixed f_setlabel() does not reject some invalid characters. (appeared at R0.09b)
R0.13c (October 14, 2018)
Supported stdint.h for C99 and later. (integer.h was included in ff.h)
Fixed reading a directory gets infinite loop when the last directory entry is not empty. (appeared at R0.12)
Fixed creating a sub-directory in the fragmented sub-directory on the exFAT volume collapses FAT chain of the parent directory. (appeared at R0.12)
Fixed f_getcwd() cause output buffer overrun when the buffer has a valid drive number. (appeared at R0.13b)
R0.14 (October 14, 2019)
Added support for 64-bit LBA and GUID partition table (FF_LBA64 = 1)
Changed some API functions, f_mkfs() and f_fdisk().
Fixed f_open() function cannot find the file with file name in length of FF_MAX_LFN characters.
Fixed f_readdir() function cannot retrieve long file names in length of FF_MAX_LFN - 1 characters.
Fixed f_readdir() function returns file names with wrong case conversion. (appeared at R0.12)
Fixed f_mkfs() function can fail to create exFAT volume in the second partition. (appeared at R0.12)
R0.14a (December 5, 2020)
Limited number of recursive calls in f_findnext().
Fixed old floppy disks formatted with MS-DOS 2.x and 3.x cannot be mounted.
Fixed some compiler warnings.
R0.14b (April 17, 2021)
Made FatFs uses standard library <string.h> for copy, compare and search instead of built-in string functions.
Added support for long long integer and floating point to f_printf(). (FF_STRF_LLI and FF_STRF_FP)
Made path name parser ignore the terminating separator to allow "dir/".
Improved the compatibility in Unix style path name feature.
Fixed the file gets dead-locked when f_open() failed with some conditions. (appeared at R0.12a)
Fixed f_mkfs() can create wrong exFAT volume due to a timing dependent error. (appeared at R0.12)
Fixed code page 855 cannot be set by f_setcp().
Fixed some compiler warnings.

View File

@ -0,0 +1,21 @@
FatFs Module Source Files R0.14b
FILES
00readme.txt This file.
00history.txt Revision history.
ff.c FatFs module.
ffconf.h Configuration file of FatFs module.
ff.h Common include file for FatFs and application module.
diskio.h Common include file for FatFs and disk I/O module.
diskio.c An example of glue function to attach existing disk I/O module to FatFs.
ffunicode.c Optional Unicode utility functions.
ffsystem.c An example of optional O/S related functions.
Low level disk I/O module is not included in this archive because the FatFs
module is only a generic file system layer and it does not depend on any specific
storage device. You need to provide a low level disk I/O module written to
control the storage device that attached to the target system.

37
sw/n64/src/fatfs/diskio.c Normal file
View File

@ -0,0 +1,37 @@
#include "ff.h"
#include "diskio.h"
#include "../sc64.h"
DSTATUS disk_status (BYTE pdrv) {
return 0;
}
DSTATUS disk_initialize (BYTE pdrv) {
return 0;
}
DRESULT disk_read (BYTE pdrv, BYTE *buff, LBA_t sector, UINT count) {
if (pdrv == 0) {
return RES_NOTRDY;
} else if (pdrv == 1) {
sc64_debug_fsd_read(buff, sector, count);
return RES_OK;
}
return RES_PARERR;
}
#if FF_FS_READONLY == 0
DRESULT disk_write (BYTE pdrv, const BYTE *buff, LBA_t sector, UINT count) {
if (pdrv == 0) {
return RES_NOTRDY;
} else if (pdrv == 1) {
sc64_debug_fsd_write(buff, sector, count);
return RES_OK;
}
return RES_PARERR;
}
#endif
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void *buff) {
return RES_PARERR;
}

77
sw/n64/src/fatfs/diskio.h Normal file
View File

@ -0,0 +1,77 @@
/*-----------------------------------------------------------------------/
/ Low level disk interface modlue include file (C)ChaN, 2019 /
/-----------------------------------------------------------------------*/
#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE pdrv);
DSTATUS disk_status (BYTE pdrv);
DRESULT disk_read (BYTE pdrv, BYTE* buff, LBA_t sector, UINT count);
DRESULT disk_write (BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count);
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Command code for disk_ioctrl fucntion */
/* Generic command (Used by FatFs) */
#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */
#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */
#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */
#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */
#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */
/* Generic command (Not used by FatFs) */
#define CTRL_POWER 5 /* Get/Set power status */
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
#define CTRL_EJECT 7 /* Eject media */
#define CTRL_FORMAT 8 /* Create physical format on the media */
/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE 10 /* Get card type */
#define MMC_GET_CSD 11 /* Get CSD */
#define MMC_GET_CID 12 /* Get CID */
#define MMC_GET_OCR 13 /* Get OCR */
#define MMC_GET_SDSTAT 14 /* Get SD status */
#define ISDIO_READ 55 /* Read data form SD iSDIO register */
#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */
#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */
/* ATA/CF specific ioctl command */
#define ATA_GET_REV 20 /* Get F/W revision */
#define ATA_GET_MODEL 21 /* Get model name */
#define ATA_GET_SN 22 /* Get serial number */
#ifdef __cplusplus
}
#endif
#endif

6982
sw/n64/src/fatfs/ff.c Normal file

File diff suppressed because it is too large Load Diff

422
sw/n64/src/fatfs/ff.h Normal file
View File

@ -0,0 +1,422 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem module R0.14b /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 2021, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
/ that the following condition is met:
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/
/----------------------------------------------------------------------------*/
#ifndef FF_DEFINED
#define FF_DEFINED 86631 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "ffconf.h" /* FatFs configuration options */
#if FF_DEFINED != FFCONF_DEF
#error Wrong configuration file (ffconf.h).
#endif
/* Integer types used for FatFs API */
#if defined(_WIN32) /* Windows VC++ (for development only) */
#define FF_INTDEF 2
#include <windows.h>
typedef unsigned __int64 QWORD;
#include <float.h>
#define isnan(v) _isnan(v)
#define isinf(v) (!_finite(v))
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */
#define FF_INTDEF 2
#include <stdint.h>
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef uint16_t WORD; /* 16-bit unsigned integer */
typedef uint32_t DWORD; /* 32-bit unsigned integer */
typedef uint64_t QWORD; /* 64-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#else /* Earlier than C99 */
#define FF_INTDEF 1
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef unsigned short WORD; /* 16-bit unsigned integer */
typedef unsigned long DWORD; /* 32-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#endif
/* Type of file size and LBA variables */
#if FF_FS_EXFAT
#if FF_INTDEF != 2
#error exFAT feature wants C99 or later
#endif
typedef QWORD FSIZE_t;
#if FF_LBA64
typedef QWORD LBA_t;
#else
typedef DWORD LBA_t;
#endif
#else
#if FF_LBA64
#error exFAT needs to be enabled when enable 64-bit LBA
#endif
typedef DWORD FSIZE_t;
typedef DWORD LBA_t;
#endif
/* Type of path name strings on FatFs API (TCHAR) */
#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */
typedef char TCHAR;
#define _T(x) u8 ## x
#define _TEXT(x) u8 ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */
typedef DWORD TCHAR;
#define _T(x) U ## x
#define _TEXT(x) U ## x
#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3)
#error Wrong FF_LFN_UNICODE setting
#else /* ANSI/OEM code in SBCS/DBCS */
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
/* Definitions of volume management */
#if FF_MULTI_PARTITION /* Multiple partition configuration */
typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
} PARTITION;
extern PARTITION VolToPart[]; /* Volume - Partition mapping table */
#endif
#if FF_STR_VOLUME_ID
#ifndef FF_VOLUME_STRS
extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */
#endif
#endif
/* Filesystem object structure (FATFS) */
typedef struct {
BYTE fs_type; /* Filesystem type (0:not mounted) */
BYTE pdrv; /* Associated physical drive */
BYTE n_fats; /* Number of FATs (1 or 2) */
BYTE wflag; /* win[] flag (b0:dirty) */
BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */
WORD id; /* Volume mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
WORD csize; /* Cluster size [sectors] */
#if FF_MAX_SS != FF_MIN_SS
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
#endif
#if FF_USE_LFN
WCHAR* lfnbuf; /* LFN working buffer */
#endif
#if FF_FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
#endif
#if FF_FS_REENTRANT
FF_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !FF_FS_READONLY
DWORD last_clst; /* Last allocated cluster */
DWORD free_clst; /* Number of free clusters */
#endif
#if FF_FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#if FF_FS_EXFAT
DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */
DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */
DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */
#endif
#endif
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
DWORD fsize; /* Size of an FAT [sectors] */
LBA_t volbase; /* Volume base sector */
LBA_t fatbase; /* FAT base sector */
LBA_t dirbase; /* Root directory base sector/cluster */
LBA_t database; /* Data base sector */
#if FF_FS_EXFAT
LBA_t bitbase; /* Allocation bitmap base sector */
#endif
LBA_t winsect; /* Current sector appearing in the win[] */
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
} FATFS;
/* Object ID and allocation information (FFOBJID) */
typedef struct {
FATFS* fs; /* Pointer to the hosting volume of this object */
WORD id; /* Hosting volume mount ID */
BYTE attr; /* Object attribute */
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */
DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
#if FF_FS_EXFAT
DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */
DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */
DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */
DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */
DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */
#endif
#if FF_FS_LOCK
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#endif
} FFOBJID;
/* File object structure (FIL) */
typedef struct {
FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
BYTE flag; /* File status flags */
BYTE err; /* Abort flag (error code) */
FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */
DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */
LBA_t sect; /* Sector number appearing in buf[] (0:invalid) */
#if !FF_FS_READONLY
LBA_t dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */
#endif
#if FF_USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
#endif
#if !FF_FS_TINY
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FFOBJID obj; /* Object identifier */
DWORD dptr; /* Current read/write offset */
DWORD clust; /* Current cluster */
LBA_t sect; /* Current sector (0:Read operation has terminated) */
BYTE* dir; /* Pointer to the directory item in the win[] */
BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */
#if FF_USE_LFN
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
#endif
#if FF_USE_FIND
const TCHAR* pat; /* Pointer to the name matching pattern */
#endif
} DIR;
/* File information structure (FILINFO) */
typedef struct {
FSIZE_t fsize; /* File size */
WORD fdate; /* Modified date */
WORD ftime; /* Modified time */
BYTE fattrib; /* File attribute */
#if FF_USE_LFN
TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */
TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */
#else
TCHAR fname[12 + 1]; /* File name */
#endif
} FILINFO;
/* Format parameter structure (MKFS_PARM) */
typedef struct {
BYTE fmt; /* Format option (FM_FAT, FM_FAT32, FM_EXFAT and FM_SFD) */
BYTE n_fat; /* Number of FATs */
UINT align; /* Data area alignment (sector) */
UINT n_root; /* Number of root directory entries */
DWORD au_size; /* Cluster size (byte) */
} MKFS_PARM;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Access denied due to prohibited access or directory full */
FR_EXIST, /* (8) Access denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs module application interface */
FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */
FRESULT f_close (FIL* fp); /* Close an open file object */
FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */
FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */
FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */
FRESULT f_truncate (FIL* fp); /* Truncate the file */
FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */
FRESULT f_opendir (DIR* dp, const TCHAR* path); /* Open a directory */
FRESULT f_closedir (DIR* dp); /* Close an open directory */
FRESULT f_readdir (DIR* dp, FILINFO* fno); /* Read a directory item */
FRESULT f_findfirst (DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */
FRESULT f_findnext (DIR* dp, FILINFO* fno); /* Find next file */
FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */
FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */
FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */
FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */
FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */
FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */
FRESULT f_chdir (const TCHAR* path); /* Change current directory */
FRESULT f_chdrive (const TCHAR* path); /* Change current drive */
FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */
FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */
FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */
FRESULT f_setlabel (const TCHAR* label); /* Set volume label */
FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */
FRESULT f_expand (FIL* fp, FSIZE_t fsz, BYTE opt); /* Allocate a contiguous block to the file */
FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */
FRESULT f_mkfs (const TCHAR* path, const MKFS_PARM* opt, void* work, UINT len); /* Create a FAT volume */
FRESULT f_fdisk (BYTE pdrv, const LBA_t ptbl[], void* work); /* Divide a physical drive into some partitions */
FRESULT f_setcp (WORD cp); /* Set current code page */
int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */
int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */
int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */
#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize))
#define f_error(fp) ((fp)->err)
#define f_tell(fp) ((fp)->fptr)
#define f_size(fp) ((fp)->obj.objsize)
#define f_rewind(fp) f_lseek((fp), 0)
#define f_rewinddir(dp) f_readdir((dp), 0)
#define f_rmdir(path) f_unlink(path)
#define f_unmount(path) f_mount(0, path, 0)
/*--------------------------------------------------------------*/
/* Additional user defined functions */
/* RTC function */
#if !FF_FS_READONLY && !FF_FS_NORTC
DWORD get_fattime (void);
#endif
/* LFN support functions */
#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */
WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */
WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */
DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */
#endif
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
void* ff_memalloc (UINT msize); /* Allocate memory block */
void ff_memfree (void* mblock); /* Free memory block */
#endif
/* Sync functions */
#if FF_FS_REENTRANT
int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */
int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */
void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */
int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and offset address */
/* File access mode and open method flags (3rd argument of f_open) */
#define FA_READ 0x01
#define FA_WRITE 0x02
#define FA_OPEN_EXISTING 0x00
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA_OPEN_APPEND 0x30
/* Fast seek controls (2nd argument of f_lseek) */
#define CREATE_LINKMAP ((FSIZE_t)0 - 1)
/* Format options (2nd argument of f_mkfs) */
#define FM_FAT 0x01
#define FM_FAT32 0x02
#define FM_EXFAT 0x04
#define FM_ANY 0x07
#define FM_SFD 0x08
/* Filesystem type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
#define FS_EXFAT 4
/* File attribute bits for directory entry (FILINFO.fattrib) */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#ifdef __cplusplus
}
#endif
#endif /* FF_DEFINED */

301
sw/n64/src/fatfs/ffconf.h Normal file
View File

@ -0,0 +1,301 @@
/*---------------------------------------------------------------------------/
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 86631 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_READONLY 1
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/ and optional writing functions as well. */
#define FF_FS_MINIMIZE 1
/* This option defines minimization level to remove some basic API functions.
/
/ 0: Basic functions are fully enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/ are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define FF_USE_FIND 0
/* This option switches filtered directory read functions, f_findfirst() and
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
#define FF_USE_MKFS 0
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
#define FF_USE_FASTSEEK 1
/* This option switches fast seek function. (0:Disable or 1:Enable) */
#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */
#define FF_USE_CHMOD 0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define FF_USE_LABEL 0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
#define FF_USE_STRFUNC 0
#define FF_PRINT_LLI 0
#define FF_PRINT_FLOAT 0
#define FF_STRF_ENCODE 0
/* FF_USE_STRFUNC switches string functions, f_gets(), f_putc(), f_puts() and
/ f_printf().
/
/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion.
/
/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
makes f_printf() support floating point argument. These features want C99 or later.
/ When FF_LFN_UNICODE >= 1 with LFN enabled, string functions convert the character
/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
/ to be read/written via those functions.
/
/ 0: ANSI/OEM in current CP
/ 1: Unicode in UTF-16LE
/ 2: Unicode in UTF-16BE
/ 3: Unicode in UTF-8
*/
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#define FF_CODE_PAGE 437
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect code page setting can cause a file open failure.
/
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
/ 771 - KBL
/ 775 - Baltic
/ 850 - Latin 1
/ 852 - Latin 2
/ 855 - Cyrillic
/ 857 - Turkish
/ 860 - Portuguese
/ 861 - Icelandic
/ 862 - Hebrew
/ 863 - Canadian French
/ 864 - Arabic
/ 865 - Nordic
/ 866 - Russian
/ 869 - Greek 2
/ 932 - Japanese (DBCS)
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#define FF_USE_LFN 2
#define FF_MAX_LFN 255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable LFN. FF_MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/ be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
/ specification.
/ When use stack for the working buffer, take care on stack overflow. When use heap
/ memory for the working buffer, memory management functions, ff_memalloc() and
/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
#define FF_LFN_UNICODE 0
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_BUF 255
#define FF_SFN_BUF 12
/* This set of options defines size of file name members in the FILINFO structure
/ which is used to read out directory items. These values should be suffcient for
/ the file names to read. The maximum possible length of the read file name depends
/ on character encoding. When LFN is not enabled, these options have no effect. */
#define FF_FS_RPATH 0
/* This option configures support for relative path.
/
/ 0: Disable relative path and remove related functions.
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() function is available in addition to 1.
*/
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#define FF_VOLUMES 2
/* Number of volumes (logical drives) to be used. (1-10) */
#define FF_STR_VOLUME_ID 0
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/ logical drives. Number of items must not be less than FF_VOLUMES. Valid
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/ not defined, a user defined volume string table needs to be defined as:
/
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/
#define FF_MULTI_PARTITION 0
/* This option switches support for multiple volumes on the physical drive.
/ By default (0), each logical drive number is bound to the same physical drive
/ number and only an FAT volume found on the physical drive will be mounted.
/ When this function is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ funciton will be available. */
#define FF_MIN_SS 512
#define FF_MAX_SS 512
/* This set of options configures the range of sector size to be supported. (512,
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/ harddisk, but a larger value may be required for on-board flash memory and some
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
/ for variable sector size mode and disk_ioctl() function needs to implement
/ GET_SECTOR_SIZE command. */
#define FF_LBA64 0
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
#define FF_MIN_GPT 0x10000000
/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs and
/ f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */
#define FF_USE_TRIM 0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
/ disk_ioctl() function. */
/*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_TINY 0
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
/ Instead of private sector buffer eliminated from the file object, common sector
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#define FF_FS_EXFAT 1
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 1
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2020
/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have
/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable
/ the timestamp function. Every object modified by FatFs will have a fixed timestamp
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
/ added to the project to read current time form real-time clock. FF_NORTC_MON,
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
#define FF_FS_LOCK 0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/ is 1.
/
/ 0: Disable file lock function. To avoid volume corruption, application program
/ should avoid illegal open, remove and rename to the open objects.
/ >0: Enable file lock function. The value defines how many files/sub-directories
/ can be opened simultaneously under file lock control. Note that the file
/ lock control is independent of re-entrancy. */
/* #include <somertos.h> // O/S definitions */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
#define FF_SYNC_t HANDLE
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/ module itself. Note that regardless of this option, file access to different
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/ and f_fdisk() function, are always not re-entrant. Only file/directory access
/ to the same volume is under control of this function.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
/ function, must be added to the project. Samples are available in
/ option/syscall.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of time tick.
/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be
/ included somewhere in the scope of ff.h. */
/*--- End of configuration options ---*/

170
sw/n64/src/fatfs/ffsystem.c Normal file
View File

@ -0,0 +1,170 @@
/*------------------------------------------------------------------------*/
/* Sample Code of OS Dependent Functions for FatFs */
/* (C)ChaN, 2018 */
/*------------------------------------------------------------------------*/
#include "ff.h"
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
/*------------------------------------------------------------------------*/
/* Allocate a memory block */
/*------------------------------------------------------------------------*/
void* ff_memalloc ( /* Returns pointer to the allocated memory block (null if not enough core) */
UINT msize /* Number of bytes to allocate */
)
{
return malloc(msize); /* Allocate a new memory block with POSIX API */
}
/*------------------------------------------------------------------------*/
/* Free a memory block */
/*------------------------------------------------------------------------*/
void ff_memfree (
void* mblock /* Pointer to the memory block to free (nothing to do if null) */
)
{
free(mblock); /* Free the memory block with POSIX API */
}
#endif
#if FF_FS_REENTRANT /* Mutal exclusion */
/*------------------------------------------------------------------------*/
/* Create a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to create a new
/ synchronization object for the volume, such as semaphore and mutex.
/ When a 0 is returned, the f_mount() function fails with FR_INT_ERR.
*/
//const osMutexDef_t Mutex[FF_VOLUMES]; /* Table of CMSIS-RTOS mutex */
int ff_cre_syncobj ( /* 1:Function succeeded, 0:Could not create the sync object */
BYTE vol, /* Corresponding volume (logical drive number) */
FF_SYNC_t* sobj /* Pointer to return the created sync object */
)
{
/* Win32 */
*sobj = CreateMutex(NULL, FALSE, NULL);
return (int)(*sobj != INVALID_HANDLE_VALUE);
/* uITRON */
// T_CSEM csem = {TA_TPRI,1,1};
// *sobj = acre_sem(&csem);
// return (int)(*sobj > 0);
/* uC/OS-II */
// OS_ERR err;
// *sobj = OSMutexCreate(0, &err);
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// *sobj = xSemaphoreCreateMutex();
// return (int)(*sobj != NULL);
/* CMSIS-RTOS */
// *sobj = osMutexCreate(&Mutex[vol]);
// return (int)(*sobj != NULL);
}
/*------------------------------------------------------------------------*/
/* Delete a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to delete a synchronization
/ object that created with ff_cre_syncobj() function. When a 0 is returned,
/ the f_mount() function fails with FR_INT_ERR.
*/
int ff_del_syncobj ( /* 1:Function succeeded, 0:Could not delete due to an error */
FF_SYNC_t sobj /* Sync object tied to the logical drive to be deleted */
)
{
/* Win32 */
return (int)CloseHandle(sobj);
/* uITRON */
// return (int)(del_sem(sobj) == E_OK);
/* uC/OS-II */
// OS_ERR err;
// OSMutexDel(sobj, OS_DEL_ALWAYS, &err);
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// vSemaphoreDelete(sobj);
// return 1;
/* CMSIS-RTOS */
// return (int)(osMutexDelete(sobj) == osOK);
}
/*------------------------------------------------------------------------*/
/* Request Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on entering file functions to lock the volume.
/ When a 0 is returned, the file function fails with FR_TIMEOUT.
*/
int ff_req_grant ( /* 1:Got a grant to access the volume, 0:Could not get a grant */
FF_SYNC_t sobj /* Sync object to wait */
)
{
/* Win32 */
return (int)(WaitForSingleObject(sobj, FF_FS_TIMEOUT) == WAIT_OBJECT_0);
/* uITRON */
// return (int)(wai_sem(sobj) == E_OK);
/* uC/OS-II */
// OS_ERR err;
// OSMutexPend(sobj, FF_FS_TIMEOUT, &err));
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// return (int)(xSemaphoreTake(sobj, FF_FS_TIMEOUT) == pdTRUE);
/* CMSIS-RTOS */
// return (int)(osMutexWait(sobj, FF_FS_TIMEOUT) == osOK);
}
/*------------------------------------------------------------------------*/
/* Release Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on leaving file functions to unlock the volume.
*/
void ff_rel_grant (
FF_SYNC_t sobj /* Sync object to be signaled */
)
{
/* Win32 */
ReleaseMutex(sobj);
/* uITRON */
// sig_sem(sobj);
/* uC/OS-II */
// OSMutexPost(sobj);
/* FreeRTOS */
// xSemaphoreGive(sobj);
/* CMSIS-RTOS */
// osMutexRelease(sobj);
}
#endif

15593
sw/n64/src/fatfs/ffunicode.c Normal file

File diff suppressed because it is too large Load Diff

12
sw/n64/src/init.c Normal file
View File

@ -0,0 +1,12 @@
#include "sys.h"
#include "sc64.h"
void init (void) {
uint32_t pifram = si_io_read((io32_t *) (&PIFRAM[0x3C]));
si_io_write((io32_t *) (&PIFRAM[0x3C]), pifram | 0x08);
sc64_init();
LOG_I("Initialized\r\n");
}

View File

@ -1,41 +1,68 @@
#include "boot.h"
#include "sc64.h" #include "sc64.h"
void main(void) { void main (void) {
sc64_init(); boot_info_t boot_info;
sc64_info_t sc64_info;
rom_header_t header; sc64_get_info(&sc64_info);
io32_t *src = (io32_t *) (ROM_HEADER_CART); LOG_I("Bootloader version: %.32s\r\n", sc64_info.bootloader_version);
uint32_t *dst = (uint32_t *) (&header);
for (int i = 0; i < sizeof(rom_header_t); i += 4) { switch (sc64_info.boot_mode) {
*dst++ = pi_io_read(src++); case BOOT_MODE_MENU:
LOG_E("Menu boot mode not implemented!\r\n");
while (1);
case BOOT_MODE_ROM:
boot_info.device_type = BOOT_DEVICE_TYPE_ROM;
LOG_I("Running ROM from SDRAM\r\n");
break;
case BOOT_MODE_DD:
boot_info.device_type = BOOT_DEVICE_TYPE_DD;
LOG_I("Running DDIPL from SDRAM\r\n");
break;
case BOOT_MODE_DIRECT:
LOG_I("Running bootloader from SDRAM - assuming FSD available\r\n");
while (1);
default:
LOG_E("Unknown boot mode! - %d\r\n", sc64_info.boot_mode);
while (1);
} }
LOG_I("Booting ROM:\r\n"); boot_info.reset_type = OS_INFO->reset_type;
LOG_I(" PI Config: 0x%08lX\r\n", header.pi_config);
LOG_I(" Clock rate: 0x%08lX\r\n", header.clock_rate);
LOG_I(" Load address: 0x%08lX\r\n", header.load_addr);
LOG_I(" SDK vesrion: %d.%d%c\r\n", header.sdk_version.major / 10, header.sdk_version.major % 10, header.sdk_version.minor);
LOG_I(" 1MB CRC: 0x%08lX, 0x%08lX\r\n", header.crc[0], header.crc[1]);
LOG_I(" Name: %.20s\r\n", header.name);
LOG_I(" ID: %.4s\r\n", header.id);
LOG_I(" Mask ROM version: %d\r\n", header.version);
LOG_I("\r\n");
cart_info_t info; if (sc64_info.tv_type != TV_TYPE_UNKNOWN) {
boot_info.tv_type = sc64_info.tv_type;
LOG_I("Using provided TV type: %d\r\n", boot_info.tv_type);
} else {
if (boot_get_tv_type(&boot_info)) {
LOG_I("Using TV type guessed from ROM header: %d\r\n", boot_info.tv_type);
} else {
boot_info.tv_type = OS_INFO->tv_type;
LOG_I("Using console TV type: %d\r\n", boot_info.tv_type);
}
}
sc64_get_info(&info); if (sc64_info.cic_seed != 0xFFFF) {
boot_info.cic_seed = sc64_info.cic_seed & 0xFF;
boot_info.version = (sc64_info.cic_seed >> 8) & 0x01;
LOG_I("Using provided CIC seed and version: 0x%02X / %d\r\n", boot_info.cic_seed, boot_info.version);
} else {
if (boot_get_cic_seed_version(&boot_info)) {
LOG_I("Using CIC seed and version guessed from IPL3: 0x%02X / %d\r\n", boot_info.cic_seed, boot_info.version);
} else {
boot_info.cic_seed = 0x3F;
boot_info.version = 0;
LOG_I("Using 6102/7101 CIC seed and version: 0x%02X / %d\r\n", boot_info.cic_seed, boot_info.version);
}
}
LOG_I("SC64 settings:\r\n"); LOG_I("Booting IPL3\r\n");
LOG_I(" DD enabled: %d\r\n", info.dd_enabled);
LOG_I(" Save type: %d\r\n", info.save_type); boot(&boot_info);
LOG_I(" CIC seed: 0x%02X\r\n", info.cic_seed);
LOG_I(" TV type: %d\r\n", info.tv_type);
LOG_I(" Save offset: 0x%08lX\r\n", (uint32_t) info.save_offset);
LOG_I(" DD offset: 0x%08lX\r\n", (uint32_t) info.dd_offset);
LOG_I(" Boot mode: %d\r\n", info.boot_mode);
LOG_I(" Bootloader ver: %s\r\n", info.bootloader_version);
LOG_I("\r\n");
} }

View File

@ -1,218 +0,0 @@
#include "boot.h"
#include "crc32.h"
#include "n64_regs.h"
#include "sc64.h"
static const struct crc32_to_cic_seed {
uint32_t ipl3_crc32;
uint16_t cic_seed;
} crc32_to_cic_seed[] = {
{ .ipl3_crc32 = 0x587BD543, .cic_seed = 0x00AC }, // CIC5101
{ .ipl3_crc32 = 0x6170A4A1, .cic_seed = 0x013F }, // CIC6101
{ .ipl3_crc32 = 0x009E9EA3, .cic_seed = 0x013F }, // CIC7102
{ .ipl3_crc32 = 0x90BB6CB5, .cic_seed = 0x003F }, // CICx102
{ .ipl3_crc32 = 0x0B050EE0, .cic_seed = 0x0078 }, // CICx103
{ .ipl3_crc32 = 0x98BC2C86, .cic_seed = 0x0091 }, // CICx105
{ .ipl3_crc32 = 0xACC8580A, .cic_seed = 0x0085 }, // CICx106
{ .ipl3_crc32 = 0x10C68B18, .cic_seed = 0x00DD }, // JP 64DD dev
{ .ipl3_crc32 = 0x0E018159, .cic_seed = 0x00DD }, // JP 64DD retail
{ .ipl3_crc32 = 0x8FEBA21E, .cic_seed = 0x00DE }, // US 64DD retail
};
static cart_header_t global_cart_header __attribute__((aligned(16)));
cart_header_t *boot_load_cart_header(void) {
cart_header_t *cart_header_pointer = &global_cart_header;
uint32_t *src = (uint32_t *)(CART_BASE);
uint32_t *dst = (uint32_t *) cart_header_pointer;
for (int i = 0; i < sizeof(cart_header_t); i += 4) {
*dst++ = pio_read(src++);
// while (PI->status & 0x03);
// ((uint32_t *)cart_header_pointer)[i] = (((uint32_t *)(CART_BASE))[i]);
}
return cart_header_pointer;
}
uint16_t boot_get_cic_seed(cart_header_t *cart_header) {
uint16_t cic_seed = crc32_to_cic_seed[7].cic_seed;
uint32_t ipl3_crc32 = crc32_calculate(cart_header->boot_code, sizeof(cart_header->boot_code));
for (size_t i = 0; i < ARRAY_ITEMS(crc32_to_cic_seed); i++) {
if (crc32_to_cic_seed[i].ipl3_crc32 == ipl3_crc32) {
cic_seed = crc32_to_cic_seed[i].cic_seed;
}
}
return cic_seed;
}
tv_type_t boot_get_tv_type(cart_header_t *cart_header) {
switch (cart_header->country_code) {
case 'D':
case 'F':
case 'H':
case 'I':
case 'P':
case 'S':
case 'W':
case 'X':
case 'Y':
return TV_PAL;
case '7':
case 'A':
case 'C':
case 'E':
case 'J':
case 'K':
case 'N':
case 'U':
return TV_NTSC;
case 'B':
return TV_MPAL;
default:
return -1;
}
}
__attribute__((noreturn)) void bootX(cart_header_t *cart_header, uint16_t cic_seed, tv_type_t tv_type) {
uint32_t is_x105_boot = (cic_seed == crc32_to_cic_seed[5].cic_seed);
uint32_t is_ddipl_boot = (
(cic_seed == crc32_to_cic_seed[7].cic_seed) ||
(cic_seed == crc32_to_cic_seed[8].cic_seed) ||
(cic_seed == crc32_to_cic_seed[9].cic_seed)
);
tv_type_t os_tv_type = tv_type == -1 ? OS_BOOT_CONFIG->tv_type : tv_type;
volatile uint64_t gpr_regs[32];
MI->interrupt_mask = MI_INT_CLEAR_SP | MI_INT_CLEAR_SI | MI_INT_CLEAR_AI | MI_INT_CLEAR_VI | MI_INT_CLEAR_PI | MI_INT_CLEAR_DP;
while (!(SP->status & SP_STATUS_HALT));
SP->status = SP_STATUS_CLEAR_INTERRUPT | SP_STATUS_SET_HALT;
while (SP->dma_busy & SP_DMA_BUSY);
PI->status = PI_STATUS_CLEAR_INTERRUPT | PI_STATUS_RESET_CONTROLLER;
VI->v_intr = 0x3FF;
VI->h_limits = 0;
VI->current_line = 0;
AI->dram_addr = 0;
AI->len = 0;
PI->dom1_lat = cart_header->pi_conf & 0xFF;
PI->dom1_pwd = cart_header->pi_conf >> 8;
PI->dom1_pgs = cart_header->pi_conf >> 16;
PI->dom1_rls = cart_header->pi_conf >> 20;
if (DP_CMD->status & DP_CMD_STATUS_XBUS_DMEM_DMA) {
while (DP_CMD->status & DP_CMD_STATUS_PIPE_BUSY);
}
for (size_t i = 0; i < ARRAY_ITEMS(cart_header->boot_code); i++) {
SP_MEM->dmem[16 + i] = cart_header->boot_code[i];
}
// CIC X105 based games checks if start of IPL2 code exists in SP IMEM
SP_MEM->imem[0] = 0x3C0DBFC0; // lui t5, 0xBFC0
SP_MEM->imem[1] = 0x8DA807FC; // lw t0, 0x07FC(t5)
SP_MEM->imem[2] = 0x25AD07C0; // addiu t5, t5, 0x07C0
SP_MEM->imem[3] = 0x31080080; // andi t0, t0, 0x0080
SP_MEM->imem[4] = 0x5500FFFC; // bnel t0, zero, &SP_MEM->imem[1]
SP_MEM->imem[5] = 0x3C0DBFC0; // lui t5, 0xBFC0
SP_MEM->imem[6] = 0x8DA80024; // lw t0, 0x0024(t5)
SP_MEM->imem[7] = 0x3C0BB000; // lui t3, 0xB000
if (is_x105_boot) {
OS_BOOT_CONFIG->mem_size_6105 = OS_BOOT_CONFIG->mem_size;
}
for (size_t i = 0; i < ARRAY_ITEMS(gpr_regs); i++) {
gpr_regs[i] = 0;
}
gpr_regs[CPU_REG_T3] = CPU_ADDRESS_IN_REG(SP_MEM->dmem[16]);
gpr_regs[CPU_REG_S3] = is_ddipl_boot ? OS_BOOT_ROM_TYPE_DD : OS_BOOT_ROM_TYPE_GAME_PAK;
gpr_regs[CPU_REG_S4] = os_tv_type;
gpr_regs[CPU_REG_S5] = OS_BOOT_RESET_TYPE_COLD;
gpr_regs[CPU_REG_S6] = BOOT_SEED_IPL3(cic_seed);
gpr_regs[CPU_REG_S7] = BOOT_SEED_OS_VERSION(cic_seed);
gpr_regs[CPU_REG_SP] = CPU_ADDRESS_IN_REG(SP_MEM->imem[ARRAY_ITEMS(SP_MEM->imem) - 4]);
gpr_regs[CPU_REG_RA] = CPU_ADDRESS_IN_REG(SP_MEM->imem[(os_tv_type == TV_PAL) ? 341 : 340]);
// return;
__asm__ (
".set noat \n\t"
".set noreorder \n\t"
"li $t0, 0x34000000 \n\t"
"mtc0 $t0, $12 \n\t"
"nop \n\t"
"li $t0, 0x0006E463 \n\t"
"mtc0 $t0, $16 \n\t"
"nop \n\t"
"li $t0, 0x00005000 \n\t"
"mtc0 $t0, $9 \n\t"
"nop \n\t"
"li $t0, 0x0000005C \n\t"
"mtc0 $t0, $13 \n\t"
"nop \n\t"
"li $t0, 0x007FFFF0 \n\t"
"mtc0 $t0, $4 \n\t"
"nop \n\t"
"li $t0, 0xFFFFFFFF \n\t"
"mtc0 $t0, $14 \n\t"
"nop \n\t"
"mtc0 $t0, $30 \n\t"
"nop \n\t"
"lui $t0, 0x0000 \n\t"
"mthi $t0 \n\t"
"nop \n\t"
"mtlo $t0 \n\t"
"nop \n\t"
"ctc1 $t0, $31 \n\t"
"nop \n\t"
"move $ra, %[gpr_regs] \n\t"
"ld $at, 0x08($ra) \n\t"
"ld $v0, 0x10($ra) \n\t"
"ld $v1, 0x18($ra) \n\t"
"ld $a0, 0x20($ra) \n\t"
"ld $a1, 0x28($ra) \n\t"
"ld $a2, 0x30($ra) \n\t"
"ld $a3, 0x38($ra) \n\t"
"ld $t0, 0x40($ra) \n\t"
"ld $t1, 0x48($ra) \n\t"
"ld $t2, 0x50($ra) \n\t"
"ld $t3, 0x58($ra) \n\t"
"ld $t4, 0x60($ra) \n\t"
"ld $t5, 0x68($ra) \n\t"
"ld $t6, 0x70($ra) \n\t"
"ld $t7, 0x78($ra) \n\t"
"ld $s0, 0x80($ra) \n\t"
"ld $s1, 0x88($ra) \n\t"
"ld $s2, 0x90($ra) \n\t"
"ld $s3, 0x98($ra) \n\t"
"ld $s4, 0xA0($ra) \n\t"
"ld $s5, 0xA8($ra) \n\t"
"ld $s6, 0xB0($ra) \n\t"
"ld $s7, 0xB8($ra) \n\t"
"ld $t8, 0xC0($ra) \n\t"
"ld $t9, 0xC8($ra) \n\t"
"ld $k0, 0xD0($ra) \n\t"
"ld $k1, 0xD8($ra) \n\t"
"ld $gp, 0xE0($ra) \n\t"
"ld $sp, 0xE8($ra) \n\t"
"ld $fp, 0xF0($ra) \n\t"
"ld $ra, 0xF8($ra) \n\t"
"jr $t3 \n\t"
"nop"
:
: [gpr_regs] "r" (gpr_regs)
: "t0", "ra"
);
}

View File

@ -1,69 +0,0 @@
#ifndef BOOT_H__
#define BOOT_H__
#include "platform.h"
struct cart_header_s {
uint32_t pi_conf;
uint32_t clock_rate;
uint32_t boot_addr;
uint32_t release_addr;
uint32_t crc_1;
uint32_t crc_2;
uint32_t ___unused_1[2];
char name[20];
uint32_t ___unused_2;
uint32_t format;
char id[2];
char country_code;
uint8_t version;
uint32_t boot_code[1008];
} __attribute__((packed, aligned(1)));
typedef struct cart_header_s cart_header_t;
struct os_boot_config_s {
uint32_t tv_type;
uint32_t rom_type;
uint32_t rom_base;
uint32_t reset_type;
uint32_t cic_id;
uint32_t version;
uint32_t mem_size;
uint8_t app_nmi_buffer[64];
uint32_t ___unused[37];
uint32_t mem_size_6105;
} __attribute__((packed, aligned(1)));
typedef struct os_boot_config_s os_boot_config_t;
typedef enum {
TV_PAL = 0,
TV_NTSC = 1,
TV_MPAL = 2,
} tv_type_t;
#define OS_BOOT_CONFIG_BASE (0xA0000300)
#define OS_BOOT_CONFIG ((os_boot_config_t *) OS_BOOT_CONFIG_BASE)
#define OS_BOOT_ROM_TYPE_GAME_PAK (0)
#define OS_BOOT_ROM_TYPE_DD (1)
#define OS_BOOT_RESET_TYPE_COLD (0)
#define OS_BOOT_RESET_TYPE_NMI (1)
#define OS_BOOT_RESET_TYPE_DISK (2)
#define BOOT_SEED_IPL3(x) (((x) & 0x000000FF) >> 0)
#define BOOT_SEED_OS_VERSION(x) (((x) & 0x00000100) >> 8)
cart_header_t *boot_load_cart_header(void);
uint16_t boot_get_cic_seed(cart_header_t *cart_header);
tv_type_t boot_get_tv_type(cart_header_t *cart_header);
void bootX(cart_header_t *cart_header, uint16_t cic_seed, tv_type_t tv_type);
#endif

View File

@ -1,170 +0,0 @@
#ifndef N64_REGS_H__
#define N64_REGS_H__
#include <inttypes.h>
#define ARRAY_ITEMS(x) (sizeof(x) / sizeof(x[0]))
#define CPU_ADDRESS_IN_REG(x) ((0xFFFFFFFFULL << 32) | ((uint32_t) (&(x))))
#define CPU_REG_Z0 (0)
#define CPU_REG_AT (1)
#define CPU_REG_V0 (2)
#define CPU_REG_V1 (3)
#define CPU_REG_A0 (4)
#define CPU_REG_A1 (5)
#define CPU_REG_A2 (6)
#define CPU_REG_A3 (7)
#define CPU_REG_T0 (8)
#define CPU_REG_T1 (9)
#define CPU_REG_T2 (10)
#define CPU_REG_T3 (11)
#define CPU_REG_T4 (12)
#define CPU_REG_T5 (13)
#define CPU_REG_T6 (14)
#define CPU_REG_T7 (15)
#define CPU_REG_S0 (16)
#define CPU_REG_S1 (17)
#define CPU_REG_S2 (18)
#define CPU_REG_S3 (19)
#define CPU_REG_S4 (20)
#define CPU_REG_S5 (21)
#define CPU_REG_S6 (22)
#define CPU_REG_S7 (23)
#define CPU_REG_T8 (24)
#define CPU_REG_T9 (25)
#define CPU_REG_K0 (26)
#define CPU_REG_K1 (27)
#define CPU_REG_GP (28)
#define CPU_REG_SP (29)
#define CPU_REG_FP (30)
#define CPU_REG_RA (31)
typedef struct SP_MEM_s {
volatile uint32_t dmem[1024];
volatile uint32_t imem[1024];
} SP_MEM_t;
typedef struct SP_regs_s {
volatile void *mem_addr;
volatile void *dram_addr;
volatile uint32_t rd_len;
volatile uint32_t wr_len;
volatile uint32_t status;
volatile uint32_t dma_full;
volatile uint32_t dma_busy;
volatile uint32_t semaphore;
} SP_regs_t;
typedef struct DP_CMD_regs_s {
volatile void *start;
volatile void *end;
volatile void *current;
volatile uint32_t status;
volatile uint32_t clock;
volatile uint32_t buf_busy;
volatile uint32_t pipe_busy;
volatile uint32_t tmem;
} DP_CMD_regs_t;
typedef struct MI_regs_s {
volatile uint32_t mode;
volatile uint32_t version;
volatile uint32_t interrupt;
volatile uint32_t interrupt_mask;
} MI_regs_t;
typedef struct VI_regs_s {
volatile uint32_t control;
volatile void *dram_addr;
volatile uint32_t h_width;
volatile uint32_t v_intr;
volatile uint32_t current_line;
volatile uint32_t timing;
volatile uint32_t v_sync;
volatile uint32_t h_sync;
volatile uint32_t h_sync_leap;
volatile uint32_t h_limits;
volatile uint32_t v_limits;
volatile uint32_t color_burst;
volatile uint32_t h_scale;
volatile uint32_t v_scale;
} VI_regs_t;
typedef struct AI_regs_s {
volatile void *dram_addr;
volatile uint32_t len;
volatile uint32_t control;
volatile uint32_t status;
volatile uint32_t dacrate;
volatile uint32_t bitrate;
} AI_regs_t;
typedef struct PI_regs_s {
volatile void *dram_addr;
volatile uint32_t cart_addr;
volatile uint32_t rd_len;
volatile uint32_t wr_len;
volatile uint32_t status;
volatile uint32_t dom1_lat;
volatile uint32_t dom1_pwd;
volatile uint32_t dom1_pgs;
volatile uint32_t dom1_rls;
volatile uint32_t dom2_lat;
volatile uint32_t dom2_pwd;
volatile uint32_t dom2_pgs;
volatile uint32_t dom2_rls;
} PI_regs_t;
#define SP_MEM_BASE (0xA4000000)
#define SP_REGS_BASE (0xA4040000)
#define DP_CMD_REGS_BASE (0xA4100000)
#define MI_REGS_BASE (0xA4300000)
#define VI_REGS_BASE (0xA4400000)
#define AI_REGS_BASE (0xA4500000)
#define PI_REGS_BASE (0xA4600000)
#define DDIPL_BASE (0xA6000000)
#define CART_BASE (0xB0000000)
#define SP_MEM ((volatile SP_MEM_t *) SP_MEM_BASE)
#define SP ((volatile SP_regs_t *) SP_REGS_BASE)
#define DP_CMD ((volatile DP_CMD_regs_t *) DP_CMD_REGS_BASE)
#define MI ((volatile MI_regs_t *) MI_REGS_BASE)
#define VI ((volatile VI_regs_t *) VI_REGS_BASE)
#define AI ((volatile AI_regs_t *) AI_REGS_BASE)
#define PI ((volatile PI_regs_t *) PI_REGS_BASE)
#define DDIPL ((volatile uint32_t *) DDIPL_BASE)
#define CART ((volatile uint32_t *) CART_BASE)
#define SP_STATUS_HALT (1 << 0)
#define SP_STATUS_DMA_BUSY (1 << 2)
#define SP_STATUS_SET_HALT (1 << 1)
#define SP_STATUS_CLEAR_INTERRUPT (1 << 3)
#define SP_DMA_BUSY (1 << 0)
#define DP_CMD_STATUS_XBUS_DMEM_DMA (1 << 0)
#define DP_CMD_STATUS_PIPE_BUSY (1 << 5)
#define DP_CMD_STATUS_CLEAR_XBUS_DMEM_DMA (1 << 0)
#define DP_CMD_STATUS_CLEAR_FREEZE (1 << 2)
#define DP_CMD_STATUS_CLEAR_FLUSH (1 << 4)
#define MI_INT_CLEAR_SP (1 << 0)
#define MI_INT_CLEAR_SI (1 << 2)
#define MI_INT_CLEAR_AI (1 << 4)
#define MI_INT_CLEAR_VI (1 << 6)
#define MI_INT_CLEAR_PI (1 << 8)
#define MI_INT_CLEAR_DP (1 << 10)
#define PI_STATUS_DMA_BUSY (1 << 0)
#define PI_STATUS_IO_BUSY (1 << 1)
#define PI_STATUS_RESET_CONTROLLER (1 << 0)
#define PI_STATUS_CLEAR_INTERRUPT (1 << 1)
#endif

View File

@ -1,20 +1,22 @@
#include <string.h>
#include "sc64.h" #include "sc64.h"
bool sc64_check_presence(void) { extern char header_text_info __attribute__((section(".data")));
bool sc64_check_presence (void) {
uint32_t version = pi_io_read(&SC64->VERSION); uint32_t version = pi_io_read(&SC64->VERSION);
return (version == SC64_VERSION_2); return (version == SC64_VERSION_2);
} }
void sc64_wait_cpu_ready(void) { void sc64_wait_cpu_ready (void) {
uint32_t sr; uint32_t sr;
do { do {
sr = pi_io_read(&SC64->SR_CMD); sr = pi_io_read(&SC64->SR_CMD);
} while (!(sr & SC64_SR_CPU_READY)); } while (!(sr & SC64_SR_CPU_READY));
} }
bool sc64_wait_cpu_busy(void) { bool sc64_wait_cpu_busy (void) {
uint32_t sr; uint32_t sr;
do { do {
sr = pi_io_read(&SC64->SR_CMD); sr = pi_io_read(&SC64->SR_CMD);
@ -22,7 +24,7 @@ bool sc64_wait_cpu_busy(void) {
return sr & SC64_SR_CMD_ERROR; return sr & SC64_SR_CMD_ERROR;
} }
bool sc64_perform_cmd(uint8_t cmd, uint32_t *args, uint32_t *result) { bool sc64_perform_cmd (uint8_t cmd, uint32_t *args, uint32_t *result) {
pi_io_write(&SC64->DATA[0], args[0]); pi_io_write(&SC64->DATA[0], args[0]);
pi_io_write(&SC64->DATA[1], args[1]); pi_io_write(&SC64->DATA[1], args[1]);
pi_io_write(&SC64->SR_CMD, (uint32_t) cmd); pi_io_write(&SC64->SR_CMD, (uint32_t) cmd);
@ -34,20 +36,20 @@ bool sc64_perform_cmd(uint8_t cmd, uint32_t *args, uint32_t *result) {
return error; return error;
} }
uint32_t sc64_get_config(cfg_id_t id) { uint32_t sc64_get_config (cfg_id_t id) {
uint32_t args[2] = { id, 0 }; uint32_t args[2] = { id, 0 };
uint32_t result[2]; uint32_t result[2];
sc64_perform_cmd(SC64_CMD_QUERY, args, result); sc64_perform_cmd(SC64_CMD_QUERY, args, result);
return result[1]; return result[1];
} }
void sc64_set_config(cfg_id_t id, uint32_t value) { void sc64_set_config (cfg_id_t id, uint32_t value) {
uint32_t args[2] = { id, value }; uint32_t args[2] = { id, value };
sc64_perform_cmd(SC64_CMD_CONFIG, args, NULL); sc64_perform_cmd(SC64_CMD_CONFIG, args, NULL);
} }
void sc64_get_info(cart_info_t *info) { void sc64_get_info (sc64_info_t *info) {
io32_t *src = UNCACHED(&header_text_info); io32_t *src = (io32_t *) UNCACHED(&header_text_info);
uint32_t *dst = (uint32_t *) info->bootloader_version; uint32_t *dst = (uint32_t *) info->bootloader_version;
sc64_set_config(CFG_ID_SDRAM_SWITCH, false); sc64_set_config(CFG_ID_SDRAM_SWITCH, false);
@ -58,14 +60,37 @@ void sc64_get_info(cart_info_t *info) {
info->dd_enabled = (bool) sc64_get_config(CFG_ID_DD_ENABLE); info->dd_enabled = (bool) sc64_get_config(CFG_ID_DD_ENABLE);
info->save_type = (save_type_t) sc64_get_config(CFG_ID_SAVE_TYPE); info->save_type = (save_type_t) sc64_get_config(CFG_ID_SAVE_TYPE);
info->cic_seed = (uint8_t) sc64_get_config(CFG_ID_CIC_SEED); info->cic_seed = (uint16_t) sc64_get_config(CFG_ID_CIC_SEED);
info->tv_type = (tv_type_t) sc64_get_config(CFG_ID_TV_TYPE); info->tv_type = (tv_type_t) sc64_get_config(CFG_ID_TV_TYPE);
info->save_offset = (io32_t *) (0x10000000 | sc64_get_config(CFG_ID_SAVE_OFFEST)); info->save_offset = (io32_t *) (0x10000000 | sc64_get_config(CFG_ID_SAVE_OFFEST));
info->dd_offset = (io32_t *) (0x10000000 | sc64_get_config(CFG_ID_DD_OFFEST)); info->dd_offset = (io32_t *) (0x10000000 | sc64_get_config(CFG_ID_DD_OFFEST));
info->boot_mode = (boot_mode_t) sc64_get_config(CFG_ID_BOOT_MODE); info->boot_mode = (boot_mode_t) sc64_get_config(CFG_ID_BOOT_MODE);
} }
void sc64_wait_usb_tx_ready(void) { void sc64_wait_usb_rx_ready (uint32_t *type, uint32_t *length) {
uint32_t args[2] = { 0, 0 };
uint32_t result[2];
do {
sc64_perform_cmd(SC64_CMD_DEBUG_RX_READY, args, result);
} while (result[0] == 0 && result[1] == 0);
*type = result[0];
*length = result[1];
}
void sc64_wait_usb_rx_busy (void) {
uint32_t args[2] = { 0, 0 };
uint32_t result[2];
do {
sc64_perform_cmd(SC64_CMD_DEBUG_RX_BUSY, args, result);
} while (result[0]);
}
void sc64_usb_rx_data (io32_t *address, uint32_t length) {
uint32_t args[2] = { (uint32_t) (address), length };
sc64_perform_cmd(SC64_CMD_DEBUG_RX_DATA, args, NULL);
}
void sc64_wait_usb_tx_ready (void) {
uint32_t args[2] = { 0, 0 }; uint32_t args[2] = { 0, 0 };
uint32_t result[2]; uint32_t result[2];
do { do {
@ -73,27 +98,26 @@ void sc64_wait_usb_tx_ready(void) {
} while (!result[0]); } while (!result[0]);
} }
void sc64_usb_tx_data(io32_t *address, uint32_t length) { void sc64_usb_tx_data (io32_t *address, uint32_t length) {
uint32_t args[2] = { (uint32_t) (address), length }; uint32_t args[2] = { (uint32_t) (address), length };
sc64_perform_cmd(SC64_CMD_DEBUG_TX_DATA, args, NULL); sc64_perform_cmd(SC64_CMD_DEBUG_TX_DATA, args, NULL);
} }
void sc64_debug_write(uint8_t type, const void *data, uint32_t len) { void sc64_debug_write (uint8_t type, const void *data, uint32_t len) {
char *dma = "DMA@"; char *dma = "DMA@";
char *cmp = "CMPH"; char *cmp = "CMPH";
io32_t *sdram = UNCACHED(SC64_DEBUG_WRITE_ADDRESS); io32_t *sdram = (io32_t *) (SC64_DEBUG_WRITE_ADDRESS);
io32_t *src = (io32_t *) (data); uint32_t *src = (uint32_t *) (data);
io32_t *dst = sdram; io32_t *dst = sdram;
uint32_t copy_length = ALIGN(len, 4); uint32_t copy_length = ALIGN(len, 4);
uint32_t transfer_length = 4 + 4 + copy_length + 4;
bool writable = sc64_get_config(CFG_ID_SDRAM_WRITABLE);
sc64_wait_usb_tx_ready(); sc64_wait_usb_tx_ready();
bool writable = sc64_get_config(CFG_ID_SDRAM_WRITABLE);
if (!writable) { if (!writable) {
sc64_set_config(CFG_ID_SDRAM_WRITABLE, true); sc64_set_config(CFG_ID_SDRAM_WRITABLE, true);
} }
@ -101,8 +125,13 @@ void sc64_debug_write(uint8_t type, const void *data, uint32_t len) {
pi_io_write(dst++, *((uint32_t *) (dma))); pi_io_write(dst++, *((uint32_t *) (dma)));
pi_io_write(dst++, (type << 24) | len); pi_io_write(dst++, (type << 24) | len);
for (uint32_t i = 0; i < copy_length; i += 4) { while (src < ((uint32_t *) (data + copy_length))) {
pi_io_write(dst++, *src++); pi_io_write(dst++, *src++);
if (dst >= (io32_t *) ((void *) (sdram) + SC64_DEBUG_MAX_SIZE)) {
sc64_usb_tx_data(sdram, (dst - sdram) * sizeof(uint32_t));
sc64_wait_usb_tx_ready();
dst = sdram;
}
} }
pi_io_write(dst++, *((uint32_t *) (cmp))); pi_io_write(dst++, *((uint32_t *) (cmp)));
@ -111,14 +140,44 @@ void sc64_debug_write(uint8_t type, const void *data, uint32_t len) {
sc64_set_config(CFG_ID_SDRAM_WRITABLE, false); sc64_set_config(CFG_ID_SDRAM_WRITABLE, false);
} }
sc64_usb_tx_data(sdram, transfer_length); sc64_usb_tx_data(sdram, (dst - sdram) * sizeof(uint32_t));
} }
void sc64_debug_print(const char *text) { void sc64_debug_fsd_read (const void *data, uint32_t sector, uint32_t count) {
sc64_debug_write(SC64_DEBUG_TYPE_TEXT, text, strlen(text)); uint32_t type;
uint32_t length;
io32_t *sdram = (io32_t *) (SC64_DEBUG_READ_ADDRESS);
io32_t *src = sdram;
uint32_t *dst = (uint32_t *) (data);
uint32_t info[2] = { sector, count };
sc64_debug_write(SC64_DEBUG_TYPE_FSD_READ, &info, sizeof(info));
sc64_wait_usb_rx_ready(&type, &length);
sc64_usb_rx_data(sdram, length);
sc64_wait_usb_rx_busy();
uint32_t copy_length = ALIGN(length, 4);
for (int i = 0; i < copy_length; i += 4) {
*dst++ = pi_io_read(src++);
}
} }
void sc64_init(void) { void sc64_debug_fsd_write (const void *data, uint32_t sector, uint32_t count) {
uint32_t length = (8 + (count * 512)) / 4;
uint32_t buffer[length];
buffer[0] = sector;
buffer[1] = count;
for (uint32_t i = 0; i < count * 512; i += 4) {
buffer[2 + i] = ((uint32_t *) (data))[i];
}
sc64_debug_write(SC64_DEBUG_TYPE_FSD_WRITE, buffer, length);
}
void sc64_init (void) {
while (!sc64_check_presence()); while (!sc64_check_presence());
sc64_wait_cpu_ready(); sc64_wait_cpu_ready();
sc64_set_config(CFG_ID_SDRAM_SWITCH, true); sc64_set_config(CFG_ID_SDRAM_SWITCH, true);

View File

@ -3,6 +3,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include "sys.h" #include "sys.h"
@ -33,6 +34,9 @@ typedef struct {
#define SC64_CMD_CONFIG ('C') #define SC64_CMD_CONFIG ('C')
#define SC64_CMD_QUERY ('Q') #define SC64_CMD_QUERY ('Q')
#define SC64_CMD_DEBUG_RX_DATA ('E')
#define SC64_CMD_DEBUG_RX_READY ('A')
#define SC64_CMD_DEBUG_RX_BUSY ('F')
#define SC64_CMD_DEBUG_TX_DATA ('D') #define SC64_CMD_DEBUG_TX_DATA ('D')
#define SC64_CMD_DEBUG_TX_READY ('S') #define SC64_CMD_DEBUG_TX_READY ('S')
@ -43,6 +47,8 @@ typedef struct {
#define SC64_DEBUG_MAX_SIZE (32 * 1024) #define SC64_DEBUG_MAX_SIZE (32 * 1024)
#define SC64_DEBUG_TYPE_TEXT (0x01) #define SC64_DEBUG_TYPE_TEXT (0x01)
#define SC64_DEBUG_TYPE_FSD_READ (0xF1)
#define SC64_DEBUG_TYPE_FSD_WRITE (0xF2)
typedef enum { typedef enum {
@ -89,16 +95,13 @@ typedef enum {
typedef struct { typedef struct {
bool dd_enabled; bool dd_enabled;
save_type_t save_type; save_type_t save_type;
uint8_t cic_seed; uint16_t cic_seed;
tv_type_t tv_type; tv_type_t tv_type;
io32_t *save_offset; io32_t *save_offset;
io32_t *dd_offset; io32_t *dd_offset;
boot_mode_t boot_mode; boot_mode_t boot_mode;
char bootloader_version[32]; char bootloader_version[32];
} cart_info_t; } sc64_info_t;
extern char header_text_info;
bool sc64_check_presence(void); bool sc64_check_presence(void);
@ -107,11 +110,15 @@ bool sc64_wait_cpu_busy(void);
bool sc64_perform_cmd(uint8_t cmd, uint32_t *args, uint32_t *result); bool sc64_perform_cmd(uint8_t cmd, uint32_t *args, uint32_t *result);
uint32_t sc64_get_config(cfg_id_t id); uint32_t sc64_get_config(cfg_id_t id);
void sc64_set_config(cfg_id_t id, uint32_t value); void sc64_set_config(cfg_id_t id, uint32_t value);
void sc64_get_info(cart_info_t *info); void sc64_get_info(sc64_info_t *info);
void sc64_wait_usb_rx_ready (uint32_t *type, uint32_t *length);
void sc64_wait_usb_rx_busy (void);
void sc64_usb_rx_data (io32_t *address, uint32_t length);
void sc64_wait_usb_tx_ready(void); void sc64_wait_usb_tx_ready(void);
void sc64_usb_tx_data(io32_t *address, uint32_t length); void sc64_usb_tx_data(io32_t *address, uint32_t length);
void sc64_debug_write(uint8_t type, const void *data, uint32_t len); void sc64_debug_write(uint8_t type, const void *data, uint32_t len);
void sc64_debug_print(const char *text); void sc64_debug_fsd_read(const void *data, uint32_t sector, uint32_t count);
void sc64_debug_fsd_write(const void *data, uint32_t sector, uint32_t count);
void sc64_init(void); void sc64_init(void);

View File

@ -48,3 +48,19 @@ run:
loop: loop:
j loop j loop
.section .text.ipl2
ipl2:
.global ipl2
.set noat
.set noreorder
lui $t5, 0xBFC0
1:
lw $t0, 0x7FC($t5)
addiu $t5, $t5, 0x7C0
andi $t0, $t0, 0x80
bnel $t0, $zero, 1b
lui $t5, 0xBFC0
lw $t0, 0x24($t5)
lui $t3, 0xB000

View File

@ -1,57 +1,73 @@
#include "sys.h" #include "sys.h"
static uint32_t c0_get_count(void) { void c0_set_status (uint32_t status) {
uint32_t x; __asm__ volatile (
asm volatile("mfc0 %0,$9" : "=r" (x)); ".set noat \n"
return x; ".set noreorder \n"
"mtc0 %[status], $12 \n"
"nop \n"
:
: [status] "r" (status)
);
} }
void wait_ms(uint32_t ms) { uint32_t c0_get_count (void) {
uint32_t count;
__asm__ volatile (
".set noat \n"
".set noreorder \n"
"mfc0 %[count], $9 \n"
"nop \n"
: [count] "=r" (count)
);
return count;
}
void wait_ms (uint32_t ms) {
uint32_t start = c0_get_count(); uint32_t start = c0_get_count();
while (c0_get_count() - start < (ms * ((CPU_FREQUENCY / 2) / 1000))); while (c0_get_count() - start < (ms * ((CPU_FREQUENCY / 2) / 1000)));
} }
uint32_t io_read(io32_t *address) { uint32_t io_read (io32_t *address) {
asm volatile ("" : : : "memory"); io32_t *uncached = UNCACHED(address);
uint32_t value = *UNCACHED(address); __asm__ volatile ("" : : : "memory");
asm volatile ("" : : : "memory"); uint32_t value = *uncached;
__asm__ volatile ("" : : : "memory");
return value; return value;
} }
void io_write(io32_t *address, uint32_t value) { void io_write (io32_t *address, uint32_t value) {
asm volatile ("" : : : "memory"); io32_t *uncached = UNCACHED(address);
*UNCACHED(address) = value; __asm__ volatile ("" : : : "memory");
asm volatile ("" : : : "memory"); *uncached = value;
__asm__ volatile ("" : : : "memory");
} }
uint32_t pi_busy(void) { uint32_t pi_busy (void) {
return (io_read(&PI->SR) & (PI_SR_IO_BUSY | PI_SR_DMA_BUSY)); return (io_read(&PI->SR) & (PI_SR_IO_BUSY | PI_SR_DMA_BUSY));
} }
uint32_t pi_io_read(io32_t *address) { uint32_t pi_io_read (io32_t *address) {
while (pi_busy());
return io_read(address); return io_read(address);
} }
void pi_io_write(io32_t *address, uint32_t value) { void pi_io_write (io32_t *address, uint32_t value) {
io_write(address, value);
while (pi_busy()); while (pi_busy());
io_write(address, value);
} }
uint32_t si_busy(void) { uint32_t si_busy (void) {
return (io_read(&SI->SR) & (SI_SR_IO_BUSY | SI_SR_DMA_BUSY)); return (io_read(&SI->SR) & (SI_SR_IO_BUSY | SI_SR_DMA_BUSY));
} }
uint32_t si_io_read(io32_t *address) { uint32_t si_io_read (io32_t *address) {
while (si_busy());
return io_read(address); return io_read(address);
} }
void si_io_write(io32_t *address, uint32_t value) { void si_io_write (io32_t *address, uint32_t value) {
io_write(address, value);
while (si_busy()); while (si_busy());
} io_write(address, value);
void init(void) {
uint32_t pifram = si_io_read((io32_t *) (&PIFRAM[0x3C]));
si_io_write((io32_t *) (&PIFRAM[0x3C]), pifram | 0x08);
} }

View File

@ -2,8 +2,8 @@
#define SYS_H__ #define SYS_H__
#include <inttypes.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h>
typedef volatile uint8_t io8_t; typedef volatile uint8_t io8_t;
@ -12,27 +12,191 @@ typedef volatile uint32_t io32_t;
#define ALIGN(value, align) (((value) + ((typeof(value))(align) - 1)) & ~((typeof(value))(align) - 1)) #define ALIGN(value, align) (((value) + ((typeof(value))(align) - 1)) & ~((typeof(value))(align) - 1))
#define CACHED(address) ((io32_t *) ((((io32_t) (address)) & 0x1FFFFFFFUL) | 0x80000000UL)) #define UNCACHED(address) ((typeof(address)) (((io32_t) (address)) | (0xA0000000UL)))
#define UNCACHED(address) ((io32_t *) ((((io32_t) (address)) & 0x1FFFFFFFUL) | 0xA0000000UL))
#define CPU_FREQUENCY (93750000UL) #define CPU_FREQUENCY (93750000UL)
typedef struct { #define C0_SR_CU3 (1 << 31)
uint32_t tv_type; #define C0_SR_CU2 (1 << 30)
uint32_t rom_type; #define C0_SR_CU1 (1 << 29)
uint32_t rom_base; #define C0_SR_CU0 (1 << 28)
uint32_t reset_type; #define C0_SR_RP (1 << 27)
uint32_t cic_id; #define C0_SR_FR (1 << 26)
uint32_t version; #define C0_SR_RE (1 << 25)
uint32_t mem_size; #define C0_SR_DS_ITS (1 << 24)
uint8_t app_nmi_buffer[64]; #define C0_SR_DS_BEV (1 << 22)
uint32_t __reserved_1[37]; #define C0_SR_DS_TS (1 << 21)
uint32_t mem_size_6105; #define C0_SR_DS_SR (1 << 20)
} boot_info_t; #define C0_SR_DS_CH (1 << 18)
#define C0_SR_DS_CE (1 << 17)
#define C0_SR_DS_DE (1 << 16)
#define C0_SR_IM7 (1 << 15)
#define C0_SR_IM6 (1 << 14)
#define C0_SR_IM5 (1 << 13)
#define C0_SR_IM4 (1 << 12)
#define C0_SR_IM3 (1 << 11)
#define C0_SR_IM2 (1 << 10)
#define C0_SR_IM1 (1 << 9)
#define C0_SR_IM0 (1 << 8)
#define C0_SR_KX (1 << 7)
#define C0_SR_SX (1 << 6)
#define C0_SR_UX (1 << 5)
#define C0_SR_KSU1 (1 << 4)
#define C0_SR_KSU0 (1 << 3)
#define C0_SR_EXR (1 << 2)
#define C0_SR_EXL (1 << 1)
#define C0_SR_IE (1 << 0)
#define BOOT_INFO_BASE (0x00000300UL)
#define BOOT_INFO ((boot_info_t *) BOOT_INFO_BASE) typedef struct {
io32_t DMEM[1024];
io32_t IMEM[1024];
} sp_mem_t;
#define SP_MEM_BASE (0x04000000UL)
#define SP_MEM ((sp_mem_t *) SP_MEM_BASE)
typedef struct {
io32_t PADDR;
io32_t MADDR;
io32_t RD_LEN;
io32_t WR_LEN;
io32_t SR;
io32_t DMA_FULL;
io32_t DMA_BUSY;
io32_t SEMAPHORE;
} sp_regs_t;
#define SP_BASE (0x04040000UL)
#define SP ((sp_regs_t *) SP_BASE)
#define SP_SR_HALT (1 << 0)
#define SP_SR_BROKE (1 << 1)
#define SP_SR_DMA_BUSY (1 << 2)
#define SP_SR_DMA_FULL (1 << 3)
#define SP_SR_IO_FULL (1 << 4)
#define SP_SR_SSTEP (1 << 5)
#define SP_SR_INTR_BREAK (1 << 6)
#define SP_SR_SIG0 (1 << 7)
#define SP_SR_SIG1 (1 << 8)
#define SP_SR_SIG2 (1 << 9)
#define SP_SR_SIG3 (1 << 10)
#define SP_SR_SIG4 (1 << 11)
#define SP_SR_SIG5 (1 << 12)
#define SP_SR_SIG6 (1 << 13)
#define SP_SR_SIG7 (1 << 14)
#define SP_SR_CLR_HALT (1 << 0)
#define SP_SR_SET_HALT (1 << 1)
#define SP_SR_CLR_BROKE (1 << 2)
#define SP_SR_CLR_INTR (1 << 3)
#define SP_SR_SET_INTR (1 << 4)
#define SP_SR_CLR_SSTEP (1 << 5)
#define SP_SR_SET_SSTEP (1 << 6)
#define SP_SR_CLR_INTR_BREAK (1 << 7)
#define SP_SR_SET_INTR_BREAK (1 << 8)
#define SP_SR_CLR_SIG0 (1 << 9)
#define SP_SR_SET_SIG0 (1 << 10)
#define SP_SR_CLR_SIG1 (1 << 11)
#define SP_SR_SET_SIG1 (1 << 12)
#define SP_SR_CLR_SIG2 (1 << 13)
#define SP_SR_SET_SIG2 (1 << 14)
#define SP_SR_CLR_SIG3 (1 << 15)
#define SP_SR_SET_SIG3 (1 << 16)
#define SP_SR_CLR_SIG4 (1 << 17)
#define SP_SR_SET_SIG4 (1 << 18)
#define SP_SR_CLR_SIG5 (1 << 19)
#define SP_SR_SET_SIG5 (1 << 20)
#define SP_SR_CLR_SIG6 (1 << 21)
#define SP_SR_SET_SIG6 (1 << 22)
#define SP_SR_CLR_SIG7 (1 << 23)
#define SP_SR_SET_SIG7 (1 << 24)
typedef struct {
io32_t START;
io32_t END;
io32_t CURRENT;
io32_t SR;
io32_t CLOCK;
io32_t BUF_BUSY;
io32_t PIPE_BUSY;
io32_t TMEM;
} dpc_regs_t;
#define DPC_BASE (0x04100000UL)
#define DPC ((dpc_regs_t *) DPC_BASE)
#define DPC_SR_XBUS_DMEM_DMA (1 << 0)
#define DPC_SR_FREEZE (1 << 1)
#define DPC_SR_FLUSH (1 << 2)
#define DPC_SR_START_GCLK (1 << 3)
#define DPC_SR_TMEM_BUSY (1 << 4)
#define DPC_SR_PIPE_BUSY (1 << 5)
#define DPC_SR_CMD_BUSY (1 << 6)
#define DPC_SR_CBUF_READY (1 << 7)
#define DPC_SR_DMA_BUSY (1 << 8)
#define DPC_SR_END_VALID (1 << 9)
#define DPC_SR_START_VALID (1 << 10)
#define DPC_SR_CLR_XBUS_DMEM_DMA (1 << 0)
#define DPC_SR_SET_XBUS_DMEM_DMA (1 << 1)
#define DPC_SR_CLR_FREEZE (1 << 2)
#define DPC_SR_SET_FREEZE (1 << 3)
#define DPC_SR_CLR_FLUSH (1 << 4)
#define DPC_SR_SET_FLUSH (1 << 5)
#define DPC_SR_CLR_TMEM_CTR (1 << 6)
#define DPC_SR_CLR_PIPE_CTR (1 << 7)
#define DPC_SR_CLR_CMD_CTR (1 << 8)
#define DPC_SR_CLR_CLOCK_CTR (1 << 9)
typedef struct {
io32_t CR;
io32_t MADDR;
io32_t H_WIDTH;
io32_t V_INTR;
io32_t CURR_LINE;
io32_t TIMING;
io32_t V_SYNC;
io32_t H_SYNC;
io32_t H_SYNC_LEAP;
io32_t H_LIMITS;
io32_t V_LIMITS;
io32_t COLOR_BURST;
io32_t H_SCALE;
io32_t V_SCALE;
} vi_regs_t;
#define VI_BASE (0x04400000UL)
#define VI ((vi_regs_t *) VI_BASE)
#define VI_CR_TYPE_16 (2 << 0)
#define VI_CR_TYPE_32 (3 << 0)
#define VI_CR_GAMMA_DITHER_ON (1 << 2)
#define VI_CR_GAMMA_ON (1 << 3)
#define VI_CR_DIVOT_ON (1 << 4)
#define VI_CR_SERRATE_ON (1 << 6)
#define VI_CR_ANTIALIAS_0 (1 << 8)
#define VI_CR_ANTIALIAS_1 (1 << 9)
#define VI_CR_DITHER_FILTER_ON (1 << 16)
typedef struct {
io32_t MADDR;
io32_t LEN;
io32_t CR;
io32_t SR;
io32_t DACRATE;
io32_t BITRATE;
} ai_regs_t;
#define AI_BASE (0x04500000UL)
#define AI ((ai_regs_t *) AI_BASE)
#define AI_SR_DMA_BUSY (1 << 30)
#define AI_SR_FIFO_FULL (1 << 31)
#define AI_CR_DMA_ON (1 << 0)
typedef struct { typedef struct {
@ -55,8 +219,8 @@ typedef struct {
#define PI_SR_DMA_BUSY (1 << 0) #define PI_SR_DMA_BUSY (1 << 0)
#define PI_SR_IO_BUSY (1 << 1) #define PI_SR_IO_BUSY (1 << 1)
#define PI_SR_DMA_ERROR (1 << 2) #define PI_SR_DMA_ERROR (1 << 2)
#define PI_SR_RESET_CONTROLLER (1 << 0) #define PI_SR_RESET (1 << 0)
#define PI_SR_CLEAR_INTERRUPT (1 << 1) #define PI_SR_CLR_INTR (1 << 1)
typedef struct { typedef struct {
@ -82,7 +246,7 @@ typedef struct {
typedef struct { typedef struct {
uint32_t pi_config; uint32_t pi_config;
uint32_t clock_rate; uint32_t clock_rate;
uint32_t load_addr; void (*entry_point)(void);
struct { struct {
uint16_t __reserved_1; uint16_t __reserved_1;
uint8_t major; uint8_t major;
@ -91,31 +255,32 @@ typedef struct {
uint32_t crc[2]; uint32_t crc[2];
uint32_t __reserved_1[2]; uint32_t __reserved_1[2];
char name[20]; char name[20];
uint8_t ___reserved_2[7]; uint8_t __reserved_2[7];
char id[4]; char id[4];
uint8_t version; uint8_t revision;
uint32_t ipl3[1008];
} rom_header_t; } rom_header_t;
#define ROM_HEADER_DDIPL_BASE (0x06000000UL) #define ROM_DDIPL_BASE (0x06000000UL)
#define ROM_HEADER_DDIPL ((rom_header_t *) ROM_HEADER_DDIPL_BASE) #define ROM_DDIPL ((io32_t *) ROM_DDIPL_BASE)
#define ROM_HEADER_CART_BASE (0x10000000UL) #define ROM_CART_BASE (0x10000000UL)
#define ROM_HEADER_CART ((rom_header_t *) ROM_HEADER_CART_BASE) #define ROM_CART ((io32_t *) ROM_CART_BASE)
#define PIFRAM_BASE (0x1FC007C0UL) #define PIFRAM_BASE (0x1FC007C0UL)
#define PIFRAM ((io8_t *) PIFRAM_BASE) #define PIFRAM ((io8_t *) PIFRAM_BASE)
void wait_ms(uint32_t ms); void c0_set_status (uint32_t status);
uint32_t io_read(io32_t *address); uint32_t c0_get_count (void);
void io_write(io32_t *address, uint32_t value); void wait_ms (uint32_t ms);
uint32_t pi_busy(void); uint32_t io_read (io32_t *address);
uint32_t pi_io_read(io32_t *address); void io_write (io32_t *address, uint32_t value);
void pi_io_write(io32_t *address, uint32_t value); uint32_t pi_busy (void);
uint32_t si_busy(void); uint32_t pi_io_read (io32_t *address);
uint32_t si_io_read(io32_t *address); void pi_io_write (io32_t *address, uint32_t value);
void si_io_write(io32_t *address, uint32_t value); uint32_t si_busy (void);
uint32_t si_io_read (io32_t *address);
void si_io_write (io32_t *address, uint32_t value);
#endif #endif

View File

@ -1,35 +1,44 @@
#include <stdio.h>
#include <errno.h> #include <errno.h>
#include <sys/types.h> #include <stdio.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "sc64.h" #include "sc64.h"
int _close_r(struct _reent *prt, int fd) { extern char _sheap __attribute__((section(".data")));
extern char _eheap __attribute__((section(".data")));
int _close_r (struct _reent *prt, int fd) {
errno = ENOSYS;
return -1; return -1;
} }
int _fstat_r(struct _reent *prt, int fd, struct stat *pstat) { int _fstat_r (struct _reent *prt, int fd, struct stat *pstat) {
pstat->st_mode = S_IFCHR; errno = ENOSYS;
return -1;
}
int _isatty_r (struct _reent *prt, int fd) {
if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO){
return 1;
}
errno = EBADF;
return 0; return 0;
} }
int _isatty_r(struct _reent *prt, int fd) { off_t _lseek_r (struct _reent *prt, int fd, off_t pos, int whence) {
return 1; errno = ENOSYS;
return -1;
} }
off_t _lseek_r(struct _reent *prt, int fd, off_t pos, int whence) { ssize_t _read_r (struct _reent *prt, int fd, void *buf, size_t cnt) {
return 0; errno = ENOSYS;
return -1;
} }
ssize_t _read_r(struct _reent *prt, int fd, void *buf, size_t cnt) { caddr_t _sbrk_r (struct _reent *prt, ptrdiff_t incr) {
return 0;
}
caddr_t _sbrk_r(struct _reent *prt, ptrdiff_t incr) {
extern char _sheap;
extern char _eheap;
static char *curr_heap_end = &_sheap; static char *curr_heap_end = &_sheap;
char *prev_heap_end; char *prev_heap_end;
@ -44,12 +53,19 @@ caddr_t _sbrk_r(struct _reent *prt, ptrdiff_t incr) {
return (caddr_t) prev_heap_end; return (caddr_t) prev_heap_end;
} }
ssize_t _write_r(struct _reent *prt, int fd, const void *buf, size_t cnt) { ssize_t _write_r (struct _reent *prt, int fd, const void *buf, size_t cnt) {
sc64_debug_write(SC64_DEBUG_TYPE_TEXT, buf, cnt); if (fd == STDIN_FILENO) {
return cnt; errno = EBADF;
return -1;
} else if (fd == STDOUT_FILENO || fd == STDERR_FILENO) {
sc64_debug_write(SC64_DEBUG_TYPE_TEXT, buf, cnt);
return cnt;
}
errno = ENOSYS;
return -1;
} }
void __assert_func(const char *file, int line, const char *func, const char *failedexpr) { void __assert_func (const char *file, int line, const char *func, const char *failedexpr) {
LOG_E("\r\nassertion \"%s\" failed: file \"%s\", line %d%s%s\r\n", failedexpr, file, line, func ? ", function: " : "", func ? func : ""); LOG_E("\r\nassertion \"%s\" failed: file \"%s\", line %d%s%s\r\n", failedexpr, file, line, func ? ", function: " : "", func ? func : "");
while (1); while (1);
} }

2
sw/pc/.gitignore vendored
View File

@ -1,3 +1,4 @@
/__pycache__
/backup /backup
/roms /roms
/saves /saves
@ -7,6 +8,7 @@
*.data *.data
*.eep *.eep
*.fla *.fla
*.img
*.n64 *.n64
*.srm *.srm
*.v64 *.v64

View File

@ -43,6 +43,8 @@ class SC64:
__DDIPL_ROM_LENGTH = 0x400000 __DDIPL_ROM_LENGTH = 0x400000
__DEBUG_ID_TEXT = 0x01 __DEBUG_ID_TEXT = 0x01
__DEBUG_ID_FSD_READ = 0xF1
__DEBUG_ID_FSD_WRITE = 0xF2
def __init__(self) -> None: def __init__(self) -> None:
@ -50,12 +52,15 @@ class SC64:
self.__progress_init = None self.__progress_init = None
self.__progress_value = None self.__progress_value = None
self.__progress_finish = None self.__progress_finish = None
self.__fsd_file = None
self.__find_sc64() self.__find_sc64()
def __del__(self) -> None: def __del__(self) -> None:
if (self.__serial): if (self.__serial):
self.__serial.close() self.__serial.close()
if (self.__fsd_file):
self.__fsd_file.close()
def __set_progress_init(self, value: int, label: str) -> None: def __set_progress_init(self, value: int, label: str) -> None:
@ -172,6 +177,11 @@ class SC64:
self.__read_cmd_status("C") self.__read_cmd_status("C")
def __debug_write(self, type: int, data: bytes) -> None:
self.__write_cmd("D", type, len(data))
self.__write(data)
def __read_file_from_sdram(self, file: str, offset: int, length: int, align: int = 2) -> None: def __read_file_from_sdram(self, file: str, offset: int, length: int, align: int = 2) -> None:
with open(file, "wb") as f: with open(file, "wb") as f:
transfer_size = self.__align(length, align) transfer_size = self.__align(length, align)
@ -274,11 +284,13 @@ class SC64:
}[type] }[type]
def set_cic_seed(self, type: int = None) -> None: def set_cic_seed(self, seed: int = None) -> None:
if (type == None): if (seed == None or seed == 0xFFFF):
self.__change_config(self.__CFG_ID_CIC_SEED, 0xFFFF) self.__change_config(self.__CFG_ID_CIC_SEED, 0xFFFF)
elif (seed >= 0 and seed <= 0x1FF):
self.__change_config(self.__CFG_ID_CIC_SEED, seed)
else: else:
self.__change_config(self.__CFG_ID_CIC_SEED, type) raise SC64Exception("CIC seed outside of supported values")
def download_rom(self, file: str, length: int, offset: int = 0) -> None: def download_rom(self, file: str, length: int, offset: int = 0) -> None:
@ -347,10 +359,23 @@ class SC64:
self.__write_file_to_sdram(file, dd_ipl_offset, min_length=self.__DDIPL_ROM_LENGTH) self.__write_file_to_sdram(file, dd_ipl_offset, min_length=self.__DDIPL_ROM_LENGTH)
def debug_loop(self) -> None: def __debug_process_fsd_read(self, file: str, id: int, data: bytes) -> None:
print("\r\nDebug server started\r\n") sector = int.from_bytes(data[0:4], byteorder='big')
count = int.from_bytes(data[4:8], byteorder='big')
if (file):
if (self.__fsd_file == None):
self.__fsd_file = open(file, "rb")
self.__fsd_file.seek(sector * 512)
self.__debug_write(id, self.__fsd_file.read(count * 512))
else:
self.__debug_write(id, bytes(count * 512))
def debug_loop(self, file: str = None) -> None:
print("\033[34m --- Debug server started --- \033[0m")
self.__serial.timeout = 0.01 self.__serial.timeout = 0.01
self.__serial.write_timeout = 1
while (True): while (True):
start_indicator = self.__read_long(4) start_indicator = self.__read_long(4)
@ -358,19 +383,28 @@ class SC64:
header = self.__read_long(4) header = self.__read_long(4)
id = int(header[0]) id = int(header[0])
length = int.from_bytes(header[1:4], byteorder="big") length = int.from_bytes(header[1:4], byteorder="big")
if (length > 0):
align = self.__align(length, 4) - length align = self.__align(length, 4) - length
data = self.__read_long(length) data = self.__read_long(length)
if (id == self.__DEBUG_ID_TEXT): if (id == self.__DEBUG_ID_TEXT):
print(data.decode(encoding="ascii", errors="backslashreplace"), end="") print(data.decode(encoding="ascii", errors="backslashreplace"), end="")
sys.stdout.flush() elif (id == self.__DEBUG_ID_FSD_READ):
else: pass
print(f"Got unknown id: {id}, length: {length}") elif (id == self.__DEBUG_ID_FSD_WRITE):
pass
else:
print(f"Got unknown id: {id}, length: {length}")
self.__read_long(align)
end_indicator = self.__read_long(4)
if (end_indicator != b"CMPH"):
print(f"Got unknown end indicator: {end_indicator.decode(encoding='ascii', errors='backslashreplace')}")
if (id == self.__DEBUG_ID_FSD_READ):
self.__debug_process_fsd_read(file, id, data)
self.__read_long(align)
end_indicator = self.__read_long(4)
if (end_indicator != b"CMPH"):
print(f"Got unknown end indicator: {end_indicator.decode(encoding='ascii', errors='backslashreplace')}")
else: else:
print(f"Got unknown start indicator: {start_indicator.decode(encoding='ascii', errors='backslashreplace')}") print(f"Got unknown start indicator: {start_indicator.decode(encoding='ascii', errors='backslashreplace')}")
@ -446,14 +480,15 @@ if __name__ == "__main__":
parser.add_argument("-e", metavar="save_path", default=None, required=False, help="path to save file") parser.add_argument("-e", metavar="save_path", default=None, required=False, help="path to save file")
parser.add_argument("-i", metavar="ddipl_path", default=None, required=False, help="path to DDIPL file") parser.add_argument("-i", metavar="ddipl_path", default=None, required=False, help="path to DDIPL file")
parser.add_argument("-q", default=None, action="store_true", required=False, help="start debug server") parser.add_argument("-q", default=None, action="store_true", required=False, help="start debug server")
parser.add_argument("-f", metavar="sd_path", default=None, required=False, help="path to disk or file for fake SD card emulation")
parser.add_argument("rom", metavar="rom_path", default=None, help="path to ROM file", nargs="?") parser.add_argument("rom", metavar="rom_path", default=None, help="path to ROM file", nargs="?")
args = parser.parse_args()
if (len(sys.argv) <= 1): if (len(sys.argv) <= 1):
parser.print_help() parser.print_help()
parser.exit() parser.exit()
args = parser.parse_args()
try: try:
sc64 = SC64() sc64 = SC64()
@ -469,6 +504,7 @@ if __name__ == "__main__":
dd_ipl_file = args.i dd_ipl_file = args.i
rom_file = args.rom rom_file = args.rom
debug_server = args.q debug_server = args.q
sd_file = args.f
firmware_backup_file = "sc64firmware.bin.bak" firmware_backup_file = "sc64firmware.bin.bak"
@ -486,19 +522,24 @@ if __name__ == "__main__":
os.remove(firmware_backup_file) os.remove(firmware_backup_file)
if (not is_read): if (not is_read):
print(f"Setting boot mode to [{sc64.get_boot_mode_label(boot_mode)}]") if (boot_mode != 1):
print(f"Setting boot mode to [{sc64.get_boot_mode_label(boot_mode)}]")
sc64.set_boot_mode(boot_mode) sc64.set_boot_mode(boot_mode)
print(f"Setting save type to [{sc64.get_save_type_label(save_type)}]") if (save_type):
print(f"Setting save type to [{sc64.get_save_type_label(save_type)}]")
sc64.set_save_type(save_type) sc64.set_save_type(save_type)
print(f"Setting TV type to [{sc64.get_tv_type_label(tv_type)}]") if (tv_type != 3):
print(f"Setting TV type to [{sc64.get_tv_type_label(tv_type)}]")
sc64.set_tv_type(tv_type) sc64.set_tv_type(tv_type)
print(f"Setting CIC seed to [{hex(cic_seed) if cic_seed != 0xFFFF else 'Unknown'}]") if (cic_seed != 0xFFFF):
print(f"Setting CIC seed to [{hex(cic_seed) if cic_seed != 0xFFFF else 'Unknown'}]")
sc64.set_cic_seed(cic_seed) sc64.set_cic_seed(cic_seed)
print(f"Setting 64DD emulation to [{'Enabled' if dd_enable else 'Disabled'}]") if (dd_enable):
print(f"Setting 64DD emulation to [{'Enabled' if dd_enable else 'Disabled'}]")
sc64.set_dd_enable(dd_enable) sc64.set_dd_enable(dd_enable)
if (rom_file): if (rom_file):
@ -523,7 +564,7 @@ if __name__ == "__main__":
sc64.upload_save(save_file) sc64.upload_save(save_file)
if (debug_server): if (debug_server):
sc64.debug_loop() sc64.debug_loop(sd_file)
except SC64Exception as e: except SC64Exception as e:
print(f"Error: {e}") print(f"Error: {e}")

View File

@ -1,8 +1,3 @@
#define STR(x) #x
#define XSTR(s) STR(s)
#define VERSION XSTR(__SC64_VERSION)
.section .text.reset_handler .section .text.reset_handler
reset_handler: reset_handler:
.global reset_handler .global reset_handler
@ -14,16 +9,6 @@ reset_handler:
la sp, __stack_pointer$ la sp, __stack_pointer$
la ra, init_text
jalr zero, 0(ra)
.org 0x20, 0x00
header_text_info:
.global header_text_info
.ascii "SummerGovernor64 "
.ascii VERSION
.org 0x40, 0x00
init_text: init_text:
la a0, _sitext la a0, _sitext
la a1, _stext la a1, _stext