From 9aa317da37ffca6abb0b337ca4592bf78f29e7d4 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:37:10 +0000 Subject: [PATCH] BS2Mach: 21/29 functions (gpt-6.1-sol low) (worker 115f25f2) --- libs/RVL_SDK/include/revolution/dvd.h | 4 + src/BS2/BS2Mach.c | 2068 +++++++++++++++++++++-- tools/decomp-assist/BS2Mach.attempts.md | 171 ++ 3 files changed, 2137 insertions(+), 106 deletions(-) create mode 100644 tools/decomp-assist/BS2Mach.attempts.md diff --git a/libs/RVL_SDK/include/revolution/dvd.h b/libs/RVL_SDK/include/revolution/dvd.h index 86a0dcbe..c08195bc 100644 --- a/libs/RVL_SDK/include/revolution/dvd.h +++ b/libs/RVL_SDK/include/revolution/dvd.h @@ -150,7 +150,11 @@ typedef struct DVDErrorInfo { void DVDInit(); BOOL DVDReadAbsAsyncPrio(DVDCommandBlock* block, void* addr, s32 length, u32 offset, DVDCommandCallback callback, s32 prio); +#ifdef BS2_MACH_FIVE_ARG_READ +BOOL DVDReadAbsAsyncForBS(DVDCommandBlock* block, void* addr, s32 length, u32 offset, DVDCommandCallback callback); +#else BOOL DVDReadAbsAsyncForBS(DVDCommandBlock* block, void* addr, s32 length, u32 offset, DVDCommandCallback callback, s32 prio); +#endif BOOL DVDReadDiskID(DVDCommandBlock* block, DVDDiskID* diskID, DVDCommandCallback callback); BOOL DVDCompareDiskID(const DVDDiskID* id1, const DVDDiskID* id2); diff --git a/src/BS2/BS2Mach.c b/src/BS2/BS2Mach.c index 3b0621e6..02b1b400 100644 --- a/src/BS2/BS2Mach.c +++ b/src/BS2/BS2Mach.c @@ -1,4 +1,6 @@ +#define BS2_MACH_FIVE_ARG_READ #include "BS2/BS2.h" +#include "BS2/BS2BringUp.h" #include "BS2/BS2Update.h" #include "config.h" @@ -8,19 +10,26 @@ #include #include +#include +#include +#include +#include +#include #include +BOOL BS2IsValidDisc(void); + typedef struct AppLoaderHeader { - char date[16]; // 0x00 - u32 entryPoint; // 0x10 - u32 length; // 0x14 - u32 trailerSize; // 0x18 + char date[16]; // 0x00 + u32 entryPoint; // 0x10 + u32 length; // 0x14 + u32 trailerSize; // 0x18 u8 pad_0x1C[4]; } AppLoaderHeader; u8 TicketViewsBuf[OSRoundUp32B(sizeof(ESTicketView) * 64)] ALIGN32; -ESTicketView* lbl_81696578 = (ESTicketView*)TicketViewsBuf; +ESTicketView *lbl_81696578 = (ESTicketView *)TicketViewsBuf; DVDDiskID lbl_810ADF60 ALIGN32; OSBootInfo2 bi2 ALIGN32; AppLoaderHeader AppLoaderHdr ALIGN32; @@ -75,10 +84,10 @@ u32 lbl_81698AA8 = 0; u32 lbl_81698AAC = 0; u32 lbl_81698AB0 = 0; u32 lbl_81698AB4 = 0; -u32 lbl_81698AB8 = 0; -u32 lbl_81698ABC = 0; +u8 *lbl_81698AB8 = NULL; +NANDFileInfo *lbl_81698ABC = NULL; u32 lbl_81698AC0 = 0; -u32 lbl_81698AC4 = 0; +NANDCallback lbl_81698AC4 = NULL; u32 lbl_81698AC8 = 0; u32 lbl_81698ACC = 0; u32 lbl_81698AD0 = 0; @@ -86,12 +95,65 @@ u32 lbl_81698AD4 = 0; u32 lbl_81698AD8 = 0; vu32 lbl_81698ADC = 0; vu32 lbl_81698AE0 = 0; -u32* lbl_81698AE4 = 0; +u32 *lbl_81698AE4 = 0; u32 lbl_81698AE8 = 0; u32 lbl_81698AEC = 0; u32 lbl_81698AF0 = 0; -void BS2Report(const char* msg, ...) { +#define DvdReadPending lbl_81698A0C +#define BannerAllocation lbl_81698A10 +#define BannerBuffer lbl_81698A14 +#define BannerAvailable lbl_81698A18 +#define Allocator lbl_81698A1C +#define RestartRequested lbl_81698A24 +#define PartitionOpen lbl_81698A28 +#define CacheSeekComplete lbl_81698A2C +#define LoadingTitle lbl_81698A30 +#define CacheFailed lbl_81698A44 +#define RegionValid lbl_81698A48 +#define NandPending lbl_81698A4C +#define CancelNand lbl_81698A50 +#define LowReadResult lbl_81698A54 +#define CacheCommandComplete lbl_81698A58 +#define AudioBufferUnconfigured lbl_81698A5C +#define ResetTime lbl_81698A60 +#define SpinupDeadline lbl_81698A68 +#define CoverPollTime lbl_81698A70 +#define DriveWasReset lbl_81698A78 +#define TitleTicketView lbl_81698A7C +#define CurrentTmd lbl_81698A80 +#define TitleCode lbl_81698A84 +#define RequiredIosHigh lbl_81698A88 +#define RequiredIosLow lbl_81698A8C +#define GamePartition lbl_81698A90 +#define UpdatePartition lbl_81698A94 +#define PartitionCursor lbl_81698A98 +#define DataToc lbl_81698A9C +#define GameToc lbl_81698AA0 +#define CoverOpenTimeHigh lbl_81698AA8 +#define CoverOpenTimeLow lbl_81698AAC +#define NandTransferred lbl_81698AB0 +#define NandLength lbl_81698AB4 +#define NandBuffer lbl_81698AB8 +#define NandFile lbl_81698ABC +#define NandOperation lbl_81698AC0 +#define NandCompletion lbl_81698AC4 +#define LoaderOffset lbl_81698AC8 +#define LoaderLength lbl_81698ACC +#define LoaderAddress lbl_81698AD0 +#define CacheLength lbl_81698AD4 +#define BannerLength lbl_81698AD8 +#define DvdTransferLength lbl_81698ADC +#define DvdTransferred lbl_81698AE0 +#define DvdProgress lbl_81698AE4 +#define LoaderClose lbl_81698AE8 +#define LoaderMain lbl_81698AEC +#define LoaderInit lbl_81698AF0 +#define CoverBlock lbl_8108BF60 +#define UpdateDiskID lbl_810ADF60 +#define TicketViews lbl_81696578 + +void BS2Report(const char *msg, ...) { #ifdef ENABLE_BS2_REPORT va_list marker; va_start(marker, msg); @@ -100,26 +162,26 @@ void BS2Report(const char* msg, ...) { #endif } -void BS2NANDCallback(s32 result) { - if (lbl_81698A4C) { - lbl_81698A4C = 0; +void BS2NANDCallback(s32 result, NANDCommandBlock *block) { + if (NandPending) { + NandPending = 0; } if (result < NAND_RESULT_OK) { OSReport("Failed to access boot cache file\n"); BS2BootFromCache = FALSE; BS2BootCaching = FALSE; - lbl_81698A44 = 1; + CacheFailed = 1; State = BS2_STT_2; } } -void BS2DVDCallback(s32 result, DVDCommandBlock* block) { - if (lbl_81698A0C) { - lbl_81698A0C = 0; - lbl_81698AE0 += lbl_81698ADC; +void BS2DVDCallback(s32 result, DVDCommandBlock *block) { + if (DvdReadPending) { + DvdReadPending = 0; + DvdTransferred += DvdTransferLength; if (result < DVD_RESULT_OK) { - *lbl_81698AE4 = 0; + *DvdProgress = 0; } } @@ -127,7 +189,8 @@ void BS2DVDCallback(s32 result, DVDCommandBlock* block) { State = BS2_STT_NO_DISK; } - if ((State == BS2_STT_RVL_GAME || State == BS2_STT_GC_GAME || State == BS2_STT_UPDATE_DISK || State == BS2_STT_DATA_DISK) && result == 1) { + if ((State == BS2_STT_RVL_GAME || State == BS2_STT_GC_GAME || State == BS2_STT_UPDATE_DISK || State == BS2_STT_DATA_DISK) && + result == 1) { BS2CancelUpdate(); State = BS2_STT_NO_DISK; } @@ -171,7 +234,7 @@ void BS2RestartStateMachine() { BS2BootCaching = TRUE; } - lbl_81698A24 = 1; + RestartRequested = 1; OSRestoreInterrupts(old); } @@ -181,27 +244,27 @@ void BS2AbortStateMachine() { BS2Report("[BS2AbortStateMachine]\n"); - lbl_81698A24 = 0; + RestartRequested = 0; if (State == BS2_STT_64) { OSRestoreInterrupts(enabled); - } else if (State == BS2_STT_BEGIN || State == BS2_STT_1 || State == BS2_STT_2 || State == BS2_STT_4 || State == BS2_STT_6 || State == BS2_STT_8 || - State == BS2_STT_10) { + } else if (State == BS2_STT_BEGIN || State == BS2_STT_1 || State == BS2_STT_2 || State == BS2_STT_4 || State == BS2_STT_6 || + State == BS2_STT_8 || State == BS2_STT_10) { State = BS2_STT_64; OSRestoreInterrupts(enabled); - } else if (State == BS2_STT_NO_DISK || State == BS2_STT_COVER_OPEN || State == BS2_STT_55 || State == BS2_STT_WRONG_DISK || State == BS2_STT_66 || - State == BS2_STT_67 || State == BS2_STT_68 || State == BS2_STT_FATAL_ERROR || State == BS2_STT_UPDATE_FAILED || - State == BS2_STT_DIRTY_DISK) { + } else if (State == BS2_STT_NO_DISK || State == BS2_STT_COVER_OPEN || State == BS2_STT_55 || State == BS2_STT_WRONG_DISK || + State == BS2_STT_66 || State == BS2_STT_67 || State == BS2_STT_68 || State == BS2_STT_FATAL_ERROR || + State == BS2_STT_UPDATE_FAILED || State == BS2_STT_DIRTY_DISK) { OSRestoreInterrupts(enabled); } else { - *lbl_81698AE4 = 0; - lbl_81698AE0 = 0; - lbl_81698ADC = 0; + *DvdProgress = 0; + DvdTransferred = 0; + DvdTransferLength = 0; if (State == BS2_STT_3 || State == BS2_STT_5 || State == BS2_STT_7 || State == BS2_STT_9) { State = BS2_STT_62; } else { - if (lbl_81698A4C != 0) { - lbl_81698A50 = 1; + if (NandPending != 0) { + CancelNand = 1; } State = BS2_STT_60; DVDCancelAsync(&Block, NULL); @@ -211,32 +274,35 @@ void BS2AbortStateMachine() { } } -void BS2SetBannerBuffer(void* pBanner, u32 bannerSize) { - lbl_81698A14 = (u32)pBanner; - lbl_81698AD8 = bannerSize; +void BS2SetBannerBuffer(void *pBanner, u32 bannerSize) { + BannerBuffer = (u32)pBanner; + BannerLength = bannerSize; } -void BS2SetMemAllocator(MEMAllocator* allocator) { - lbl_81698A1C = (u32)allocator; +void BS2SetMemAllocator(MEMAllocator *allocator) { Allocator = (u32)allocator; } + +BOOL BS2IsBannerAvailable() { return BannerAvailable; } + +void *BS2GetBannerBufferAddr() { return (void *)BannerBuffer; } + +u32 BS2GetBannerBufferLength() { return BannerLength; } + +BOOL BS2IsDiagDisc() { return (u8)(*(u8 *)OSPhysicalToCached(OS_ADDR_BOOT_INFO) - 0x30U) <= 1; } + +extern vu32 BS2VideoMode; +extern vu32 __DVDLayoutFormat; + +void Run(u32 entryPoint, void *start, u32 blockCount, u32 argument) { + u8 *block = start; + do { + DCZeroRange(block, 32); + DCFlushRange(block, 32); + block += 32; + } while (--blockCount != 0); + ((void (*)(u32))entryPoint)(argument); } -BOOL BS2IsBannerAvailable() { - return lbl_81698A18; -} - -void* BS2GetBannerBufferAddr() { - return (void*)lbl_81698A14; -} - -u32 BS2GetBannerBufferLength() { - return lbl_81698AD8; -} - -BOOL BS2IsDiagDisc() { - return (u8)(*(u8*)OSPhysicalToCached(OS_ADDR_BOOT_INFO) - 0x30U) <= 1; -} - -BOOL BS2GetLockedTitles(ESTitleId* pTitleIds, u32* count) { +BOOL BS2GetLockedTitles(ESTitleId *pTitleIds, u32 *count) { u32 i; u32 titleMask; u32 titleCount; @@ -250,26 +316,26 @@ BOOL BS2GetLockedTitles(ESTitleId* pTitleIds, u32* count) { } *count = 0; - lbl_81698A98 = (u32)PartitionInfoBuf; - for (i = 0; i < **(u32**)&lbl_81698AA0; i++) { - BS2Report("gamePartition ... 0x%08X\n", *(u32*)lbl_81698A98); - BS2Report("type ... 0x%08X\n", *(u32*)(lbl_81698A98 + 4)); - if (*(u32*)(lbl_81698A98 + 4) & 0xFF000000) { + PartitionCursor = (u32)PartitionInfoBuf; + for (i = 0; i < **(u32 **)&GameToc; i++) { + BS2Report("gamePartition ... 0x%08X\n", (u32)((DVDPartitionInfo *)PartitionCursor)->partition); + BS2Report("type ... 0x%08X\n", ((DVDPartitionInfo *)PartitionCursor)->partitionType); + if (((DVDPartitionInfo *)PartitionCursor)->partitionType & 0xFF000000) { BS2Report(" count++\n"); (*count)++; } - lbl_81698A98 += 8; + PartitionCursor += 8; } - lbl_81698A98 = (u32)PartitionInfoBuf + 0x20; - for (i = 0; i < **(u32**)&lbl_81698A9C; i++) { - BS2Report("gamePartition ... 0x%08X\n", *(u32*)lbl_81698A98); - BS2Report("type ... 0x%08X\n", *(u32*)(lbl_81698A98 + 4)); - if (*(u32*)(lbl_81698A98 + 4) & 0xFF000000) { + PartitionCursor = (u32)PartitionInfoBuf + 0x20; + for (i = 0; i < **(u32 **)&DataToc; i++) { + BS2Report("gamePartition ... 0x%08X\n", (u32)((DVDPartitionInfo *)PartitionCursor)->partition); + BS2Report("type ... 0x%08X\n", ((DVDPartitionInfo *)PartitionCursor)->partitionType); + if (((DVDPartitionInfo *)PartitionCursor)->partitionType & 0xFF000000) { BS2Report(" count++\n"); (*count)++; } - lbl_81698A98 += 8; + PartitionCursor += 8; } return TRUE; @@ -277,32 +343,32 @@ BOOL BS2GetLockedTitles(ESTitleId* pTitleIds, u32* count) { getLockedTitles: titleCount = *count; if (titleCount != 0) { - lbl_81698A98 = (u32)PartitionInfoBuf; + PartitionCursor = (u32)PartitionInfoBuf; titleMask = (u32)-1; - for (i = 0; i < **(u32**)&lbl_81698AA0; i++) { + for (i = 0; i < **(u32 **)&GameToc; i++) { if (titleCount == 0) { return TRUE; } - if (*(u32*)(lbl_81698A98 + 4) & 0xFF000000) { - *pTitleIds = ((ESTitleId)0x00010000 << 32) | (*(u32*)(lbl_81698A98 + 4) & titleMask); + if (((DVDPartitionInfo *)PartitionCursor)->partitionType & 0xFF000000) { + *pTitleIds = ((ESTitleId)0x00010000 << 32) | (((DVDPartitionInfo *)PartitionCursor)->partitionType & titleMask); titleCount--; pTitleIds++; } - lbl_81698A98 += 8; + PartitionCursor += 8; } - lbl_81698A98 = (u32)PartitionInfoBuf + 0x20; + PartitionCursor = (u32)PartitionInfoBuf + 0x20; titleMask = (u32)-1; - for (i = 0; i < **(u32**)&lbl_81698A9C; i++) { + for (i = 0; i < **(u32 **)&DataToc; i++) { if (titleCount == 0) { return TRUE; } - if (*(u32*)(lbl_81698A98 + 4) & 0xFF000000) { - *pTitleIds = ((ESTitleId)0x00010000 << 32) | (*(u32*)(lbl_81698A98 + 4) & titleMask); + if (((DVDPartitionInfo *)PartitionCursor)->partitionType & 0xFF000000) { + *pTitleIds = ((ESTitleId)0x00010000 << 32) | (((DVDPartitionInfo *)PartitionCursor)->partitionType & titleMask); titleCount--; pTitleIds++; } - lbl_81698A98 += 8; + PartitionCursor += 8; } } @@ -310,35 +376,35 @@ getLockedTitles: } BOOL BS2IsTitleAvailable(ESTitleId titleId) { - u32* count; + u32 *count; u32 i; if (State != BS2_STT_DATA_DISK && State != BS2_STT_RVL_GAME) { return FALSE; } - lbl_81698A98 = (u32)PartitionInfoBuf; - count = *(u32**)&lbl_81698AA0; + PartitionCursor = (u32)PartitionInfoBuf; + count = *(u32 **)&GameToc; for (i = 0; i < *count; i++) { - if (*(u32*)(lbl_81698A98 + 4) == (u32)titleId) { + if (((DVDPartitionInfo *)PartitionCursor)->partitionType == (u32)titleId) { return TRUE; } - lbl_81698A98 += 8; + PartitionCursor += 8; } - lbl_81698A98 = (u32)PartitionInfoBuf + 0x20; - count = *(u32**)&lbl_81698A9C; + PartitionCursor = (u32)PartitionInfoBuf + 0x20; + count = *(u32 **)&DataToc; for (i = 0; i < *count; i++) { - if (*(u32*)(lbl_81698A98 + 4) == (u32)titleId) { + if (((DVDPartitionInfo *)PartitionCursor)->partitionType == (u32)titleId) { return TRUE; } - lbl_81698A98 += 8; + PartitionCursor += 8; } return FALSE; } -s32 BS2GetTicketFromNand(ESTitleId titleId, ESTicketView* pTicketView) { +s32 BS2GetTicketFromNand(ESTitleId titleId, ESTicketView *pTicketView) { s32 ret; u32 ticketCount; s32 index; @@ -357,40 +423,40 @@ s32 BS2GetTicketFromNand(ESTitleId titleId, ESTicketView* pTicketView) { return -1; } - ret = ES_GetTicketViews(titleId, lbl_81696578, &ticketCount); + ret = ES_GetTicketViews(titleId, TicketViews, &ticketCount); if (ret != 0) { OSReport("ES_GetTicketViews%d failed: %d\n", 2, ret); return ret; } BS2Report("Found %d tickets in NAND\n", ticketCount); - index = __OSGetValidTicketIndex(lbl_81696578, ticketCount); + index = __OSGetValidTicketIndex(TicketViews, ticketCount); if (index < 0 || (u32)index > ticketCount - 1) { OSReport("Failed to get best ticket.\n"); return -1; } - memcpy(pTicketView, &lbl_81696578[index], sizeof(ESTicketView)); + memcpy(pTicketView, &TicketViews[index], sizeof(ESTicketView)); DCStoreRange(pTicketView, sizeof(ESTicketView)); return ticketCount; } -BOOL BS2StartLoadingTitle(ESTitleId titleId, ESTicketView* pTicketView) { - u32* gamePartitionCount; - u32* dataPartitionCount; +BOOL BS2StartLoadingTitle(ESTitleId titleId, ESTicketView *pTicketView) { + u32 *gamePartitionCount; + u32 *dataPartitionCount; u32 i; if (State != BS2_STT_DATA_DISK && State != BS2_STT_RVL_GAME) { return FALSE; } - lbl_81698A30 = 1; - lbl_81698A7C = (u32)pTicketView; - lbl_81698A98 = (u32)PartitionInfoBuf; - gamePartitionCount = *(u32**)&lbl_81698AA0; + LoadingTitle = 1; + TitleTicketView = (u32)pTicketView; + PartitionCursor = (u32)PartitionInfoBuf; + gamePartitionCount = *(u32 **)&GameToc; for (i = 0; i < *gamePartitionCount; i++) { - if (*(u32*)(lbl_81698A98 + 4) == (u32)titleId) { - lbl_81698A90 = lbl_81698A98; + if (((DVDPartitionInfo *)PartitionCursor)->partitionType == (u32)titleId) { + GamePartition = PartitionCursor; if (BS2BootFromCache) { State = BS2_STT_8; } else { @@ -400,14 +466,14 @@ BOOL BS2StartLoadingTitle(ESTitleId titleId, ESTicketView* pTicketView) { BS2BootCaching = FALSE; return TRUE; } - lbl_81698A98 += 8; + PartitionCursor += 8; } - lbl_81698A98 = (u32)PartitionInfoBuf + 0x20; - dataPartitionCount = *(u32**)&lbl_81698A9C; + PartitionCursor = (u32)PartitionInfoBuf + 0x20; + dataPartitionCount = *(u32 **)&DataToc; for (i = 0; i < *dataPartitionCount; i++) { - if (*(u32*)(lbl_81698A98 + 4) == (u32)titleId) { - lbl_81698A90 = lbl_81698A98; + if (((DVDPartitionInfo *)PartitionCursor)->partitionType == (u32)titleId) { + GamePartition = PartitionCursor; if (BS2BootFromCache) { State = BS2_STT_8; } else { @@ -417,12 +483,1802 @@ BOOL BS2StartLoadingTitle(ESTitleId titleId, ESTicketView* pTicketView) { BS2BootCaching = FALSE; return TRUE; } - lbl_81698A98 += 8; + PartitionCursor += 8; } return FALSE; } -void callback(s32 result) { - lbl_81698A54 = result; +void callback(s32 result) { LowReadResult = result; } + +ESError BS2ESGetTicketViews(IOSFd *descriptor, ESTitleId titleId, ESTicketView *views, u32 *count) { + struct { + ESTitleId title[4]; + u32 count[56]; + } work ALIGN32; + IOSIoVector vectors[4] ALIGN32; + ESError result; + IOSIoVector *request = vectors; + ESTitleId *title = work.title; + u32 *ticketCount = work.count; + + if (*descriptor < 0 || !count) { + return ES_ERR_INVALID; + } + if ((u32)views % 32 != 0) { + return ES_ERR_INVALID; + } + *title = titleId; + if (!views) { + request[0].base = (u8 *)title; + request[0].length = sizeof(*title); + request[1].base = (u8 *)ticketCount; + request[1].length = sizeof(*ticketCount); + result = IOS_Ioctlv(*descriptor, 0x12, 1, 1, request); + if (result == 0) { + *count = *ticketCount; + } + return result; + } + if (*count == 0) { + return ES_ERR_INVALID; + } + *ticketCount = *count; + request[0].base = (u8 *)title; + request[0].length = sizeof(*title); + request[1].base = (u8 *)ticketCount; + request[1].length = sizeof(*ticketCount); + request[2].base = (u8 *)views; + request[2].length = *count * sizeof(*views); + return IOS_Ioctlv(*descriptor, 0x13, 2, 1, request); +} +void BS2Reboot(void) { + ESTicketView ticket ALIGN32; + struct { + ESTitleId title[32]; + } launchWork ALIGN32; + OSStateFlags flags ALIGN32; + IOSIoVector vectors[4] ALIGN32; + IOSFd descriptor; + u32 ticketCount; + s32 initErr; + s32 err; + + descriptor = -1; + initErr = ISFS_OpenLibEx(); + if (initErr != ISFS_ERROR_OK) { + OSReport("ISFS_OpenLibEx failed: %d\n", initErr); + } else { + BS2Report("\nISFS_OpenLibEx successful\n"); + __OSReadStateFlags(&flags); + flags.lastAppType = 0; + flags.shutdownType = OS_STATE_FLAGS_SHUTDOWN_RETURN_MENU; + flags.discState = OS_STATE_FLAGS_DISC_CHANGED; + __OSWriteStateFlags(&flags); + + err = 0; + descriptor = IOS_Open("/dev/es", 0); + if (descriptor < 0) { + err = descriptor; + } + if (err != 0) { + OSReport("ES_InitLib failed: %d\n", err); + } else { + BS2Report("ES_InitLib: %d\n", err); + { + s32 result = BS2ESGetTicketViews(&descriptor, SYSMENU_TITLE_ID, NULL, &ticketCount); + if (result != 0) { + OSReport("ES_GetTicketViews failed: %d\n", result); + } else { + BS2Report("ES_GetTicketViews: %d\n", result); + if (ticketCount != 1) { + OSReport("Error: Should only have 1 ticket for System Menu\n"); + } + { + s32 result = BS2ESGetTicketViews(&descriptor, SYSMENU_TITLE_ID, &ticket, &ticketCount); + if (result != 0) { + OSReport("ES_GetTicketViews failed: %d\n", result); + } else { + BS2Report("ES_GetTicketViews: %d\n", result); + { + s32 launchResult; + IOSIoVector *request = vectors; + ESTitleId *title = launchWork.title; + if (descriptor < 0) { + launchResult = -0x3f9; + } else if ((u32)&ticket % 32 != 0) { + launchResult = -0x3f9; + } else { + *title = SYSMENU_TITLE_ID; + request[0].base = (u8 *)title; + request[0].length = sizeof(*title); + request[1].base = (u8 *)&ticket; + request[1].length = sizeof(ESTicketView); + launchResult = IOS_IoctlvReboot(descriptor, 8, 2, 0, request); + } + if (launchResult != 0) { + OSReport("ES_LaunchTitle failed: %d\n", launchResult); + } else { + BS2Report("ES_LaunchTitle: %d\n", launchResult); + while (TRUE) { + } + } + } + } + } + } + } + } + } +} + +void BS2StartGame() { + u32 runResult; + u8 *base; + s32 ret; + u32 oldBytes; + u32 driveError; + s32 status; + ESTicketView *ticketViews; + u32 titleType; + u32 titleCode; + u32 ticketCount; + BOOL oldInterrupts; + OSStateFlags stateFlags; + u32 (*entry)(void); + + StartingGame = TRUE; + while (DVDGetCommandBlockStatus(&CoverBlock) != DVD_STATE_IDLE) { + } + + BS2Report("BS2StartGame(1)\n"); + BS2Report("DVD transferred bytes:%d\n", DvdTransferred); + + NandPending = 1; + { + s32 closeResult; + + closeResult = NANDCloseAsync(&BS2CacheFileInfo, BS2NANDCallback, &BS2NandBlock); + if (closeResult == NAND_RESULT_OK) { + while (NandPending != 0) { + } + if (CacheFailed != 0) { + NANDDelete("/title/00000001/00000002/data/cache.dat"); + } + } else { + OSReport("Error occurred when close cache.dat (%d)\n", closeResult); + } + } + + while (!PADSync()) { + } + + base = (u8 *)0x80000000; + *(u32 *)0x80003180 = *(u32 *)base; + *(u8 *)0x80003184 = 0x80; + *(u8 *)0x80003187 = PartitionParams.numTmdBytes ? 0x80 : 0; + *(u32 *)0x80003194 = ((DVDPartitionInfo *)GamePartition)->partitionType; + *(u32 *)0x80003198 = (u32)((DVDPartitionInfo *)GamePartition)->partition; + DCFlushRange((void *)0x80003100, 0x100); + + __OSUnRegisterStateEvent(); + __OSReadStateFlags(&stateFlags); + stateFlags.lastAppType = 0x81; + if (CacheFailed == 0) { + stateFlags.lastAppType |= 0x40; + } + stateFlags.shutdownType = OS_STATE_FLAGS_SHUTDOWN_BAD; + stateFlags.discState = OS_STATE_FLAGS_DISC_IN; + __OSWriteStateFlags(&stateFlags); + __OSClearRTCFlags(); + + titleType = RequiredIosHigh; + titleCode = RequiredIosLow; + ticketCount = 1; + ticketViews = TicketViews; + if ((titleCode | titleType) == 0) { + titleCode = 3; + titleType = 1; + } + + ret = ES_InitLib(); + if (ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xAC3, "\nFailed to boot app"); + } + BS2Report(" sysVersion = %016llx\n", ((ESTitleId)titleType << 32) | titleCode); + ret = ES_GetTicketViews(((ESTitleId)titleType << 32) | titleCode, NULL, &ticketCount); + if (ticketCount != 1 || ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xACD, "\nFailed to boot app"); + } + ret = ES_GetTicketViews(((ESTitleId)titleType << 32) | titleCode, ticketViews, &ticketCount); + BS2Report("GetTicketViews: rc = %d\n", ret); + if (ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xAD7, "\nFailed to boot app"); + } + + DVDLowFinalize(); + oldBytes = *(u32 *)0x8000311C; + DCStoreRange((void *)0x80003100, 0x100); + ret = ES_LaunchTitle(((ESTitleId)titleType << 32) | titleCode, ticketViews); + BS2Report("LaunchTitle: rc = %d\n", ret); + if (ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xAF3, "\nFailed to boot app"); + } + + DCInvalidateRange((void *)0x80003100, 0x100); + __OSInitIPCBuffer(); + IPCReInit(); + IPCCltReInit(); + BS2Report("IPC driver is re-initialized\n"); + if (oldBytes < *(u32 *)0x8000311C) { + *(u32 *)0x80003120 = oldBytes - (*(u32 *)0x8000311C - *(u32 *)0x80003120); + *(u32 *)0x80003128 = oldBytes - (*(u32 *)0x8000311C - *(u32 *)0x80003128); + *(u32 *)0x80003130 = oldBytes - (*(u32 *)0x8000311C - *(u32 *)0x80003130); + *(u32 *)0x80003134 = oldBytes - (*(u32 *)0x8000311C - *(u32 *)0x80003134); + *(u32 *)0x8000311C = oldBytes; + } + + DVDLowInit(); + BS2Report("DVDLowInit done\n"); + + LowReadResult = 0; + DVDLowReadDiskID(&DiskID, (DVDLowCallback)callback); + while (LowReadResult == 0) { + BOOL enabled = OSDisableInterrupts(); + OSRestoreInterrupts(enabled); + } + + status = LowReadResult; + if (status != 2) { + if ((status >= 2) || (status < 1)) { + goto disk_fatal; + } else { + goto disk_done; + } + } else { + OSReport("\nDisk error(%d) has occurred", LowReadResult); + LowReadResult = 0; + DVDLowRequestError((DVDLowCallback)callback); + while (LowReadResult == 0) { + BOOL enabled = OSDisableInterrupts(); + OSRestoreInterrupts(enabled); + } + driveError = DVDLowGetImmBufferReg() & 0xFF000000; + if (driveError == 0x01000000 || (driveError = DVDLowGetImmBufferReg() & 0xFF000000) == 0x03000000) { + BS2Reboot(); + } + if (DvdTransferred == 0 && (driveError = DVDLowGetImmBufferReg() & 0xFF000000) == 0x04000000) { + BS2Reboot(); + } + goto disk_fatal; + } + +disk_fatal: + DVDSetAutoFatalMessaging(TRUE); + __DVDPrintFatalMessage(); + +disk_done: + BS2Report("DVDLowReadDiskID done\n"); + ret = strncmp((char *)base, (char *)&DiskID, 4); + if (ret != 0) { + OSReport("\nDisk has changed!"); + BS2Reboot(); + } + + BS2Report("PartitionParams.numTmdBytes = %d\n", PartitionParams.numTmdBytes); + LowReadResult = 0; + if (PartitionParams.numTmdBytes != 0) { + DVDLowOpenPartitionWithTmdAndTicketView((u32)((DVDPartitionInfo *)GamePartition)->partition, &PartitionParams.ticketView, + PartitionParams.numTmdBytes, &PartitionParams.tmd, PartitionParams.numCertBytes, + PartitionParams.certificates, (DVDLowCallback)callback); + } else { + DVDLowOpenPartition((u32)((DVDPartitionInfo *)GamePartition)->partition, NULL, 0, NULL, &PartitionParams.tmd, + (DVDLowCallback)callback); + } + while (LowReadResult == 0) { + BOOL enabled = OSDisableInterrupts(); + OSRestoreInterrupts(enabled); + } + + status = LowReadResult; + if (status != 2) { + if (status < 2) { + if (status >= 1) { + goto partition_done; + } + } else if (status == 0x40) { + goto partition_eticket; + } + goto partition_fatal; + } else { + OSReport("\nDisk error(%d) has occurred", LowReadResult); + LowReadResult = 0; + DVDLowRequestError((DVDLowCallback)callback); + while (LowReadResult == 0) { + BOOL enabled = OSDisableInterrupts(); + OSRestoreInterrupts(enabled); + } + driveError = DVDLowGetImmBufferReg() & 0xFF000000; + if (driveError == 0x01000000 || (driveError = DVDLowGetImmBufferReg() & 0xFF000000) == 0x03000000) { + BS2Reboot(); + } + goto partition_fatal; + } + +partition_eticket: + OSReport("ETicket Error: %d\n", DVDLowGetLastEticketError()); + +partition_fatal: + DVDSetAutoFatalMessaging(TRUE); + __DVDPrintFatalMessage(); + +partition_done: + BS2Report("DVDLowOpenPartition done\n"); + if (*(u8 *)0x8000315D != 0x80) { + u32 diBits; + u32 diValue; + u32 *diAddr; + + diAddr = (u32 *)0xCC003024; + diBits = 2; + diBits |= 4; + diValue = *diAddr; + diValue |= 1; + *diAddr = diValue | diBits; + enableLegacyDI(); + } + oldInterrupts = OSDisableInterrupts(); + __OSStopAudioSystem(); + entry = (u32 (*)(void))LoaderClose; + runResult = entry(); + __OSFPRInit(); + ICFlashInvalidate(); + __sync(); + __isync(); + Run(runResult, (void *)0x81330000, 0x20000, 0); + (void)oldInterrupts; +} + +void BS2StartGCGame() { + static u8 gameCubeLanguages[] = {0, 0, 1, 2, 3, 4, 5}; + s32 ret; + u32 rtc; + u32 counterBias; + u32 seconds; + u32 timerFrequency; + u32 soundMode; + s8 productVideoMode; + u8 progressiveMode; + u8 language; + u8 euRgb60Mode; + u32 ticketCount; + ESTicketView *ticketViews; + OSSram *sram; + OSTime time; + + StartingGame = TRUE; + while (DVDGetCommandBlockStatus(&CoverBlock) != DVD_STATE_IDLE) { + } + + soundMode = SCGetSoundMode(); + if (soundMode == 2) { + soundMode = 1; + } else { + soundMode = SCGetSoundMode(); + } + OSSetSoundMode(soundMode); + + productVideoMode = SCGetProductVideoMode(); + if (productVideoMode != SC_PRODUCT_VIDEO_PAL) { + progressiveMode = SCGetProgressiveMode(); + OSSetProgressiveMode(progressiveMode == 1); + OSSetLanguage(0); + OSSetEuRgb60Mode(0); + } else { + language = SCGetLanguage(); + if (language > 6) { + OSSetLanguage(0); + } else { + language = SCGetLanguage(); + OSSetLanguage(gameCubeLanguages[language]); + } + euRgb60Mode = SCGetEuRgb60Mode(); + OSSetEuRgb60Mode(euRgb60Mode == 1); + } + + __OSGetRTC(&rtc); + counterBias = SCGetCounterBias(); + seconds = rtc + counterBias; + timerFrequency = OS_BUS_CLOCK >> 2; + time = (OSTime)timerFrequency * seconds; + __OSSetTime(time); + + sram = __OSLockSram(); + sram->displayOffsetH = SCGetDisplayOffsetH(); + sram->counterBias = SCGetCounterBias(); + sram->flags |= 0x20; + __OSUnlockSram(TRUE); + while (!__OSSyncSram()) { + } + + NandPending = 1; + ret = NANDCloseAsync(&BS2CacheFileInfo, BS2NANDCallback, &BS2NandBlock); + if (ret == NAND_RESULT_OK) { + while (NandPending != 0) { + } + if (CacheFailed != 0) { + NANDDelete("/title/00000001/00000002/data/cache.dat"); + } + } else { + OSReport("Error occurred when close cache.dat (%d)\n", ret); + } + + while (!PADSync()) { + } + + OSDisableInterrupts(); + __OSStopAudioSystem(); + OSEnableInterrupts(); + OSSetVideoMode(BS2VideoMode); + while (!__OSSyncSram()) { + } + + __OSUnRegisterStateEvent(); + { + OSStateFlags stateFlags; + __OSReadStateFlags(&stateFlags); + stateFlags.lastAppType = 0x82; + stateFlags.shutdownType = OS_STATE_FLAGS_SHUTDOWN_BAD; + stateFlags.discState = OS_STATE_FLAGS_DISC_CHANGED; + __OSWriteStateFlags(&stateFlags); + } + + __OSClearRTCFlags(); + *(u32 *)0xCC003024 |= 7; + ticketViews = TicketViews; + ticketCount = 1; + BS2Report(" sysVersion = %016llx\n", 0x0000000100000100ULL); + ret = ES_InitLib(); + if (ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xC40, "\nFailed to boot app"); + } + BS2Report(" sysVersion = %016llx\n", 0x0000000100000100ULL); + ret = ES_GetTicketViews(0x0000000100000100ULL, NULL, &ticketCount); + if (ticketCount != 1 || ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xC4A, "\nFailed to boot app"); + } + ret = ES_GetTicketViews(0x0000000100000100ULL, ticketViews, &ticketCount); + BS2Report("GetTicketViews: rc = %d\n", ret); + if (ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xC54, "\nFailed to boot app"); + } + ret = ES_LaunchTitle(0x0000000100000100ULL, ticketViews); + BS2Report("LaunchTitle: rc = %d\n", ret); + if (ret != ES_ERR_OK) { + OSReport("\nsecurity error(%d) has occurred", ret); + OSPanic("BS2Mach.c", 0xC5D, "\nFailed to boot app"); + } +} + +BOOL CheckDVDCommandStatus(DVDCommandBlock *block) { + if (State == 0x3A) { + return TRUE; + } + + if (State == 0x43) { + u32 coverRegister = DVDLowGetCoverRegister(); + u32 nextState = BS2_STT_68; + + if ((coverRegister & 1) != 0) { + nextState = BS2_STT_NO_DISK; + } + State = nextState; + } + + switch (block->state) { + case 0: + return TRUE; + case 3: + State = BS2_STT_COVER_CLOSED; + break; + case 4: + case 5: + if (State == 7 || State == 9 || State == 10) { + u64 systemTime = __OSGetSystemTime(); + CoverOpenTimeLow = (u32)systemTime; + CoverOpenTimeHigh = (u32)(systemTime >> 32); + State = BS2_STT_66; + } else { + State = BS2_STT_NO_DISK; + } + break; + case -1: + State = BS2_STT_FATAL_ERROR; + FatalErrorFlag = TRUE; + break; + case 11: + State = 0x3B; + break; + case 10: + if (DVDResetRequired()) { + State = BS2_STT_2; + } else if (PartitionOpen != 0) { + State = 0x3D; + } else { + State = 0x3F; + } + break; + case 6: + case 7: + State = BS2_STT_WRONG_DISK; + break; + } + + if (AbortFlag != 0 && (State == 0x34 || State == 0x35 || State == 0x37 || State == 0x38 || State == 0x44 || (u32)(State - 0x39) <= 2)) { + BS2BootFromCache = FALSE; + BS2BootCaching = TRUE; + State = BS2_STT_64; + } + + return FALSE; +} + +void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block); +void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block); +void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block); + +void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block) { + s32 ret; + + if (CancelNand != 0) { + CancelNand = 0; + NandCompletion(0, block); + } else if (result < 0) { + NandCompletion(result, block); + } else { + NandTransferred += result; + NandBuffer += result; + if (NandLength - NandTransferred > 0x40000) { + if (NandOperation == 1) { + BS2Report("NANDWriteAsync buf:0x%08X, length:0x%08X\n", NandBuffer, 0x40000); + ret = NANDWriteAsync(NandFile, (void *)NandBuffer, 0x40000, BS2NANDDivideCallback, block); + } else { + BS2Report("NANDReadAsync buf:0x%08X, length:0x%08X\n", NandBuffer, 0x40000); + ret = NANDReadAsync(NandFile, (void *)NandBuffer, 0x40000, BS2NANDDivideCallback, block); + } + if (ret < 0) { + NandCompletion(ret, block); + } + } else { + if (NandLength - NandTransferred != 0) { + if (NandOperation == 1) { + BS2Report("NANDWriteAsync buf:0x%08X, length:0x%08X\n", NandBuffer, NandLength - NandTransferred); + ret = NANDWriteAsync(NandFile, (void *)NandBuffer, NandLength - NandTransferred, BS2NANDDivideCallback, block); + } else { + BS2Report("NANDReadAsync buf:0x%08X, length:0x%08X\n", NandBuffer, NandLength - NandTransferred); + ret = NANDReadAsync(NandFile, (void *)NandBuffer, NandLength - NandTransferred, BS2NANDDivideCallback, block); + } + if (ret < 0) { + NandCompletion(ret, block); + } + } else { + NandCompletion(NandLength, block); + } + } + } +} + +void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block) { + NandFile = info; + NandBuffer = (u8 *)buffer; + NandLength = length; + NandTransferred = 0; + NandCompletion = callback; + NandOperation = 2; + if (NandLength > 0x40000) { + BS2Report("NANDReadAsync buf:0x%08X, length:0x%08X\n", NandBuffer, 0x40000); + NANDReadAsync(NandFile, (void *)NandBuffer, 0x40000, BS2NANDDivideCallback, block); + } else { + BS2Report("NANDReadAsync buf:0x%08X, length:0x%08X\n", NandBuffer, NandLength); + NANDReadAsync(NandFile, (void *)NandBuffer, NandLength, BS2NANDDivideCallback, block); + } +} + +void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block) { + NandFile = info; + NandBuffer = (u8 *)buffer; + NandLength = length; + NandTransferred = 0; + NandCompletion = callback; + NandOperation = 1; + if (NandLength > 0x40000) { + BS2Report("NANDWriteAsync buf:0x%08X, length:0x%08X\n", NandBuffer, 0x40000); + NANDWriteAsync(NandFile, (void *)NandBuffer, 0x40000, BS2NANDDivideCallback, block); + } else { + BS2Report("NANDWriteAsync buf:0x%08X, length:0x%08X\n", NandBuffer, NandLength); + NANDWriteAsync(NandFile, (void *)NandBuffer, NandLength, BS2NANDDivideCallback, block); + } +} + +BOOL CheckBS2CommandStatus() { + u32 partCount; + u32 chunkLength; + if (CheckDVDCommandStatus(&Block) == 0) { + BS2Report("DVD command is issuing\n"); + return 0; + } + if (BS2BootFromCache == 0) { + if (BS2BootCaching == 0) { + BS2Report("Boot cache mode OFF\n"); + return 1; + } + } + if (NandPending != 0) { + BS2Report("NAND command is issuing\n"); + return 0; + } + if (CacheCommandComplete != 0) { + if (State == 3) { + CacheSeekComplete = 1; + } + CacheCommandComplete = 0; + return TRUE; + } + switch (State) { + case 3: { + CacheLength = 0; + BS2Report("Seek cache.dat\n"); + NandPending = 1; + CacheCommandComplete = 1; + NANDSeekAsync(&BS2CacheFileInfo, 0, 0, BS2NANDCallback, &BS2NandBlock); + return 0; + } + case 5: { + if (BS2BootCaching != 0) { + BS2Report("Write drive info\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + 0x20; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &DriveInfo, 0x20, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 9: { + if (BS2BootCaching != 0) { + BS2Report("Write disk id\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + 0x20; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &DiskID, 0x20, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 0x10: { + if (BS2BootCaching != 0) { + BS2Report("Write game toc\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + 0x20; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &GameTOCBuf, 0x20, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 0x12: { + if (BS2BootCaching != 0) { + BS2Report("Write partition ifno\n"); + NandPending = 1; + partCount = ((DVDGameTOC *)DataToc)->partitionCount; + chunkLength = OSRoundUp32B(partCount * sizeof(DVDPartitionInfo)) + 32; + CacheCommandComplete = 1; + CacheLength = CacheLength + chunkLength; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &PartitionInfoBuf, chunkLength, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 0x14: { + if (BS2BootCaching != 0) { + BS2Report("Write boot info 3\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + 0x2000; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &bi3, 0x2000, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 0x26: { + if (BS2BootCaching != 0) { + BS2Report("Write open partition\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + 0x4a00; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &PartitionParams.tmd, 0x4a00, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 0x28: { + if (BS2BootCaching != 0) { + BS2Report("Write apploader header\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + 0x20; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, &AppLoaderHdr, 0x20, BS2NANDCallback, &BS2NandBlock); + return 0; + } + } + break; + } + case 0x2a: { + if (BS2BootCaching != 0) { + BS2Report("Write apploader\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + (AppLoaderHdr.length + 0x1fU & 0xffffffe0); + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, (void *)0x81200000, (AppLoaderHdr.length + 0x1fU & 0xffffffe0), BS2NANDCallback, + &BS2NandBlock); + return 0; + } + } + break; + } + case 0x2c: { + if (BS2BootCaching != 0) { + BS2Report("Write apploader load\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + LoaderLength; + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, (void *)LoaderAddress, (unsigned int)LoaderLength, BS2NANDCallback, + &BS2NandBlock); + return 0; + } + } + break; + } + case 0x2e: { + if (BS2BootCaching != 0) { + BS2Report("Write banner\n"); + NandPending = 1; + CacheCommandComplete = 1; + CacheLength = CacheLength + (BannerLength + 0x1fU & 0xffffffe0); + if ((unsigned int)CacheLength > 0xb00000) { + BS2NANDCallback(-1, NULL); + return 1; + } else { + BS2NANDDivideWriteAsync(&BS2CacheFileInfo, (void *)BannerBuffer, BannerLength + 0x1fU & 0xffffffe0, BS2NANDCallback, + &BS2NandBlock); + return 0; + } + } + break; + } + case 0x30: { + break; + } + default: { + return 1; + } + } + return TRUE; +} + +void BS2InquiryAsync(void *buffer, s32 length, u32 offset) { + if (BS2BootFromCache) { + BS2Report("Unencrypted read from cache.dat\n"); + NandPending = 1; + BS2NANDDivideReadAsync(&BS2CacheFileInfo, buffer, length, (NANDCallback)BS2NANDCallback, &BS2NandBlock); + } else { + DVDUnencryptedReadAbsAsyncForBS(&Block, buffer, length, offset, BS2DVDCallback); + } +} + +void BS2ReadDiskID(void *buffer, s32 length, u32 offset) { + if (BS2BootFromCache) { + BS2Report("Read from cache.dat\n"); + NandPending = 1; + BS2NANDDivideReadAsync(&BS2CacheFileInfo, buffer, length, (NANDCallback)BS2NANDCallback, &BS2NandBlock); + } else { + ((BOOL (*)(DVDCommandBlock *, void *, s32, u32, DVDCommandCallback))DVDReadAbsAsyncForBS)(&Block, buffer, length, offset, + BS2DVDCallback); + } +} + +BS2State BS2Tick() { + u32 interruptsEnabled = OSDisableInterrupts(); + u32 titleCode, titlePrefix; + u8 titleCharacters[4]; + u32 readOffset, readLength, readAddress; + DVDFileInfo bannerFile; + s32 discRegion, status; + u64 currentTime; + BOOL regionMatches; + char productRegion; + DVDPartitionInfo *partition; + u32 iosHigh; + char *ticketByte; + u32 entryCount; + u32 readInterruptsEnabled; + switch (State) { + case 0: + BS2Report("No Disk : %d\n", BS2NoDisk); + BS2Report("Drive Reset : %d\n", BS2DriveReset); + BS2Report("Wait Spinup : %d\n", BS2WaitSpinup); + BS2Report("Boot From Cache : %d\n", BS2BootFromCache); + DvdProgress = (u32 *)&(*(u32 *)0x800030d4); + PartitionParams.numTmdBytes = 0; + PartitionParams.numCertBytes = 0; + PartitionParams.dataWordOffset = 0; + (*(u32 *)0x800030d4) = 0; + DvdTransferred = 0; + DvdTransferLength = 0; + AudioBufferUnconfigured = 1; + CoverBlock.state = 0; + if (BS2NoDisk != 0) + State = BS2_STT_NO_DISK; + else if (BS2DriveReset != 0) + State = BS2_STT_2; + else { + State = BS2_STT_3; + currentTime = __OSGetSystemTime(); + ResetTime = currentTime; + if (BS2WaitSpinup == 0 || BS2BootFromCache != 0) { + currentTime = __OSGetSystemTime(); + SpinupDeadline = currentTime; + } else { + currentTime = __OSGetSystemTime(); + SpinupDeadline = currentTime + (u64)((OS_BUS_CLOCK >> 2) * 5); + } + } + break; + case 1: + currentTime = __OSGetSystemTime(); + if ((OSTime)currentTime < (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 80)) + break; + State = BS2_STT_2; + case 2: + PartitionParams.numTmdBytes = 0; + PartitionParams.numCertBytes = 0; + PartitionParams.dataWordOffset = 0; + *DvdProgress = 0; + DvdTransferred = 0; + DvdTransferLength = 0; + AudioBufferUnconfigured = 1; + currentTime = __OSGetSystemTime(); + ResetTime = currentTime; + if (BS2BootFromCache == 0) { + currentTime = __OSGetSystemTime(); + SpinupDeadline = currentTime + (u64)((OS_BUS_CLOCK >> 2) * 7); + } else { + currentTime = __OSGetSystemTime(); + SpinupDeadline = currentTime; + } + __OSClearRTCFlags(); + DVDResetAsync(&Block, BS2DVDCallback); + CoverBlock.state = 0; + DriveWasReset = 1; + State = BS2_STT_3; + case 3: + currentTime = __OSGetSystemTime(); + if ((OSTime)currentTime < (OSTime)SpinupDeadline) { + status = CheckDVDCommandStatus(&Block); + if (status != 0) { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - ResetTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 200)) { + status = CheckDVDCommandStatus(&CoverBlock); + if (status != 0) { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + } + } + } + } else { + status = CheckBS2CommandStatus(); + if (status != 0) { + State = BS2_STT_4; + case 4: + if (BS2BootFromCache == 0) + DVDInquiryAsync(&Block, &DriveInfo, BS2DVDCallback); + else { + BS2Report("Read drive info from cache.dat\n"); + NandPending = 1; + BS2NANDDivideReadAsync(&BS2CacheFileInfo, &DriveInfo, 0x20, BS2NANDCallback, &BS2NandBlock); + } + State = BS2_STT_5; + } + } + break; + case 5: + status = CheckBS2CommandStatus(); + if (status != 0) { + if (((*(u32 *)0x8000002c) & 0xf0000000) == 0) + (*(u16 *)0x800030e6) = 0x8002; + else + (*(u16 *)0x800030e6) = DriveInfo.deviceCode | 0x8000; + State = BS2_STT_8; + } + break; + case 6: + DVDDownRotationAsync(&Block, BS2DVDCallback); + State = BS2_STT_7; + break; + case 7: + status = CheckDVDCommandStatus(&Block); + if (status == 0) + break; + State = BS2_STT_8; + case 8: + if (BS2BootFromCache == 0) + DVDReadDiskID(&Block, &DiskID, BS2DVDCallback); + else { + BS2Report("Read disk id from cache.dat\n"); + NandPending = 1; + BS2NANDDivideReadAsync(&BS2CacheFileInfo, &DiskID, 0x20, BS2NANDCallback, &BS2NandBlock); + } + State = BS2_STT_9; + break; + case 9: + case 10: + status = CheckBS2CommandStatus(); + if (status == 0) + break; + memcpy((void *)0x80000000, &DiskID, 0x20); + if ((*(u32 *)0x80000018) == 0x5d1c9ea3) { + status = strncmp((char *)0x80000000, "RAAE", 4); + if ((((status == 0) || (status = strncmp((char *)0x80000000, "408", 3), status == 0)) || + (status = strncmp((char *)0x80000000, "410", 3), status == 0)) || + (status = strncmp((char *)0x80000000, "410", 3), status == 0)) + regionMatches = FALSE; + else + regionMatches = TRUE; + if (regionMatches) { + BS2Report("REVOLUTION DISC\n"); + __DVDLayoutFormat = 0; + State = BS2_STT_15; + break; + } + } + if ((*(u32 *)0x8000001c) == -0x3dcc60c3) { + BS2Report("DOLPHIN LAYOUT FORMAT\n"); + __DVDLayoutFormat = 2; + State = BS2_STT_11; + } else { + BS2Report("UNKNOWN\n"); + State = BS2_STT_54; + break; + } + case 0xb: + productRegion = (*(u8 *)0x80000008); + if (AudioBufferUnconfigured == 0) { + State = BS2_STT_GC_GAME; + break; + } + AudioBufferUnconfigured = 0; + if (productRegion == '\0') + __DVDAudioBufferConfig(&Block, 0, 0, BS2DVDCallback); + else { + productRegion = (*(u8 *)0x80000009); + if (productRegion == '\0') + productRegion = '\n'; + __DVDAudioBufferConfig(&Block, 1, productRegion, BS2DVDCallback); + } + State = BS2_STT_12; + case 0xc: + status = CheckDVDCommandStatus(&Block); + if (status == 0) + break; + State = BS2_STT_13; + case 0xd: + DVDUnencryptedReadAbsAsyncForBS(&Block, &bi2, 0x2000, 0x110, BS2DVDCallback); + State = BS2_STT_14; + case 0xe: + status = CheckDVDCommandStatus(&Block); + discRegion = bi2.countryCode; + if (status == 0) + break; + productRegion = SCGetProductGameRegion(); + switch (productRegion) { + case 0: + regionMatches = discRegion == 0; + break; + case 1: + regionMatches = discRegion == 1; + break; + case 2: + regionMatches = discRegion == 2; + break; + default: + regionMatches = FALSE; + break; + } + if (regionMatches) + State = BS2_STT_GC_GAME; + else + State = BS2_STT_54; + break; + case 0xf: + if (LoadingTitle != 0) { + State = BS2_STT_LOCKED_DISK; + break; + } + BS2InquiryAsync(&GameTOCBuf, 0x20, 0x10000); + State = BS2_STT_16; + case 0x10: + status = CheckBS2CommandStatus(); + if (status == 0) + break; + *(DVDGameTOC **)&GameToc = (DVDGameTOC *)GameTOCBuf; + BS2Report("length ... 0x%08X\n", 0x20); + BS2Report("numGamePartitions ... 0x%08X\n", (*(DVDGameTOC **)&GameToc)->partitionCount); + BS2Report("partitionInfos ... 0x%08X\n", (u32)(*(DVDGameTOC **)&GameToc)->partitionInfo); + DataToc = (u32)((DVDGameTOC *)GameTOCBuf + 1); + BS2Report("numGamePartitions ... 0x%08X\n", ((DVDGameTOC *)GameTOCBuf)[1].partitionCount); + BS2Report("partitionInfos ... 0x%08X\n", ((DVDGameTOC *)DataToc)->partitionInfo); + State = BS2_STT_17; + case 0x11: + BS2InquiryAsync(&PartitionInfoBuf, ((((DVDGameTOC *)DataToc)->partitionCount * 8 + 0x1fU & 0xffffffe0) + 0x20), + (u32)(*(DVDGameTOC **)&GameToc)->partitionInfo); + State = BS2_STT_18; + case 0x12: { + status = CheckBS2CommandStatus(); + if (status == 0) + break; + partition = (DVDPartitionInfo *)PartitionInfoBuf; + PartitionCursor = (u32)&PartitionInfoBuf; + UpdatePartition = 0; + GamePartition = 0; + for (titleCode = 0; titleCode < (*(DVDGameTOC **)&GameToc)->partitionCount; titleCode = titleCode + 1) { + BS2Report("gamePartition ... 0x%08X\n", (u32)partition->partition); + BS2Report("type ... 0x%08X\n", ((DVDPartitionInfo *)PartitionCursor)->partitionType); + if (((DVDPartitionInfo *)PartitionCursor)->partitionType == 0) + GamePartition = PartitionCursor; + if (((DVDPartitionInfo *)PartitionCursor)->partitionType == 1) + UpdatePartition = PartitionCursor; + partition = (DVDPartitionInfo *)PartitionCursor + 1; + PartitionCursor = (u32)partition; + } + partition = (DVDPartitionInfo *)PartitionInfoBuf + 4; + PartitionCursor = (u32)((DVDPartitionInfo *)PartitionInfoBuf + 4); + for (titleCode = 0; titleCode < ((DVDGameTOC *)DataToc)->partitionCount; titleCode = titleCode + 1) { + BS2Report("gamePartition ... 0x%08X\n", (u32)partition->partition); + BS2Report("type ... 0x%08X\n", ((DVDPartitionInfo *)PartitionCursor)->partitionType); + partition = (DVDPartitionInfo *)PartitionCursor + 1; + PartitionCursor = (u32)partition; + } + State = BS2_STT_19; + } + case 0x13: + BS2InquiryAsync(&bi3, 0x2000, 0x13800); + State = BS2_STT_20; + case 0x14: + status = CheckBS2CommandStatus(); + discRegion = bi3.countryCode; + if (status == 0) + break; + if (bi3.magic != -0x3c07e572) { + State = BS2_STT_54; + break; + } + productRegion = SCGetProductGameRegion(); + switch (productRegion) { + case 0: + regionMatches = discRegion == 0; + break; + case 1: + regionMatches = discRegion == 1; + break; + case 2: + regionMatches = discRegion == 2; + break; + case 4: + regionMatches = discRegion == 4; + break; + case 5: + regionMatches = discRegion == 5; + break; + default: + regionMatches = FALSE; + break; + } + if (regionMatches) { + status = BS2IsValidDisc(); + if (status == 0) + State = BS2_STT_54; + else if (BS2BootFromCache == 0) { + if (UpdatePartition == 0) { + if (GamePartition == 0) + State = BS2_STT_54; + else + State = BS2_STT_37; + } else { + State = BS2_STT_21; + case 0x15: + DVDOpenPartitionAsync(&Block, (void *)(u32)&PartitionParams.tmd, (u32)((DVDPartitionInfo *)UpdatePartition)->partition, + BS2DVDCallback); + PartitionOpen = 1; + State = BS2_STT_22; + } + } else + State = BS2_STT_37; + } else + State = BS2_STT_54; + break; + case 0x16: + status = CheckDVDCommandStatus(&Block); + if (status != 0) { + CurrentTmd = (u32)&PartitionParams.tmd; + BS2Report("TMD ver ... 0x%02X\n", PartitionParams.tmd.head.version); + BS2Report("CA CRL ver ... 0x%02X\n", ((ESTitleMeta *)CurrentTmd)->head.caCrlVersion); + BS2Report("Signer CRL ver ... 0x%02X\n", ((ESTitleMeta *)CurrentTmd)->head.signerCrlVersion); + BS2Report("Req sys ver ... 0x%08X%08X\n", (u32)(((ESTitleMeta *)CurrentTmd)->head.sysVersion >> 32), + (u32)((ESTitleMeta *)CurrentTmd)->head.sysVersion); + BS2Report("Title ID ... 0x%08X%08X\n", (u32)(((ESTitleMeta *)CurrentTmd)->head.titleId >> 32), + (u32)((ESTitleMeta *)CurrentTmd)->head.titleId); + State = BS2_STT_23; + } + break; + case 0x17: + DVDReadAbsAsyncForBS(&Block, &UpdateDiskID, 0x20, 0, BS2DVDCallback); + State = BS2_STT_24; + break; + case 0x18: + status = CheckDVDCommandStatus(&Block); + if (status == 0) + break; + if (UpdateDiskID.rvlMagic != 0x5d1c9ea3) { + State = BS2_STT_35; + break; + } + State = BS2_STT_25; + case 0x19: + DVDReadAbsAsyncForBS(&Block, &AppLoaderHdr, 0x20, 0x910, BS2DVDCallback); + State = BS2_STT_26; + break; + case 0x1a: + status = CheckDVDCommandStatus(&Block); + if (status == 0) + break; + BS2Report(" appLoaderLength ...... 0x%x\n", AppLoaderHdr.length); + BS2Report(" appLoaderFunc1 ...... 0x%x\n", AppLoaderHdr.entryPoint); + State = BS2_STT_27; + case 0x1b: + DVDReadAbsAsyncForBS(&Block, (void *)0x81200000, (AppLoaderHdr.length + 0x1fU & 0xffffffe0), 0x918, BS2DVDCallback); + State = BS2_STT_28; + break; + case 0x1c: + status = CheckDVDCommandStatus(&Block); + if (status == 0) + break; + ICInvalidateRange((void *)0x81200000, (AppLoaderHdr.length + 0x1fU & 0xffffffe0)); + ((void (*)(void *, void *, void *))AppLoaderHdr.entryPoint)(((void *)&LoaderInit), ((void *)&LoaderMain), ((void *)&LoaderClose)); + ((void (*)(void *))((*(void **)&LoaderInit)))((void *)BS2Report); + BS2Report("\nApploader Initialized\n"); + State = BS2_STT_29; + break; + case 0x1d: + status = ((int (*)(u32 *, u32 *, u32 *))((*(void **)&LoaderMain)))(&readAddress, &readLength, &readOffset); + if (status == 0) + State = BS2_STT_31; + else { + BS2Report("Addr [0x%x] length [0x%x] offset [0x%x]\n", readAddress, readLength, readOffset); + readInterruptsEnabled = OSDisableInterrupts(); + DVDReadAbsAsyncForBS(&Block, (void *)readAddress, readLength, readOffset >> (__DVDLayoutFormat & 0x3f), BS2DVDCallback); + if (*(s32 *)DvdProgress != 0) { + DvdReadPending = 1; + DvdTransferLength = readLength; + } + OSRestoreInterrupts(readInterruptsEnabled); + State = BS2_STT_30; + } + break; + case 0x1e: + status = CheckDVDCommandStatus(&Block); + if (status != 0) + State = BS2_STT_29; + break; + case 0x1f: + __DVDFSInit(); + BS2UpdateInit((MEMAllocator *)Allocator); + State = BS2_STT_32; + break; + case 0x20: + status = BS2UpdateState(); + if (status == 0) { + status = __DVDGetDriveStatus(); + if (((status == 4) || (status == 5)) || ((status == 3 || (status == 0xb)))) { + State = BS2_STT_60; + DVDCancelAllAsync(BS2DVDCallback); + if (status == 0xb) + RetryErrorFlag = 1; + } + } else { + status = BS2GetUpdateEntryNum(); + if ((status != 0) && (status = BS2UpdateState(), status == 1)) { + entryCount = BS2GetUpdateEntryNum(); + BS2Report("%d entries\n", entryCount); + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + State = BS2_STT_UPDATE_DISK; + } + } else { + BS2Report("No entry\n"); + State = BS2_STT_35; + } + } + break; + case 0x21: + status = CheckDVDCommandStatus(&CoverBlock); + if ((status != 0) && (status = BS2UpdateState(), status == 1)) { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + break; + } + status = BS2UpdateState(); + if (status == 1) + break; + State = BS2_STT_RUNNING_UPDATE; + case 0x22: + status = BS2UpdateState(); + if (status == 2) { + status = __DVDGetDriveStatus(); + if ((((status == 4) || (status == 5)) || (status == 3)) || (status == 0xb)) { + State = BS2_STT_60; + DVDCancelAllAsync(BS2DVDCallback); + UpdateErrorFlag = 1; + if (status == 0xb) + RetryErrorFlag = 1; + } + } else { + status = BS2UpdateState(); + if (status == 3) { + BS2Report("Update success\n"); + } else { + status = BS2UpdateState(); + if (status == 4) { + BS2Report("Update success\nPlease reboot\n"); + } else { + BS2Report("Update failed\n"); + UpdateErrorFlag = 1; + status = __DVDGetDriveStatus(); + if (((status == 4) || (status == 5)) || ((status == 3 || (status == 0xb)))) { + State = BS2_STT_60; + DVDCancelAllAsync(BS2DVDCallback); + if (status == 0xb) + RetryErrorFlag = 1; + } else + State = BS2_STT_UPDATE_FAILED; + break; + } + } + State = BS2_STT_35; + } + break; + case 0x23: + DVDClosePartitionAsync(&Block, BS2DVDCallback); + State = BS2_STT_36; + break; + case 0x24: + status = CheckDVDCommandStatus(&Block); + if (status == 0) + break; + PartitionOpen = 0; + status = BS2UpdateState(); + if (status == 4) { + State = BS2_STT_RESET_SYSTEM; + break; + } + if (GamePartition == 0) { + State = BS2_STT_54; + break; + } + State = BS2_STT_37; + case 0x25: + if (BS2BootFromCache == 0) + DVDOpenPartitionAsync(&Block, (void *)(u32)&PartitionParams.tmd, (u32)((DVDPartitionInfo *)GamePartition)->partition, + BS2DVDCallback); + else { + BS2Report("Open partition from cache.dat\n"); + NandPending = 1; + BS2NANDDivideReadAsync(&BS2CacheFileInfo, (void *)(u32)&PartitionParams.tmd, 0x4a00, BS2NANDCallback, &BS2NandBlock); + } + PartitionOpen = 1; + State = BS2_STT_38; + break; + case 0x26: { + status = CheckBS2CommandStatus(); + if (status == 0) + break; + CurrentTmd = (u32)&PartitionParams.tmd; + BS2Report("TMD ver ... 0x%02X\n", PartitionParams.tmd.head.version); + BS2Report("CA CRL ver ... 0x%02X\n", ((ESTitleMeta *)CurrentTmd)->head.caCrlVersion); + BS2Report("Signer CRL ver ... 0x%02X\n", ((ESTitleMeta *)CurrentTmd)->head.signerCrlVersion); + BS2Report("Req sys ver ... 0x%08X%08X\n", (u32)(((ESTitleMeta *)CurrentTmd)->head.sysVersion >> 32), + (u32)((ESTitleMeta *)CurrentTmd)->head.sysVersion); + BS2Report("Title ID ... 0x%08X%08X\n", (u32)(((ESTitleMeta *)CurrentTmd)->head.titleId >> 32), + (u32)((ESTitleMeta *)CurrentTmd)->head.titleId); + iosHigh = (u32)(((ESTitleMeta *)CurrentTmd)->head.sysVersion >> 32); + RequiredIosLow = (u32)((ESTitleMeta *)CurrentTmd)->head.sysVersion; + RequiredIosHigh = iosHigh; + titleCode = (u32)((ESTitleMeta *)CurrentTmd)->head.titleId; + TitleCode = titleCode; + if ((u32)((ESTitleMeta *)CurrentTmd)->head.sysVersion == 0x10 && (u32)(((ESTitleMeta *)CurrentTmd)->head.sysVersion >> 32) == 1) { + BS2Report("This must be a backup disk\n"); + State = BS2_STT_FATAL_ERROR; + break; + } + memset(titleCharacters, 0, sizeof(titleCharacters)); + titlePrefix = titleCode >> 0x18; + titleCharacters[3] = (u8)titleCode; + titleCharacters[0] = (char)(titleCode >> 0x18); + if (titlePrefix < 0x52) { + if (titlePrefix != 0x44) + goto unrestricted_title; + check_title_region: + if (titleCharacters[3] == 0x41) { + regionMatches = TRUE; + goto title_region_checked; + } + productRegion = SCGetProductGameRegion(); + if (productRegion == '\x03') + goto title_region_mismatch; + if ('\x02' < productRegion) { + if (productRegion == '\x05') { + if (titleCharacters[3] != 0x43) + goto title_region_mismatch; + regionMatches = TRUE; + } else { + if (('\x04' < productRegion) || (titleCharacters[3] != 0x4b)) + goto title_region_mismatch; + regionMatches = TRUE; + } + goto title_region_checked; + } + if (productRegion == '\x01') { + if (titleCharacters[3] < 0x58) { + if (titleCharacters[3] == 0x45) + goto us_title_region; + } else if (titleCharacters[3] < 0x5b) { + us_title_region: + regionMatches = TRUE; + goto title_region_checked; + } + goto title_region_mismatch; + } + if (productRegion < '\x01') { + if ((productRegion < '\0') || + ((titleCharacters[3] != 0x57 && ((0x56 < titleCharacters[3] || (titleCharacters[3] != 0x4a)))))) + goto title_region_mismatch; + regionMatches = TRUE; + } else { + switch (titleCharacters[3]) { + case 0x44: + case 0x46: + case 0x48: + case 0x49: + case 0x50: + case 0x52: + case 0x53: + case 0x55: + case 0x56: + case 0x58: + case 0x59: + case 0x5a: + regionMatches = TRUE; + break; + case 0x57: + titleCharacters[1] = (u8)(titleCode >> 0x10); + titleCharacters[2] = (u8)(titleCode >> 8); + if (((titleCharacters[0] != 'R') || ((titleCode >> 0x10 & 0xff) != 0x4c)) || ((titleCode >> 8 & 0xff) != 0x57)) + goto title_region_mismatch; + regionMatches = TRUE; + break; + default: + title_region_mismatch: + regionMatches = FALSE; + break; + } + } + goto title_region_checked; + } else { + if (titlePrefix < 0x55) + goto check_title_region; + unrestricted_title: + regionMatches = TRUE; + } + title_region_checked: + if (!regionMatches) { + RegionValid = 0; + State = BS2_STT_47; + break; + } + RegionValid = 1; + State = BS2_STT_39; + } + case 0x27: + BS2ReadDiskID(&AppLoaderHdr, 0x20, 0x910); + State = BS2_STT_40; + break; + case 0x28: + status = CheckBS2CommandStatus(); + if (status == 0) + break; + BS2Report(" appLoaderLength ...... 0x%x\n", AppLoaderHdr.length); + BS2Report(" appLoaderFunc1 ...... 0x%x\n", AppLoaderHdr.entryPoint); + State = BS2_STT_41; + case 0x29: + BS2ReadDiskID((void *)0x81200000, (AppLoaderHdr.length + 0x1fU & 0xffffffe0), 0x918); + State = BS2_STT_42; + break; + case 0x2a: + status = CheckBS2CommandStatus(); + if (status == 0) + break; + ICInvalidateRange((void *)0x81200000, (AppLoaderHdr.length + 0x1fU & 0xffffffe0)); + ((void (*)(void *, void *, void *))AppLoaderHdr.entryPoint)(((void *)&LoaderInit), ((void *)&LoaderMain), ((void *)&LoaderClose)); + ((void (*)(void *))((*(void **)&LoaderInit)))((void *)OSReport); + BS2Report("\nApploader Initialized\n"); + State = BS2_STT_43; + break; + case 0x2b: + status = ((int (*)(u32 *, u32 *, u32 *))((*(void **)&LoaderMain)))(&readAddress, &readLength, &readOffset); + if (status == 0) + State = BS2_STT_45; + else { + BS2Report("Addr [0x%x] length [0x%x] offset [0x%x]\n", readAddress, readLength, readOffset); + readInterruptsEnabled = OSDisableInterrupts(); + BS2ReadDiskID((void *)readAddress, readLength, readOffset >> (__DVDLayoutFormat & 0x3f)); + LoaderLength = readLength; + LoaderAddress = readAddress; + LoaderOffset = readOffset; + if ((*(s32 *)DvdProgress != 0) && (BS2BootFromCache == 0)) { + DvdReadPending = 1; + DvdTransferLength = readLength; + } + OSRestoreInterrupts(readInterruptsEnabled); + State = BS2_STT_44; + } + break; + case 0x2c: + status = CheckBS2CommandStatus(); + if (status != 0) + State = BS2_STT_43; + break; + case 0x2d: + if (PartitionParams.numTmdBytes == 0) { + __DVDFSInit(); + status = DVDConvertPathToEntrynum("/opening.bnr"); + if (-1 < status) { + DVDFastOpen(status, &bannerFile); + if (Allocator != 0) { + if (BannerAllocation != 0) + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + status = (int)MEMAllocFromAllocator((MEMAllocator *)Allocator, ((bannerFile.length + 0x3fU) & 0xffffffe0)); + BannerAllocation = status; + if (status == 0) + OSPanic("BS2Mach.c", 0x12c8, "BS2 ERROR >>> Cannnot alloc 0x%08x from MEMAllocator", bannerFile.length); + BannerLength = bannerFile.length; + BannerBuffer = OSRoundDown32B(BannerAllocation) + 32; + BS2Report("BannerBufferAddr : %08X\n"); + } else { + if ((BannerBuffer != 0) && (BannerLength != 0)) { + if (BannerLength < ((bannerFile.length + 0x1fU) & 0xffffffe0)) + OSPanic("BS2Mach.c", 0x12d3, "BS2 ERROR >>> Banner buffer is not enough to load banner file (0x%08x)"); + BS2Report("BannerBufferAddr : %08X\n", BannerBuffer); + } else + OSPanic("BS2Mach.c", 0x12da, "BS2 ERROR >>> MEMAllocator and banner buffer is not set"); + } + if (bannerFile.length != 0) { + BS2ReadDiskID((void *)BannerBuffer, ((bannerFile.length + 0x1fU) & 0xffffffe0), + bannerFile.startAddr >> (__DVDLayoutFormat & 0x3f)); + State = BS2_STT_46; + break; + } + } + BannerAvailable = 0; + if ((Allocator != 0) && (BannerAllocation != 0)) { + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + BannerAllocation = 0; + BannerBuffer = 0; + BannerLength = 0; + } + State = BS2_STT_47; + } else + State = BS2_STT_47; + break; + case 0x2e: + status = CheckBS2CommandStatus(); + if (status != 0) { + BannerAvailable = 1; + State = BS2_STT_47; + } + break; + case 0x2f: + DVDClosePartitionAsync(&Block, BS2DVDCallback); + State = BS2_STT_48; + break; + case 0x30: + status = CheckBS2CommandStatus(); + if (status != 0) { + PartitionOpen = 0; + if (RegionValid == 0) + State = BS2_STT_54; + else { + if (BS2BootCaching != 0) { + BS2BootFromCache = 1; + BS2BootCaching = 0; + } + if (((u32)((ESTitleMeta *)CurrentTmd)->head.titleId == 0x4c4f43) && (LoadingTitle == 0)) + State = BS2_STT_DATA_DISK; + else if (PartitionParams.numTmdBytes == 0) + State = BS2_STT_RVL_GAME; + else + State = BS2_STT_START_LOCKED_DISK; + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + } + break; + case 0x31: + case 0x45: + case 0x48: + status = CheckDVDCommandStatus(&CoverBlock); + if ((status != 0) && (StartingGame == 0)) { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + } + break; + case 0x32: + status = CheckDVDCommandStatus(&CoverBlock); + if ((status != 0) && (StartingGame == 0)) { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + } + break; + case 0x33: + PartitionOpen = 0; + BannerAvailable = 0; + if ((Allocator != 0) && (BannerAllocation != 0)) { + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + BannerAllocation = 0; + BannerBuffer = 0; + BannerLength = 0; + } + LoadingTitle = 0; + State = BS2_STT_2; + break; + case 0x34: + case 0x35: + BannerAvailable = 0; + if ((Allocator != 0) && (BannerAllocation != 0)) { + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + BannerAllocation = 0; + BannerBuffer = 0; + BannerLength = 0; + } + BS2BootFromCache = 0; + BS2BootCaching = 1; + LoadingTitle = 0; + if ((Block.state < 6) && (3 < Block.state)) + CheckDVDCommandStatus(&Block); + else { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + } + break; + case 0x36: + BannerAvailable = 0; + if ((Allocator != 0) && (BannerAllocation != 0)) { + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + BannerAllocation = 0; + BannerBuffer = 0; + BannerLength = 0; + } + LoadingTitle = 0; + DVDChangeDiskAsyncForBS(&Block, BS2DVDCallback); + State = BS2_STT_55; + case 0x37: + case 0x38: + CheckDVDCommandStatus(&Block); + break; + case 0x39: + case 0x3a: + BannerAvailable = 0; + if ((Allocator != 0) && (BannerAllocation != 0)) { + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + BannerAllocation = 0; + BannerBuffer = 0; + BannerLength = 0; + } + LoadingTitle = 0; + break; + case 0x3b: + case 0x3f: + if (UpdateErrorFlag == 0) { + if (RetryErrorFlag != 0) { + RetryErrorFlag = 0; + State = BS2_STT_DIRTY_DISK; + } + if (AbortFlag == 0) { + if ((Block.state < 6) && (3 < Block.state)) + CheckDVDCommandStatus(&Block); + else { + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - CoverPollTime) >= (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 100)) { + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + } + } + } else { + AbortFlag = 0; + State = BS2_STT_64; + } + } else + State = BS2_STT_UPDATE_FAILED; + break; + case 0x3c: + status = CheckBS2CommandStatus(); + if (status != 0) + State = BS2_STT_61; + break; + case 0x3d: + DVDClosePartitionAsync(&Block, BS2DVDCallback); + State = BS2_STT_62; + break; + case 0x3e: + status = CheckBS2CommandStatus(); + if (status != 0) { + PartitionOpen = 0; + RestartRequested = 0; + State = BS2_STT_63; + } + break; + case 0x40: + AbortFlag = 0; + if (RestartRequested != 0) { + RestartRequested = 0; + if (FatalErrorFlag == 0) { + if (PartitionOpen == 0) { + if ((__DVDLayoutFormat == 2) || ((BS2DriveReset != 0 && (DriveWasReset == 0)))) + State = BS2_STT_2; + else { + if (Block.state == 10) + Block.state = 0; + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&CoverBlock, BS2DVDCallback); + State = BS2_STT_3; + } + } else { + PartitionOpen = 0; + State = BS2_STT_15; + } + } else + State = BS2_STT_FATAL_ERROR; + } + break; + case 0x41: + BannerAvailable = 0; + if ((Allocator != 0) && (BannerAllocation != 0)) { + MEMFreeToAllocator((MEMAllocator *)Allocator, (void *)BannerAllocation); + BannerAllocation = 0; + BannerBuffer = 0; + BannerLength = 0; + } + break; + case 0x42: + currentTime = __OSGetSystemTime(); + if ((OSTime)(currentTime - (((u64)CoverOpenTimeHigh << 32) | CoverOpenTimeLow)) < (OSTime)(((OS_BUS_CLOCK >> 2) / 1000) * 350)) + break; + currentTime = __OSGetSystemTime(); + CoverPollTime = currentTime; + __DVDGetCoverStatusAsync(&Block, BS2DVDCallback); + State = BS2_STT_67; + case 0x43: + case 0x44: + CheckDVDCommandStatus(&Block); + break; + case 0x46: + DVDGetPartitionParamsAsync(&Block, &PartitionParams, (u32)((DVDPartitionInfo *)GamePartition)->partition, BS2DVDCallback); + State = BS2_STT_71; + break; + case 0x47: { + status = CheckBS2CommandStatus(); + if (status != 0) { + ticketByte = (char *)&PartitionParams.ticket; + for (status = 0; status < sizeof(PartitionParams.ticket); ++status) { + if (ticketByte[status] != 0) { + BS2Report("eTicket is none zero\n"); + break; + } + } + memcpy(&PartitionParams.ticketView, (void *)TitleTicketView, sizeof(ESTicketView)); + DCStoreRange(&PartitionParams.ticketView, sizeof(ESTicketView)); + DVDOpenPartitionWithParamsAsync(&Block, &PartitionParams, (u32)((DVDPartitionInfo *)GamePartition)->partition, BS2DVDCallback); + PartitionOpen = 1; + State = BS2_STT_38; + } + } break; + default: + OSPanic("BS2Mach.c", 0x14e3, "BS2 ERROR >>> UNKNOWN STATE"); + break; + } + OSRestoreInterrupts(interruptsEnabled); + return State; } diff --git a/tools/decomp-assist/BS2Mach.attempts.md b/tools/decomp-assist/BS2Mach.attempts.md new file mode 100644 index 00000000..516f44a8 --- /dev/null +++ b/tools/decomp-assist/BS2Mach.attempts.md @@ -0,0 +1,171 @@ +# BS2Mach attempts + +Baseline: 16/29 instruction-exact functions, code 2500/16980 bytes, +data 155472/158528 bytes. The fresh branch baseline gate passes. +Only this unit is changed. No linking changes are made. + +The assembly and the existing object decompiler exports under /tmp were read. +Older /tmp source candidates were used as reference and audited before adapting +individual bodies. Their assembly, force_active pragmas, register qualifiers, +volatile additions, packed string blobs, and raw structure offsets are excluded. + +## Object-order implementation, first pass + +- Run: C cache-block zero/flush loop followed by the entry call. The original + clears nearly all GPRs, replaces the stack, and branches through LR. C cannot + express that register contract. The report gives no function score. +- BS2ESGetTicketViews: separate aligned title/count buffers produced 72/71 + instructions and a 0x180 frame versus 0x160. A single 256-byte IPC workspace + with typed title/count arrays and boolean null checks gives 71/71, diffs 0. +- BS2Reboot: ordinary aligned ticket, IOS workspace, state flags and vectors + initially gave 137/137, eight stack-offset diffs. Reordering descriptor and + count declarations gives 137/137, diffs 0. No fabricated padding is used. +- BS2StartGame: implemented boot-cache close, state flags, IOS launch, DVD + reopen, and loader handoff. First score 96.48855%. Target contains sync/isync + and polls callback results; no new assembly or volatile was introduced. +- BS2StartGCGame: implemented configuration, SRAM fields, clock and MIOS launch. + First score 95.26755%. +- CheckDVDCommandStatus: original switch/state transitions, 102/102, diffs 0. +- BS2NANDDivideCallback: transfer accounting before buffer advance, separate + full/final chunk branches, first score 85.03906%. +- BS2NANDDivideReadAsync: original request setup and chunk branches with ordinary + globals, first score 60.31915%, 45/47 instructions. Compiler removes reloads. +- BS2NANDDivideWriteAsync: corresponding write setup, first score 60.31915%. +- CheckBS2CommandStatus: cache-writing state switch, first score 79.655174%. +- BS2InquiryAsync: boot-cache/DVD unencrypted read branches, instruction-exact. +- BS2ReadDiskID: boot-cache/DVD read branches, instruction-exact. +- BS2Tick: implementation pending at this checkpoint. + +String pool: the first 56 strings are identical in order; the remaining 35 +orig strings belong to BS2Tick. Checkpoint: 21/29 exact, code 4052/16980, +zero regressions, zero forbidden additions, zero readability warnings. + +## Complete state machine and data review + +BS2Tick was implemented last, preserving object order. All 91 ordinary string +literals now occur in the original order and at the original .data offsets. +A separate offset comparison found zero differences across all 91 strings. +The small writable GameCube language mapping, /dev/es and disc prefixes produce +an instruction-independent .sdata match of 32/32 bytes. The larger .data section +still has no objdiff match score; strings alone do not establish a data match. + +Semantic review corrected the cover command block reset, replaced an unsafe +four-byte memset of separate char locals with a four-byte title array, used +DVDFileInfo fields for banner position/length, and changed the newly implemented +loader code to use the target's __DVDLayoutFormat rather than BS2LastMode. +All partition/TMD/SRAM field accesses use their existing structure definitions. +The allocation rounds down then adds one cache line to select the next aligned +banner address, as the target does. This is buffer alignment, not data padding. + +The ES stack workspace follows the SDK's 256-byte IPC work-area convention. +It holds typed aligned title and count buffers. The reboot launch workspace is +also the SDK's 256-byte IPC workspace. No objects were added to move .data. + +The SDK declaration of DVDReadAbsAsyncForBS has a sixth priority parameter, +but the implementation ignores it and this IPL object passes five arguments. +BS2_MACH_FIVE_ARG_READ is defined only by BS2Mach.c and guards the declaration +in the shared header. Other units keep their original declaration and output. +The NAND callback now declares its real second callback parameter. Passing NULL +on direct error notifications restores the missing r4 argument setup without +changing the already exact callback body. + +## Remaining-function attempt coverage + +Every remaining function has at least three distinct source-level attempts. +Percentages are advisory objdiff scores from the quick gates; none is called an +exact match. Final instruction counts come from fresh ctxdiff calls. + +### Run + +1. Per-block do/while DCZeroRange/DCFlushRange, then entry call: 28/43 + instructions; objdiff reports None. +2. Counted for loop over cache blocks: objdiff 0.88372093%; register clearing, + stack replacement and LR handoff are still absent. +3. Bulk cache zero/flush followed by entry: 25/43 instructions, score None. + Retained the per-block form to preserve the target's cache-operation order. + The GPR-clearing trampoline cannot be expressed as ordinary portable C. + +### BS2StartGame + +1. Target-shaped nested error branches with empty polling loops: 96.48855%, + 387/393 instructions. The compiler hoists reads out of unqualified polls. +2. Switch dispatch for disk/partition results: 94.18575%, 396/393 instructions. +3. Restored nested branches, used DVDGetCommandBlockStatus for the cover wait + and interrupt synchronization in low-level callback waits: 93.178116%, + 406/393 instructions. This keeps polling functional without new volatile. + Compiler __sync/__isync intrinsics restore the real loader barriers without + adding asm functions or blocks. Final NAND callback ABI correction gives + 95.496185%, 401/393. Calls and register scheduling still differ. + +### BS2StartGCGame + +1. Configuration/SRAM/MIOS implementation: 95.26755%, 228/228 instructions. +2. Reverse multiplication operands and pass the MIOS title as a real 64-bit + vararg, rather than unrelated 32-bit arguments: 95.4386%, 227/228. +3. Separate seconds/timerFrequency locals and use the DVD status API for the + cover wait: 98.11404%, 227/228. Retained this functional form. Differences + include the polling call, the target's additional MMIO read, and scheduling. + +### BS2NANDDivideCallback + +1. Update transferred count, advance buffer, and retain separate full/final + chunk paths: 85.03906%. +2. Cache the remaining length in a local shared across the paths: 70.859375%, + 119/128. This changes allocation and removes more of the target's reloads. +3. Use typed file/buffer/completion globals and advance buffer before account + update: 85.0%. Final form retains the typed state but restores accounting + before buffer advance: 85.03906%, 119/128. Nine target instructions remain + missing, chiefly global reloads and callback setup ordering. + +### BS2NANDDivideReadAsync + +1. Original request setup order plus a total-length temporary: 60.31915%, + 45/47. Two target reload instructions are absent. +2. Compare the stored total directly, removing the temporary: 60.31915%, + 45/47. No improvement; optimizer produces the same sequence. +3. Typed request globals and file/buffer/length-first initialization: + 60.29787%, 45/47. Retained readable typed state. Reloads and register/setup + order remain different. + +### BS2NANDDivideWriteAsync + +1. Original write setup plus total-length temporary: 60.31915%, 45/47. +2. Direct stored-length comparison: 60.31915%, 45/47; no instruction change. +3. Typed globals and file/buffer/length-first initialization: 60.29787%, + 45/47. Same missing reloads and initialization scheduling as the read path. + +### CheckBS2CommandStatus + +1. Per-state cache write paths with shared result/exit: 79.655174%, 382/406. +2. Direct returns instead of shared goto exit: 79.655174%, 382/406. No change. +3. Compute the partition chunk length once from DVDGameTOC fields: + 78.94089%. Final correct two-argument NAND callback notifications yield + 80.133%, 387/406. Target retains repeated cache-length reloads, and setup + scheduling remains different. No volatile was added to manufacture them. + +### BS2Tick + +1. Complete switch in source-token order, typed fields and signed time checks: + 74.99381%, 1896/1940. All 91 string contents match. +2. Four-byte title array, real partition iteration, correct layout global and + cover-block reset: 75.79124%, 1904/1940. All string offsets also match. +3. Region dispatch as readable switches and a forward ticket-byte scan: + 75.50567%, 1906/1940. Retained the simpler switches and typed scan. Final + callback ABI/state cleanup gives 74.78608%, 1905/1940. Register allocation, + branch scheduling, and remaining reloads differ across many states. + +## Fresh exact-function verification + +- BS2ESGetTicketViews: 71/71 instructions, diffs 0. +- BS2Reboot: 137/137 instructions, diffs 0. +- CheckDVDCommandStatus: 102/102 instructions, diffs 0. +- BS2InquiryAsync: 39/39 instructions, diffs 0. +- BS2ReadDiskID: 39/39 instructions, diffs 0. + +The original 16 exact functions remain exact. Final quick gate: 21/29 exact, +4052/16980 code bytes, 155504/158528 data bytes, zero regressions, zero forbidden +additions and zero readability warnings. The unit remains NonMatching. + +Final full, non-quick gate: GATE PASS. Full build succeeds, main.dol SHA1 is +26116613f624061ba99c8d1a299aaa6efa85670d, regressions 0, forbidden additions 0, +readability warnings 0. No function or unit is claimed complete below 100%. -- 2.49.1