From 21fd0e0b0b9c22fb3be574e2eb12bb9db9fb1685 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 16:17:16 +0000 Subject: [PATCH] HDD Manager: repair the zero disk ID on A2 drives from older builds An APA Jail A2 drive formatted by an older build has a zero MBR disk ID at 0x1B8. Windows treats that as no ID and may write its own, which breaks the APA checksum, so the PS2 sees a damaged header. Newer formats already write a non-zero ID. Options > Repair A2 disk ID... asks for confirmation, verifies the APA header (both header sectors: magic, checksum, A2 marker, the three MBR entries), and only if the ID is zero writes a non-zero ID and the recomputed APA checksum into sector 0, then reads it back. Nothing else is written. A drive that is not A2, already has an ID, or whose header does not verify is left alone. The APA Jail scheme and the sector 0 layout are Berion's. Host tests only; not tested on PCSX2 or a real PS2. --- CHANGELOG.md | 1 + docs/hdd-formatting.md | 9 +++++ include/hdd_format.h | 7 ++++ src/dash_hdd.c | 65 ++++++++++++++++++++++++++++-- src/hdd_format.c | 28 +++++++++++++ src/hdd_format_ps2.c | 23 +++++++++++ tests/test_hdd_format.py | 48 ++++++++++++++++++++++ tests/test_hdd_format_ui.py | 11 +++++ tests/test_hdd_partition_rename.py | 1 + 9 files changed, 190 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1197f2f3..b78c3a31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ The `## Rolling` section below is the maintained summary shown on the GitHub [`l ## Rolling +- **Repair A2 disk ID (HDD Manager > Options; the APA Jail scheme is Berion's, who also explained how sector 0 doubles as the APA header and the MBR):** an APA Jail A2 drive formatted by an older build has a zero MBR disk ID at 0x1B8, which Windows treats as missing and may replace with its own, breaking the APA checksum so the PS2 sees a damaged header. **Repair A2 disk ID...** (shown for APA+exFAT drives) asks for confirmation, checks that sector 0 and 1 hold a valid APA header with the A2 marker and an intact checksum, and if the ID is zero writes a non-zero ID and the recomputed APA checksum into sector 0, then reads it back. Nothing else is written. A drive that is not A2, already has an ID, or whose header does not verify is left alone. Host test: test_hdd_format.py. Not tested on PCSX2 or a real PS2. - **3D save icons (Apollo Save Tool parity; the idea of showing the save's 3D icon is [bucanero](https://github.com/bucanero)'s, in [Apollo Save Tool for PS2](https://github.com/bucanero/apollo-ps2); the code is new):** in **Card contents** and **All saves here...**, a save's action menu has **View 3D icon**. It reads the icon file the save's `icon.sys` names and shows the model turning, with its own picture and vertex colours. Nothing is written to the card, and All saves keeps its list and marks. There is no lighting and no icon animation (the first shape is shown), and no depth buffer: faces are drawn far to near. An icon with more faces than one frame can hold (several thousand; the largest real icon checked has 598) shows the nearest faces that fit. A save with no icon, one that cannot be read, or one holding a sub-folder gets a plain note. The icon reader is host-tested with the icons in this repository and with cut and changed files (`tests/test_mc_icon3d.py`, ASan/UBSan), and a host render of those icons was checked by eye; the drawing on the console is only built by CI. NOT TESTED on PCSX2 or a real PS2. - **Extract a `.zip` in the File Browser (Apollo Save Tool parity; the idea of extracting archives on the console is [bucanero](https://github.com/bucanero)'s, in [Apollo Save Tool for PS2](https://github.com/bucanero/apollo-ps2); the code is ours, the HDD installer's reader):** a `.zip` outside the memory cards has a new **Extract .zip here...** row. Every file goes into a folder named after the archive, next to it; same-named files there are replaced, but only by a file that passes its CRC check; a new file that fails is removed, and names that would leave the folder (`..`, absolute, with `:` or `\`) or are over 255 bytes are skipped and counted. No ZIP64, encrypted or split archives; at most 1024 entries. Host test `tests/test_zip_extract_here.py` (the real code against stand-in file calls, ASan/UBSan). NOT TESTED on PCSX2 or a real PS2. - **`.vm2` and `.card` memory card images (Apollo Save Tool parity):** PS3 `.VM2` and `.CARD` PS2 card images now get the same rows as `.ps2`, `.vmc`, `.bin` and `.mc2`: **Card contents...**, **Mount as vmc0:/vmc1:**, **Write to a real memory card...**, and they are read by **All saves here...**. Only the list of extensions changed; the image is still recognised by its size and contents, so a `.vm2` with ECC bytes is read-only in Card contents, like a PCSX2 `.ps2`. NOT TESTED on PCSX2 or a real PS2. diff --git a/docs/hdd-formatting.md b/docs/hdd-formatting.md index 95bb7a77..ffb737c8 100644 --- a/docs/hdd-formatting.md +++ b/docs/hdd-formatting.md @@ -17,6 +17,15 @@ Project. Sector 0 is also the APA header and its checksum covers those four bytes. Windows treats a zero signature as missing and can write its own, and the PS2 would then see a damaged APA header. +A2 drives formatted by an older build left that ID at zero. HDD Manager > +Options > **Repair A2 disk ID...** fixes such a drive: after confirmation it +checks that the APA header (both header sectors) verifies and carries the A2 +marker, and if the ID is zero it writes a non-zero ID and the recomputed APA +checksum into sector 0, reads it back, and changes nothing else. A drive that +is not A2, already has an ID or has a header that does not verify is left +alone, with a message saying which. A drive where Windows has already written +its own ID has a bad checksum and is refused too: this repair does not guess. + ## APA Jail type D Type D is the current APA Jail layout by **Berion**, as written by the PS2 HDD diff --git a/include/hdd_format.h b/include/hdd_format.h index dfa3026c..47c1b0a6 100644 --- a/include/hdd_format.h +++ b/include/hdd_format.h @@ -47,9 +47,16 @@ int hddApaCanAllocate(HddFsReadSector read, void *context, uint32_t sectors, uin * with the corrected root directory sector for *lba when it is not. */ int hddFormatLabelFix(HddFsReadSector read, void *context, uint32_t sectors, unsigned char sector[512], uint32_t *lba, uint32_t *apa); +/* Read-only check of an A2 drive's MBR disk ID: 0 when it is set, 1 with the + * corrected sector 0 in sector when it is zero, negative when the APA header + * does not verify or the drive is not A2. */ +int hddFormatDiskIdFix(HddFsReadSector read, void *context, uint32_t serial, unsigned char sector[512]); /* Returns 0 when the exFAT label is OPL and 1 when it is not; with apply the * label is then rewritten. The UI reloads the IOP when started is set. */ int hddFormatRelabel(int apply, int *started, uint32_t *apa); +/* Same for the disk ID: 0 when set, 1 when it was (or with apply, now is) + * zero and is fixed by rewriting sector 0 only. */ +int hddFormatDiskId(int apply, int *started); /* EE adapter. Call only with the HDD stack loaded. */ int hddCheckAllocation(uint32_t sectors); int hddGetApaCapacity(uint32_t *sectors); diff --git a/src/dash_hdd.c b/src/dash_hdd.c index 2612d5a7..6ee3dd74 100644 --- a/src/dash_hdd.c +++ b/src/dash_hdd.c @@ -141,7 +141,8 @@ enum { HOP_SYSTEM_APP, HOP_ENABLE_BOOT_FLAG, HOP_READ_BOOT_FLAG, - HOP_DP_REPAIR + HOP_DP_REPAIR, + HOP_DISK_ID_REPAIR }; typedef struct @@ -547,6 +548,11 @@ static void hddJobRun(void *arg) case HOP_DP_REPAIR: dpRepairRun(j); break; + case HOP_DISK_ID_REPAIR: + j->ret = hddFormatDiskId(0, &j->format_started); + if (j->ret > 0 && (j->ret = releaseForRawWrite()) >= 0) + j->ret = hddFormatDiskId(1, &j->format_started); + break; case HOP_INJECT: releaseMounts(); j->ret = InjectHddPartitionHeaderFromSource(j->a, j->b, j->source_dir, sizeof(j->source_dir), @@ -1777,6 +1783,53 @@ static void actDpRepair(void) #endif } +/* An APA Jail A2 drive from an older build has a zero MBR disk ID, which + * Windows may replace and so break the APA header. Only that ID and the + * APA checksum in sector 0 are rewritten. */ +static void actDiskIdRepair(void) +{ +#ifndef NO_IOP_RESET + HddJob *j; + char body[160]; + int ret, began; + +#ifdef ETH + if (isFtpServerRunning() || isSmbServerRunning()) { + dashModalMessage(DI_WARNING, "HDD busy", "Stop the FTP and SMB servers before repairing the HDD.", NULL); + return; + } +#endif + if (!dashModalConfirm("Repair A2 disk ID", "An APA Jail A2 drive formatted by an older Launchstation has no disk ID. Windows may then write its own, and the PS2 would see a damaged APA header. This sets an ID in the first sector and nothing else. It does nothing if the header does not check out. Games, apps and saves are not changed.", "Repair", 0)) return; + if (!dashWorkerAwaitAll("Finishing up") || !(j = jobNew(HOP_DISK_ID_REPAIR))) return; + if (hddFormatLoad() < 0) { + hddJobFree(j); + dashModalMessage(DI_WARNING, "Repair unavailable", "The disk formatting service could not be started. The HDD has not been changed.", NULL); + return; + } + dashSoundShutdown(); + if (!runJob(j, "Repairing the A2 disk ID", 0)) { dashSoundMaintain(); dashBgmStart(); return; } + ret = j->ret; began = j->format_started; + hddJobFree(j); + if (began) { + rebootIopAndReloadCoreStackSilent(); + loadHddModules(); + } + dashSoundMaintain(); dashBgmStart(); + if (ret == -ENOTSUP) + dashModalMessage(DI_INFO, "Not an A2 drive", "Only APA Jail A2 drives are repaired. The HDD has not been changed.", NULL); + else if (ret == -EIO && !began) + dashModalMessage(DI_WARNING, "HDD not changed", "The APA header could not be read or does not check out, so the HDD was left alone.", NULL); + else if (ret < 0) { + snprintf(body, sizeof(body), "The repair did not finish (error %d).", ret); + dashModalMessage(DI_WARNING, "HDD not repaired", body, NULL); + } else if (ret) + dashModalMessage(DI_CHECK, "HDD repaired", "The disk ID is set.", NULL); + else + dashModalMessage(DI_CHECK, "Nothing to repair", "The disk already has an ID.", NULL); + afterChange(); +#endif +} + /* Check on opening Options so removing/replacing the ELF takes effect. */ static int systemAppStatus(void) { @@ -1819,8 +1872,8 @@ static void actEnableBootFlag(void) static void partitionMenu(void) { HddPart *p = (hm.n > 0 && sel < hm.n) ? &hm.parts[sel] : NULL; - DashMenuItem items[16]; - int ids[16], n = 0, r, has_cnf = 0; + DashMenuItem items[18]; + int ids[18], n = 0, r, has_cnf = 0; int system = (p == NULL || p->type == HP_SYSTEM); int reserved = (p != NULL && !strncmp(p->name, "__", 2)); enum { @@ -1838,6 +1891,7 @@ static void partitionMenu(void) A_VISIBILITY, A_ENABLE_BOOT_FLAG, A_DP_REPAIR, + A_DISK_ID_REPAIR, A_INSTALL_GAME }; @@ -1892,6 +1946,8 @@ static void partitionMenu(void) } if (dp_repair && hosdmenu > 0) ADD(DI_TOOLS, "Repair for PSBBN DP PC tools...", NULL, 0, A_DP_REPAIR); + if (dp_repair) + ADD(DI_TOOLS, "Repair A2 disk ID...", NULL, 0, A_DISK_ID_REPAIR); int resume = resumeStatus(); if (resume) ADD(DI_REFRESH, "Resume installation...", resume < 0 ? retry_detail : NULL, @@ -1942,6 +1998,9 @@ static void partitionMenu(void) case A_DP_REPAIR: actDpRepair(); break; + case A_DISK_ID_REPAIR: + actDiskIdRepair(); + break; case A_RESUME: actResume(); hm.resume_checked = 0; diff --git a/src/hdd_format.c b/src/hdd_format.c index 4a8f0c39..258494e3 100644 --- a/src/hdd_format.c +++ b/src/hdd_format.c @@ -264,6 +264,34 @@ int hddFormatLabelFix(HddFsReadSector read, void *context, uint32_t sectors, return 1; } +/* An A2 drive from an older build has a zero MBR disk ID at 0x1B8. Windows + * treats that as no ID and may write its own, which breaks the APA checksum. + * Read-only: returns 0 when the ID is set, 1 with the corrected sector 0 in + * sector (the ID and the APA checksum are the only bytes that change), or a + * negative errno. The header must verify first: the APA magic, its checksum + * over both header sectors, the A2 marker and the three MBR entries. */ +int hddFormatDiskIdFix(HddFsReadSector read, void *context, uint32_t serial, unsigned char sector[512]) +{ + unsigned char header[1024]; + uint32_t sum = 0; + unsigned i; + int ret; + if (!read || !sector) return -EINVAL; + ret = read(context, 0, header); if (ret < 0) return ret; + ret = read(context, 1, header + 512); if (ret < 0) return ret; + for (i = 4; i < 1024; i += 4) sum += get32(header + i); + if (get32(header + 4) != 0x00415041 || get32(header) != sum) return -EIO; + if (header[510] != 0x55 || header[511] != 0xaa || memcmp(header + 224, "APAJ-A2", 7) || + header[450] != 0x17 || header[466] != 0x17 || header[482] != 0x07) return -ENOTSUP; + if (get32(header + 440)) return 0; + put32(header + 440, serial ? serial : 1); + sum = 0; + for (i = 4; i < 1024; i += 4) sum += get32(header + i); + put32(header, sum); + memcpy(sector, header, 512); + return 1; +} + int hddFormatExecute(const HddFormatPlan *p, const HddFormatIo *io) { HddFormatPlan expected; diff --git a/src/hdd_format_ps2.c b/src/hdd_format_ps2.c index 2e01f7c4..9a446457 100644 --- a/src/hdd_format_ps2.c +++ b/src/hdd_format_ps2.c @@ -6,6 +6,7 @@ #include "hdd_install_recovery.h" #include "init.h" #include "dash_internal.h" +#include #include #include @@ -184,6 +185,28 @@ int hddFormatRelabel(int apply, int *started, uint32_t *apa) return ret < 0 ? ret : finish < 0 ? finish : 1; } +int hddFormatDiskId(int apply, int *started) +{ + unsigned char sector[512] __attribute__((aligned(64))), verify[512] __attribute__((aligned(64))); + int total = fileXioDevctl("hdd0:", HDIOC_TOTALSECTOR, NULL, 0, NULL, 0), ret, finish; + *started = 0; + if (total >= -4095 && total <= 0) return total ? total : -ENODEV; + ret = hddFormatDiskIdFix(readApa, "hdd0:", (uint32_t)time(NULL), sector); + if (ret <= 0 || !apply) return ret; + /* Sector 0 only. BEGIN detaches the volumes, and the caller's IOP reset + * loads the driver again so it does not keep the old header. */ + packet.sectors = (uint32_t)total; + ret = call(HF_BEGIN, 0, 0, 64, 64); + if (ret < 0) return ret; + *started = 1; + ret = writeDisk(NULL, 0, 1, sector); + if (ret >= 0) ret = flushDisk(NULL); + if (ret >= 0) ret = readDisk(NULL, 0, 1, verify); + if (ret >= 0 && memcmp(sector, verify, sizeof(verify))) ret = -EIO; + finish = call(HF_FINISH, 0, 0, 64, 64); + return ret < 0 ? ret : finish < 0 ? finish : 1; +} + static int readPhysicalSector(void *ctx, uint32_t lba, void *sector) { return readDisk(ctx, lba, 1, sector); } diff --git a/tests/test_hdd_format.py b/tests/test_hdd_format.py index b7e99fc3..85577c52 100644 --- a/tests/test_hdd_format.py +++ b/tests/test_hdd_format.py @@ -367,6 +367,7 @@ def check(header, table, expected): lib.hddApaCanAllocate.argtypes = [READ_ONE, c.c_void_p, c.c_uint32, c.c_uint32] lib.hddFormatUpper.argtypes = [c.c_uint32] lib.hddFormatLabelFix.argtypes = [READ_ONE, c.c_void_p, c.c_uint32, c.c_char_p, c.POINTER(c.c_uint32), c.POINTER(c.c_uint32)] + lib.hddFormatDiskIdFix.argtypes = [READ_ONE, c.c_void_p, c.c_uint32, c.c_char_p] lib.hddFormatUpper.restype = c.c_uint32 p = Plan() @@ -518,6 +519,53 @@ def check(header, table, expected): assert lib.hddFormatLabelFix(image.one, None, sectors, fixed, c.byref(at), c.byref(apa)) == -errno.EIO image.fail_at = None os.pwrite(image.fd, root_data[:32], root_lba * 512) + # Repair for an A2 drive an older build left with a zero disk ID: the + # ID and the APA checksum in sector 0 are the only bytes that change, + # and a header that does not verify is refused, never guessed at. + fix, good = c.create_string_buffer(512), image.bytes(0, 2) + def fix_id(serial=0x1234abcd): + return lib.hddFormatDiskIdFix(image.one, None, serial, fix) + def put_header(data): + os.pwrite(image.fd, bytes(data), 0) + if kind == JAIL: + assert get32(good, 440) != 0 and fix_id() == 0 + old = bytearray(good) + set32(old, 440, 0) + fix_apa(old) + put_header(old) + assert fix_id() == 1 + new = bytearray(old) + set32(new, 440, 0x1234abcd) + fix_apa(new) + assert fix.raw == bytes(new[:512]) + assert fix.raw[8:440] == old[8:440] and fix.raw[444:512] == old[444:512] + assert get32(new, 0) == sum(struct.unpack_from("<255I", new, 4)) & 0xffffffff + put_header(fix.raw + old[512:]) + assert fix_id() == 0 and image.bytes(0, 2) == bytes(new) + put_header(old) + assert lib.hddFormatDiskIdFix(image.one, None, 0, fix) == 1 and get32(fix.raw, 440) == 1 + # Refused: bad checksum (also what a Windows-written ID leaves), + # bad magic, a damaged second sector, no A2 marker, a failed read. + for damage in (lambda b: set32(b, 0, get32(b, 0) ^ 1), lambda b: set32(b, 4, 0), + lambda b: b.__setitem__(700, b[700] ^ 1), lambda b: set32(b, 440, 0x77777777)): + bad = bytearray(old) + damage(bad) + put_header(bad) + assert fix_id() == -errno.EIO + nomark = bytearray(old) + nomark[224:232] = b"APAJ-D\0\0" + fix_apa(nomark) + put_header(nomark) + assert fix_id() == -errno.ENOTSUP + put_header(old) + image.fail_at = image.calls + 2 + assert fix_id() == -errno.EIO + image.fail_at = None + put_header(good) + elif kind == JAIL_D: + assert fix_id() == -errno.ENOTSUP + else: + assert fix_id() == -errno.EIO bitmap_first = get32(root_data, 52) bitmap_size = struct.unpack_from("format_plan") +# A2 disk ID repair: a dry run decides first, the volumes are released before +# the raw write, and the adapter writes sector 0 and nothing else. +case = source[source.index("case HOP_DISK_ID_REPAIR:"):] +case = case[:case.index("break;")] +assert case.index("hddFormatDiskId(0") < case.index("releaseForRawWrite()") < case.index("hddFormatDiskId(1") +adapter = (root / "src/hdd_format_ps2.c").read_text() +adapter = adapter[adapter.index("int hddFormatDiskId("):] +adapter = adapter[:adapter.index("\n}\n")] +assert adapter.count("writeDisk(") == 1 and "writeDisk(NULL, 0, 1, sector)" in adapter +assert adapter.index("hddFormatDiskIdFix(") < adapter.index("HF_BEGIN") < adapter.index("writeDisk(") print("PASS: shared create/expand guards in both builds; VMC unmount precedes formatting") diff --git a/tests/test_hdd_partition_rename.py b/tests/test_hdd_partition_rename.py index fddd1c23..eef2eb7f 100644 --- a/tests/test_hdd_partition_rename.py +++ b/tests/test_hdd_partition_rename.py @@ -153,6 +153,7 @@ def function(source, signature): static int runBootFlagJob(int op,int *result){(void)op;(void)result;assert(0);return 0;} static void actEnableBootFlag(void){assert(0);} static void actDpRepair(void){assert(0);} +static void actDiskIdRepair(void){assert(0);} static void dashHddInstallApp(const char *path){(void)path;assert(0);} static void dashHddInstallGame(void){assert(0);} static int dashModalMenu(const char *title,const char *subtitle,const DashMenuItem *items,int n,int initial){