commit 9af765d755cd17ab996c911d926dfe7fa59470cc
Author: mrfox <jens.se@icloud.com>
AuthorDate: Wed Nov 25 19:25:07 2026 +0100
Commit: mrfox <jens.se@icloud.com>
CommitDate: Wed Nov 25 19:25:07 2026 +0100
docs: the wiki (docs/wiki): what we learned porting FAKE-08
Getting started, toolchain and ABI, video (black screen, LUT, 0x60EC,
native resolution, fast blits), the Guide, audio and latency, input, files
(FAT32 USB listing bug), time (49.875 MHz), crashes, Xenia vs. hardware,
pitfalls, a porting guide and sources.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
README.md | 6 +-
docs/wiki/Audio.md | 71 +++++++++++++++++++
docs/wiki/Crashes-and-Debugging.md | 66 ++++++++++++++++++
docs/wiki/Files-and-Storage.md | 54 ++++++++++++++
docs/wiki/Getting-Started.md | 66 ++++++++++++++++++
docs/wiki/Home.md | 42 +++++++++++
docs/wiki/Input.md | 26 +++++++
docs/wiki/Pitfalls.md | 63 +++++++++++++++++
docs/wiki/Porting-Guide.md | 99 ++++++++++++++++++++++++++
docs/wiki/Sources.md | 12 ++++
docs/wiki/The-Guide.md | 52 ++++++++++++++
docs/wiki/Time.md | 30 ++++++++
docs/wiki/Toolchain-and-ABI.md | 103 +++++++++++++++++++++++++++
docs/wiki/Video.md | 139 +++++++++++++++++++++++++++++++++++++
docs/wiki/Xenia-vs-Hardware.md | 33 +++++++++
15 files changed, 859 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index d0cfeb2..d2be0f0 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ xexkit is a small C/C++ runtime and build setup:
It came out of porting [FAKE-08](https://github.com/jtothebell/fake-08), a
PICO-8 emulator, to the console, and every behaviour it relies on was checked
-on real hardware. The [wiki](../../wiki) records what was learned and why the
+on real hardware. The [wiki](docs/wiki/Home.md) (in `docs/wiki/`) records what was learned and why the
code looks the way it does.
## What a title gets
@@ -71,7 +71,7 @@ include $(XEXKIT)/mk/xexkit.mk
`make` gives `build/mygame/default.xex`, with `app.elf` next to it for
`xenon-addr2line`. See [mk/xexkit.mk](mk/xexkit.mk) for the options, and the
-wiki's [Porting guide](../../wiki/Porting-Guide) for a whole port.
+wiki's [Porting guide](docs/wiki/Porting-Guide.md) for a whole port.
## Hardware tests
@@ -85,7 +85,7 @@ wiki's [Porting guide](../../wiki/Porting-Guide) for a whole port.
The tests also start in [Xenia Canary](https://github.com/xenia-canary/xenia-canary),
but Xenia has no display controller and differs from the console in several
-ways; see the wiki's [Xenia vs. hardware](../../wiki/Xenia-vs-Hardware) page.
+ways; see the wiki's [Xenia vs. hardware](docs/wiki/Xenia-vs-Hardware.md) page.
## Layout
diff --git a/docs/wiki/Audio.md b/docs/wiki/Audio.md
new file mode 100644
index 0000000..3c82a7f
--- /dev/null
+++ b/docs/wiki/Audio.md
@@ -0,0 +1,71 @@
+# Audio
+
+## The render driver
+
+A title plays sound as a client of the kernel's audio render driver:
+
+```c
+XAUDIORENDERDRVCLIENT client = { callback, context };
+XAudioRegisterRenderDriverClient(&client, &driver);
+// the kernel then calls callback(&data) every 5.33 ms; in it:
+XAudioSubmitRenderDriverFrame(driver, frame);
+```
+
+These facts are confirmed on hardware, by xsdk and by us:
+
+- The callback runs on a **kernel thread** (hardware thread 4), **187.5 times
+ a second**: one frame per 256 samples at 48 kHz. Our log shows 187/s
+ steadily.
+- A frame is **6 channels x 256 big-endian floats**, one channel after the
+ other: front left, front right, centre, LFE, back left, back right. The same
+ layout works with the console set to stereo or to 5.1.
+- Frames live in **cached physical memory** (`MmAllocatePhysicalMemoryEx(0,
+ size, PAGE_READWRITE, 0, 0xFFFFFFFF, 0)`).
+- The callback may submit straight away. It should use **integers only** and
+ return fast.
+- It is called with the console ABI, so wrap it with `xbox360_entry` (see
+ [Toolchain and ABI](Toolchain-and-ABI.md)).
+- `NtSetEvent` on a title's handle fails from the callback (a different
+ process context); `KeSetEvent` on the referenced object works.
+
+## xexkit's API
+
+`xex_audio.h` keeps a 16-frame ring. The callback takes the oldest frame, or
+a silent one when the ring is empty:
+
+```c
+xex_audio_open();
+while (xex_audio_queued() < N) {
+ float *f = xex_audio_next(); // 6 x 256 floats, other channels silent
+ // f[0..255] front left, f[256..511] front right
+ xex_audio_queue();
+}
+```
+
+`xex_audio_callbacks()` and `xex_audio_underruns()` count the driver's calls
+and the silent frames.
+
+## Latency
+
+The system's own delay is about 21 ms: Xbox 360 games report 1024 samples
+through XAudio2, or 512 in low-latency mode. A title adds its queue on top.
+
+- **Short queues crackle.** If the program fills once per 16.7 ms video frame,
+ each fill must cover more than 3 audio frames, so a queue of 2-4 runs dry
+ and the driver plays silence. Our test heard it as "raspy" at 2.
+- **Fill several times a frame.** FAKE-08 makes core audio before the vblank
+ wait, after the flip, and in 4 ms slices of its timer waits. Then 5 frames
+ (27 ms) never ran dry. Before that it queued 8 frames, made once a frame
+ after the vblank wait, and the delay was noticeable.
+- For reference, RetroArch defaults to 64 ms. Broadcast standards call audio
+ late by about 125 ms detectable.
+
+`tests/audio` plays a click and a white flash in the same frame every second.
+Up/down set the queue depth, so you can judge the delay by eye and ear.
+
+## Resampling
+
+PICO-8 makes 22050 Hz mono. FAKE-08 resamples linearly to 48 kHz and writes
+the same samples to front left and front right. That costs about 4-5 ms of CPU
+per frame in its first form; doubles in the inner loop are slow on the
+in-order core, so prefer integer or float steps.
diff --git a/docs/wiki/Crashes-and-Debugging.md b/docs/wiki/Crashes-and-Debugging.md
new file mode 100644
index 0000000..875993e
--- /dev/null
+++ b/docs/wiki/Crashes-and-Debugging.md
@@ -0,0 +1,66 @@
+# Crashes and debugging
+
+## What a crash looks like
+
+**With no handler**, a CPU fault (bad pointer, misaligned access in
+write-combined memory, illegal instruction) gives a black screen. Within 1-2 s
+the console is back in the dashboard. Nothing is logged.
+
+**A stack overflow hangs the console** whether there is a handler or not: the
+kernel puts the exception record on the overflowed stack. Hold the power
+button.
+
+## crash.txt
+
+xexkit installs a vectored exception handler before the constructors run
+(`RtlSetVectoredExceptionHandler`, ordinal 0x36D, the handler passed as both
+arguments; xsdk found this on hardware). For a fault in the title's own code
+it writes `game:/crash.txt`, then ends the title:
+
+```
+FAKE-08 XEX crash: access violation (code c0000005) at 820876b0
+ read of address f687cc9a
+IAR 820876b0 LR 82085bf8 CTR 00000000 CR 44000244 XER 00000000
+r0 ...
+stack:
+ 82085bf8
+ 8203add0
+ ...
+```
+
+Look the addresses up with the ELF of **the same build**:
+
+```sh
+docker run --rm -v $PWD:/src -w /src free60/libxenon:latest \
+ xenon-addr2line -f -C -e build/mygame/app.elf 820876b0 82085bf8 8203add0
+```
+
+The context layout (xsdk's probe): IAR at +0x08, LR at +0x0C, CTR at +0x10,
+r0-r31 as 64-bit values from +0x18, CR at +0x118, XER at +0x11C.
+
+Faults outside the title's code are passed on (return 0). The handler is
+called with the console ABI, so it goes through `xbox360_entry`. **Keep the
+handler simple:** our first version also showed a notification and slept,
+and it froze the console after writing the report.
+
+## Logging
+
+- `DbgPrint` output (stdout/stderr go there) shows in Xenia's log with
+ `--log_level=4`. On a retail console nothing reads it.
+- **Write a log file and close it after every line** (`fopen("a")` …
+ `fclose`), so a crash or hang can't lose it. Fetch it over FTP.
+- **Log the build id and time on the first line.** It is the only way to be
+ sure the console runs the build you think it runs; see [Pitfalls](Pitfalls.md).
+
+## Finding hardware-only bugs
+
+Our approach, which found the black screen, the LUT and the USB bug:
+
+1. A small test XEX that logs every step to `game:/...-log.txt`.
+2. Dump the registers or state involved before and after each step.
+3. Try one change per run, or several in timed phases ("phase 2 at 6 s: …"),
+ and have the person at the TV report when the picture changed.
+4. Compare with what Xenia, libxenon and xsdk say. Xenia is not the console;
+ see [Xenia vs. hardware](Xenia-vs-Hardware.md).
+5. A capture card or a camera pointed at the TV helps. So does a test that
+ makes timing visible, like the flash and click of `tests/audio`.
diff --git a/docs/wiki/Files-and-Storage.md b/docs/wiki/Files-and-Storage.md
new file mode 100644
index 0000000..4b68c27
--- /dev/null
+++ b/docs/wiki/Files-and-Storage.md
@@ -0,0 +1,54 @@
+# Files and storage
+
+## Paths
+
+| xexkit path | Kernel device | What |
+|---|---|---|
+| `game:/` | set up by the loader | the folder the XEX was started from (writable on the console) |
+| `hdd:/` | `\Device\Harddisk0\Partition1` | the hard disk, Aurora's `Hdd1:` |
+| `usb0:/`-`usb2:/` | `\Device\Mass0`-`2` | USB drives (FAT32 or FATX) |
+
+`xex_mount_devices()` creates the links with `ObCreateSymbolicLink` as
+`\??\name:`. `xex_kernel_path()` turns `usb0:/a/b` into `\??\usb0:\a\b`.
+Relative paths are under `game:`. Both `/` and `\` work.
+
+The rest goes through newlib's reentrant syscalls on `NtCreateFile`,
+`NtReadFile`, `NtWriteFile` and friends, with a 64-entry descriptor table:
+`open`, `read`, `write`, `lseek`, `close`, `stat`, `fstat`, `unlink`, `mkdir`,
+`rmdir`, `opendir`, `readdir`, `closedir`. stdio and iostreams work on top.
+
+## The FAT32 USB listing bug
+
+**A FAT32 USB stick's driver returns one entry per `NtQueryDirectoryFile`
+and leaves `NextEntryOffset` and `FileIndex` unwritten.** Whatever the buffer
+held before stays there. A `readdir` that follows `NextEntryOffset` then walks
+into garbage:
+
+- FAKE-08 died after listing the first cart: an access violation in
+ `readdir`, reading 0xF687CC9A;
+- the hard disk and Xenia list correctly, so nothing showed there.
+
+xexkit clears the buffer before every query and bounds-checks the offset
+(`runtime/fs.c`). xsdk found the same.
+
+## Deleting files
+
+- `NtDeleteFile` fails on the console; xexkit falls back to
+ `NtSetInformationFile(FileDispositionInformation)` on an open handle, then
+ `NtClose`.
+- **A file that's still open can't be deleted**: a sharing violation, which
+ xexkit maps to `EBUSY`. Close every stream first. Our first fs test failed
+ because an `ifstream` was still open.
+
+## Sizes and attributes
+
+`FileStandardInformation` gives the size; `FileNetworkOpenInformation` is the
+fallback. `stat` tries `NtQueryFullAttributesFile` and falls back to opening
+the file and asking the handle.
+
+## Where to keep data
+
+Write settings, saves and logs **next to the XEX** (`game:/yourtitle/`).
+`game:` is read-only in Xenia, so fall back to `hdd:/` or Xenia's writable
+`cache:`. FAKE-08 tries `game:/fake08`, then `hdd:/fake08`, then
+`cache:/fake08`, probing each with a test file.
diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md
new file mode 100644
index 0000000..dbe667a
--- /dev/null
+++ b/docs/wiki/Getting-Started.md
@@ -0,0 +1,66 @@
+# Getting started
+
+## What you need
+
+- A PC with Docker.
+- An RGH/JTAG Xbox 360 with Aurora (or FSD) and its FTP server, plus a
+ controller.
+- Optionally [Xenia Canary](https://github.com/xenia-canary/xenia-canary) for
+ quick smoke tests. See [Xenia vs. hardware](Xenia-vs-Hardware.md) for its
+ limits.
+
+## Build the tools (once)
+
+`xex-link` turns the ELF that GCC links into a XEX. It is built from
+xenon-forge, with a patch that gives the main thread 1 MB of stack instead of
+256 KB:
+
+```sh
+docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp \
+ -e CARGO_HOME=/usr/local/cargo -e RUSTUP_HOME=/usr/local/rustup \
+ -v $PWD:/build_dir rust:latest /bin/sh -e /build_dir/tools/build-xex-link.sh
+```
+
+The compiler comes from the `free60/libxenon` image: `xenon-gcc` and
+`xenon-g++` (GCC 16), newlib and libstdc++ for 32-bit PowerPC. xexkit uses
+the compiler and C/C++ libraries. **libxenon itself is not linked**: titles run
+under the retail kernel, not bare metal.
+
+## Build
+
+```sh
+docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -v $PWD:/src -w /src \
+ free60/libxenon:latest bash -lc make
+```
+
+Always pass `--user $(id -u):$(id -g)`. Otherwise the build directories belong
+to root, and later uploads into them (logs fetched from the console) fail with
+"permission denied". See [Pitfalls](Pitfalls.md).
+
+## Run on the console
+
+1. Make a folder for the title, for example `Hdd1:\Apps\MyTitle\`, and copy
+ `default.xex` into it over FTP.
+2. In Aurora, add the folder (or rescan) and start the title.
+3. Leave through the Guide: press the Xbox button, then choose Xbox Home.
+
+Logs and reports that the runtime writes to `game:/` land in that folder;
+fetch them over FTP.
+
+## A first title
+
+Copy `examples/minimal/`. Its `main.cpp` shows the usual loop:
+
+```cpp
+xex_video_init();
+xex_audio_open();
+for (;;) {
+ xex_pad pad; xex_input_get(0, &pad);
+ // ... fill audio frames while xex_audio_queued() is low
+ xex_frame f = xex_video_begin(); // waits until the last flip is on screen
+ // ... draw into f.pixels with xex_video_tiled_index()
+ xex_video_present(); // flips at the next vertical blank
+}
+```
+
+Next: the [Porting guide](Porting-Guide.md).
diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md
new file mode 100644
index 0000000..17b2c20
--- /dev/null
+++ b/docs/wiki/Home.md
@@ -0,0 +1,42 @@
+# xexkit wiki
+
+xexkit builds native Xbox 360 titles (`default.xex`) with GCC and no Microsoft
+XDK, for RGH/JTAG consoles running Aurora or FSD. These pages hold what we
+found out while porting FAKE-08 (a PICO-8 emulator) to the console. Most of it
+isn't written down anywhere else, so each page says what was seen on the
+console and why the runtime does what it does.
+
+## Pages
+
+| Page | About |
+|---|---|
+| [Getting started](Getting-Started.md) | Build the tools, build a title, run it on the console |
+| [Toolchain and ABI](Toolchain-and-ABI.md) | GCC flags, the console calling convention, the link script, the stack, C++ start-up |
+| [Video](Video.md) | Getting a picture on screen at all, then sharp at 1080p: the LUT, the 0x60EC commit, the scaler, tiling, fast blits |
+| [The Guide](The-Guide.md) | Making the Xbox button's Guide show over a title, and ending safely |
+| [Audio](Audio.md) | The kernel's render driver, the frame format, latency |
+| [Input](Input.md) | Controllers through XAM |
+| [Files and storage](Files-and-Storage.md) | Paths, devices, the FAT32 USB listing bug, deleting files |
+| [Time](Time.md) | The 49.875 MHz time base, sleeping, frame pacing |
+| [Crashes and debugging](Crashes-and-Debugging.md) | `crash.txt`, addr2line, logging, diagnosing on hardware |
+| [Xenia vs. hardware](Xenia-vs-Hardware.md) | What Xenia Canary does differently |
+| [Pitfalls](Pitfalls.md) | Mistakes that cost us hours: stale copies, FTP, Docker, screenshot plugins |
+| [Porting guide](Porting-Guide.md) | Porting a program, with FAKE-08 as the worked example |
+| [Sources](Sources.md) | Where the knowledge comes from |
+
+## The short version
+
+1. A title's surface only reaches the screen once the **display LUT is
+ filled** and the surface is **committed through 0x60EC**, as XAM does it.
+ VdSwap alone, VdSetDisplayMode and VdTurnDisplayOn do nothing for it.
+2. For a sharp picture, make the front buffers the **output's size** and turn
+ the **scaler off**. The kernel's 640x480 surface is stretched and blurred.
+3. **Swap every frame with VdSwap** and show XAM's surface when VdSwap hands it
+ back. Otherwise the Guide never appears.
+4. The **time base runs at 49.875 MHz**, not the 50 MHz the kernel reports.
+5. **Clear the buffer before every `NtQueryDirectoryFile`.** A FAT32 USB
+ stick's driver doesn't write `NextEntryOffset`.
+6. Functions the **kernel calls back** (audio, exceptions) must keep r14-r31
+ whole in 64 bits.
+7. **Never let a title end by itself while the Guide is open.** The console
+ hangs.
diff --git a/docs/wiki/Input.md b/docs/wiki/Input.md
new file mode 100644
index 0000000..d135acf
--- /dev/null
+++ b/docs/wiki/Input.md
@@ -0,0 +1,26 @@
+# Input
+
+`XamInputGetState(port, XINPUT_FLAG_GAMEPAD, &state)` (xam ordinal 0x191)
+returns the controller state for ports 0-3:
+
+- Buttons are a bit mask: up 0x1, down 0x2, left 0x4, right 0x8, start 0x10,
+ back 0x20, stick clicks 0x40/0x80, LB 0x100, RB 0x200, A 0x1000, B 0x2000,
+ X 0x4000, Y 0x8000.
+- Triggers run 0-255; sticks are signed 16-bit over the full range. Y points
+ up.
+- A disconnected port returns an error, and xexkit zeroes the state.
+- While the Guide is open, XAM keeps the controllers and they read as
+ released.
+
+`xex_input_get(port, &pad)` in `xex_input.h` wraps this; `XEX_PAD_*` are the
+bits.
+
+Notes from FAKE-08:
+
+- **Back+Start** is a screenshot hotkey on consoles with some dashboard
+ plugins, so the title never sees it held. Use the Guide for leaving.
+- Xbox players expect **A to confirm and B to go back**. If a program's own
+ layout maps them differently, as PICO-8's O/X do, choose the confirm
+ button per layout.
+- The test `tests/video` logs every button, trigger and stick change with
+ names. Use it to check a controller mapping.
diff --git a/docs/wiki/Pitfalls.md b/docs/wiki/Pitfalls.md
new file mode 100644
index 0000000..6103b9c
--- /dev/null
+++ b/docs/wiki/Pitfalls.md
@@ -0,0 +1,63 @@
+# Pitfalls
+
+These cost us the most time, and none of them were in the code.
+
+## The console runs an old copy
+
+We spent a long time chasing a "missing" feature that was in the build all
+along: Aurora was starting an older `default.xex` than the one we uploaded.
+
+- **Log the build id and build time on the first line**, for example with
+ `-DBUILD_ID=\"$(git rev-parse --short HEAD)\"` and `__DATE__ __TIME__`.
+ Check that line before testing anything else.
+- **Delete the old `default.xex` before uploading** the new one, and check
+ the size in the FTP listing. Don't rely on the size alone, though: two
+ builds can be the same size.
+- A title writes its data **next to itself**. If you fetch the log from
+ `X:\...\MyTitle\data\`, the XEX that ran is `X:\...\MyTitle\default.xex`.
+
+## Docker makes root-owned folders
+
+Without `--user $(id -u):$(id -g)`, the build directories belong to root, and
+an FTP client can't save the console's logs into them ("permission denied").
+Fix existing ones with
+`docker run --rm -v $PWD:/x free60/libxenon chown -R $(id -u):$(id -g) /x/build`.
+In containers run as your user, set `HOME=/tmp`, and add
+`git config --global --add safe.directory /src` if the build calls git.
+
+## Back+Start is taken
+
+Some dashboard plugins use Back+Start as a screenshot hotkey, so the title
+never sees it. Leave through the Guide.
+
+## Ending under the Guide hangs
+
+See [The Guide](The-Guide.md). Don't quit on a timer while the Guide is open.
+
+## Kernel callbacks and 64-bit registers
+
+The audio callback, the exception handler and the entry point must keep
+r14-r31 whole. GCC's 32-bit prologues don't. Use `xbox360_entry`.
+
+## Unwritten fields from drivers
+
+The FAT32 USB listing bug ([Files and storage](Files-and-Storage.md)) generalises:
+**clear output buffers before kernel calls fill them**, and bounds-check any
+offset they return.
+
+## Misaligned 64-bit stores into write-combined memory
+
+They fault on the console. GCC may merge two 32-bit stores into one `std`.
+Write GPU-visible memory (rings, front buffers) through `volatile uint32_t*`
+or in aligned blocks.
+
+## Assumptions that were wrong
+
+- "Xenia works, so the console will": see [Xenia vs. hardware](Xenia-vs-Hardware.md).
+- "The kernel's scaler program is needed for a picture": it hangs, and isn't
+ needed.
+- "`XNotifyQueueUICustom` (656) shows a notification": ordinal 656 is
+ `XNotifyQueueUI`, with 5 arguments (type, user, areas as one 64-bit
+ register, text, context).
+- "The delay is in the TV": it was our own queue. Measure before blaming the
+ output.
diff --git a/docs/wiki/Porting-Guide.md b/docs/wiki/Porting-Guide.md
new file mode 100644
index 0000000..bbbc5c4
--- /dev/null
+++ b/docs/wiki/Porting-Guide.md
@@ -0,0 +1,99 @@
+# Porting guide
+
+How to bring an existing C/C++ program to the console with xexkit. FAKE-08
+(PICO-8 emulator, C++ plus Lua) is the worked example; its host is
+`platform/xex/source/XexHost.cpp` in the [fake-08-xbox360](https://git.kristoffersson.info/repos/fake-08-xbox360.git) repository.
+
+## 1. Build it
+
+Add xexkit as a submodule and write a Makefile (see `examples/minimal`):
+
+```make
+XEXKIT := $(CURDIR)/xexkit
+TITLE := mygame
+TITLE_SRC := $(wildcard ../../src/*.cpp) $(wildcard ../../lib/*.c) source/MyHost.cpp
+TITLE_TOML := mygame.toml
+TITLE_FLAGS := -I../../src -DMY_PLATFORM_XEX
+TITLE_C_AS_CXX := 1 # only if C++ exceptions pass through C code (Lua)
+all: title
+include $(XEXKIT)/mk/xexkit.mk
+```
+
+Typical compile problems:
+
+- **Missing POSIX bits:** xexkit has `open`/`read`/`opendir`/`stat` and so on.
+ `chdir`, `getcwd`, sockets and threads aren't there yet.
+- **`getopt` and `argv`:** `main` gets `argc = 1`, `argv[0] = "game:\default.xex"`.
+- **Headers clashing with newlib's types** (for example XAM's networking
+ header): declare the few functions you need yourself.
+- **Lua and exceptions:** z8lua throws C++ exceptions through its C sources,
+ so they must be compiled as C++.
+
+## 2. Platform layer
+
+Most programs already have a platform or host layer (SDL, a console port).
+Copy the simplest one and replace:
+
+| Program needs | xexkit |
+|---|---|
+| a framebuffer | `xex_video_begin()` → draw → `xex_video_present()` |
+| vsync | built into `xex_video_begin()` |
+| sound | `xex_audio_next()`/`xex_audio_queue()` |
+| input | `xex_input_get()` for ports 0-3 |
+| timing | `xex_timebase()` / `xex_timebase_freq()`, `xex_sleep_ms()` |
+| files | ordinary stdio/POSIX on `game:/`, `hdd:/`, `usb0:/` |
+| quitting | return from `main` (back to the dashboard) |
+
+## 3. Video
+
+- Ask for the window size after `xex_video_init()` (`xex_video_begin()`
+ returns it). Expect 1920x1080 on a 1080p TV, or 640x480 in Xenia and on
+ interlaced outputs.
+- Scale by an integer factor yourself for pixel art: 128 x 8 = 1024 fits
+ 1080. Keep 1:1 pixels; the output is square-pixel at the native size.
+- Make the blit fast: see "Drawing fast into write-combined memory" in
+ [Video](Video.md). The first FAKE-08 blit (11 ms) dropped Celeste to 41 fps.
+- Clear the whole buffer (both buffers, so twice) when the layout changes;
+ the two front buffers alternate.
+- Draw overlays (FPS counters) **every frame**, for the same reason.
+
+## 4. Audio
+
+- Resample to 48 kHz floats.
+- **Fill several times a frame**, before and after the vblank wait. Keep
+ 5 frames (27 ms) queued; see [Audio](Audio.md).
+- If the program pulls audio in its main loop after drawing, as FAKE-08's core
+ did, do the filling from the host instead (FAKE-08's `audioTopUp`) and
+ tell the core not to.
+
+## 5. Input
+
+Map A to confirm and B to back. Read all four ports for multiplayer.
+
+## 6. Files
+
+- Put the program's data next to the XEX: FAKE-08 uses `game:/roms` for
+ carts and `game:/fake08` for settings, saves and its log.
+- Make data folders on first start (`mkdir`).
+- Fall back to a writable place when `game:` is read-only (Xenia).
+
+## 7. Robustness
+
+- Keep `crash.txt` working: it found FAKE-08's USB bug in one run.
+- Log the build id first; see [Pitfalls](Pitfalls.md).
+- Never quit by yourself while the Guide shows (`xex_video_guide_visible()`).
+- A performance overlay, with emulation, blit and wait times and late frames,
+ logged every few seconds, answers "why does it stutter" without guessing.
+
+## 8. Test on the console
+
+Xenia for "does it start", the console for everything else. Run the program
+with the performance overlay on, try the Guide, leave through Xbox Home, and
+check that the dashboard comes back normally.
+
+## FAKE-08's numbers on a 1080p TV
+
+- **Video:** 1920x1080 native, 8x scaling (1024x1024), 60 fps, no late frames
+ in Celeste once the blit was fast.
+- **Audio:** queue 5 frames, no underruns while playing.
+- **Emulation:** 0.6-6 ms per frame, depending on the cart.
diff --git a/docs/wiki/Sources.md b/docs/wiki/Sources.md
new file mode 100644
index 0000000..e99335e
--- /dev/null
+++ b/docs/wiki/Sources.md
@@ -0,0 +1,12 @@
+# Sources
+
+| Source | What we took from it |
+|---|---|
+| [xenon-forge](https://github.com/landaire/xenon-forge) (MIT/Apache-2.0) | `xex-link`, the kernel/XAM headers and import thunks (`sdk/`), the entry macro, the GPU ring and flip code (`xbox360-video`, ported to C) |
+| [xsdk](https://github.com/jessenic/xsdk) (MIT), `docs/HARDWARE.md` | the LUT and 0x60EC commit, 1:1 scaler values, the Guide through `VdSwap` and event 1, the audio frame format and callback, the vectored exception handler and context layout, the 49.875 MHz time base, the FAT32 USB listing bug, ending under the Guide |
+| [Xenia](https://github.com/xenia-project/xenia) / [Xenia Canary](https://github.com/xenia-canary/xenia-canary) (BSD) | export ordinals (`xboxkrnl_table.inc`), structure layouts (`X_VIDEO_MODE`, filter parameters, exception record), how `VdSwap` and the audio system behave |
+| [libxenon](https://github.com/Free60Project/libxenon) | display register names and values (`xenos.c`), the tiled framebuffer layout, the LUT autofill |
+| [Microsoft XAudio2 documentation](https://learn.microsoft.com/windows/win32/api/xaudio2/ns-xaudio2-xaudio2_performance_data) | the Xbox 360 audio quantum and reported latency (public documentation, no SDK material) |
+| Our own hardware runs | everything in these pages marked as seen on the console: the black-screen experiments, the hang in `VdInitializeScalerCommandBuffer`, the blit timings, the audio latency test, the stale-copy and Back+Start traps |
+
+No Microsoft XDK code, headers or tools are used in xexkit.
diff --git a/docs/wiki/The-Guide.md b/docs/wiki/The-Guide.md
new file mode 100644
index 0000000..4386111
--- /dev/null
+++ b/docs/wiki/The-Guide.md
@@ -0,0 +1,52 @@
+# The Guide
+
+Players leave a title the way they leave any game: Xbox button, then Xbox
+Home. That needs the title's help.
+
+## What the title has to do
+
+1. **Swap every frame with `VdSwap`**, passing the system command buffer
+ from `VdGetSystemCommandBuffer`. While the Guide is open, `VdSwap` puts an
+ indirect call to XAM's drawing commands into the title's ring.
+2. **Give `VdSwap` real outputs.** Its last five arguments are pointers to
+ the front buffer address, format, colour space, width and height.
+ Initialise them with your own buffer (virtual address, 6 = k_8_8_8_8, 0 =
+ RGB, its size). While XAM draws the Guide, `VdSwap` replaces them with
+ **XAM's surface** (we saw 852x480 at 0x01C19000, pitch 864).
+3. **Show XAM's surface instead of yours** on those frames:
+ - skip your own scanout write;
+ - set the scaler for its size, filling the output;
+ - commit it through 0x2840/0x2844/D1GRPH and 0x60EC;
+ - after it closes, put your own scaler values back.
+4. **Tell XAM the title's display** once, with graphics notification event 1,
+ as Direct3D does:
+ ```c
+ struct { uint16_t front_w, front_h, out_w, out_h;
+ uint32_t left, top, right, bottom; // 0, 0, front_w, front_h
+ uint32_t scaled_w, scaled_h; // the output
+ uint32_t filters[8]; } d; // 0: defaults
+ VdCallGraphicsNotificationRoutines(1, &d);
+ ```
+ Without it, XAM draws the game under the Guide as the top-left 640x480,
+ zoomed.
+
+xexkit's `video.c` does all of this. In our test, the Guide was open for 557
+frames and the title's picture came back after it closed.
+
+## Pacing while the Guide shows
+
+Frames that show XAM's surface don't latch at vertical blank. Unpaced, our
+loop ran at about 380 fps under the Guide, and Celeste kept playing at 6x
+speed. xexkit holds those frames to 60 a second with the time base.
+
+## Ending
+
+- **Never end the title by itself while the Guide is open.** XAM's Guide
+ thread waits for a swap fence that never comes, and the console hangs
+ (xsdk's finding). Check `xex_video_guide_visible()` before ending on a
+ timer or a key combination.
+- **Xbox Home** ends the title while it is still swapping, which is safe.
+- **Back+Start** is often taken by dashboard plugins (a screenshot hotkey on
+ our console), so don't rely on it as the only way out.
+
+XAM keeps the controllers while the Guide is open, so input reads as released.
diff --git a/docs/wiki/Time.md b/docs/wiki/Time.md
new file mode 100644
index 0000000..f0a3cb6
--- /dev/null
+++ b/docs/wiki/Time.md
@@ -0,0 +1,30 @@
+# Time
+
+## The time base runs at 49.875 MHz
+
+`mftb` counts at the CPU clock / 64 = **49.875 MHz**.
+`KeQueryPerformanceFrequency` reports 50 MHz, which would put everything
+0.25% off. xsdk measured this against the 60 Hz display (16,625 time base
+ticks at "50 MHz" per frame = 16,667 µs at 49.875 MHz).
+`xex_timebase_freq()` returns 49,875,000.
+
+Xenia runs its time base at 50 MHz, so times there read 0.25% long.
+
+## Wall clock, clock(), sleeping
+
+- `gettimeofday` and `time()` come from `KeQuerySystemTime`.
+- `clock()` and `times()` count the time base.
+- `xex_sleep_ms` and `usleep` use `KeDelayExecutionThread`. The kernel's
+ sleep can end a little early, so spin for the last millisecond when timing
+ frames.
+
+## Frame pacing
+
+- **60 fps:** let the display pace you. `xex_video_begin()` waits until the
+ previous flip is on screen, so draw-then-present runs at the refresh rate.
+ An FPS counter over a "second" shows 60 or 61, depending on the window
+ edges.
+- **30 fps and others:** sleep to a time base target. Sleep in short slices
+ if audio has to be refilled meanwhile; see [Audio](Audio.md).
+- **Under the Guide**, frames don't latch at vertical blank; see
+ [The Guide](The-Guide.md).
diff --git a/docs/wiki/Toolchain-and-ABI.md b/docs/wiki/Toolchain-and-ABI.md
new file mode 100644
index 0000000..3658776
--- /dev/null
+++ b/docs/wiki/Toolchain-and-ABI.md
@@ -0,0 +1,103 @@
+# Toolchain and ABI
+
+## Compiler flags
+
+```
+-m32 -mpowerpc64 -mhard-float -maltivec -fno-pic -G0 -msdata=none
+```
+
+- **`-m32 -mpowerpc64`:** titles run with 32-bit pointers in 64-bit
+ registers. The code is 32-bit SysV PowerPC, which may use 64-bit
+ instructions.
+- **`-fno-pic -G0 -msdata=none`:** no small-data sections and no PIC. The XEX
+ is loaded at a fixed address (0x82000000, code from 0x82010000).
+- Use `-ffunction-sections -fdata-sections` together with `--gc-sections`.
+ The link script keeps `.ctors`, `.eh_frame` and the import sections.
+
+## Calling the kernel: the console ABI
+
+The kernel and XAM use the console's own calling convention, which differs
+from SysV in ways that matter:
+
+| | SysV (our code) | Console (kernel, XAM) |
+|---|---|---|
+| r14-r31 | callee saves the low 32 bits | callee must keep all 64 bits |
+| Arguments 9+ | 4-byte slots at 8(r1) | 8-byte slots from 0x50 of the caller's frame |
+| Home area | none | 0x50 bytes the callee may store r3-r10 in |
+| 64-bit argument | two registers | one register |
+
+xenon-forge's import thunks (`sdk/thunks`) translate calls into the kernel.
+Functions with more than 8 arguments need a hand-written stub: see
+`VdSwap` (10 arguments) in `sdk/thunks/ppc32.S` and
+`VdInitializeScalerCommandBuffer` (12) in `runtime/extra_imports.S`:
+
+```asm
+xbox360_frame 0x70
+li 12, 0; stw 12, 0x50(1) ; argument 9, high word 0
+lwz 11, 0x78(1); stw 11, 0x54(1) ; ... low word from the SysV slot
+...
+```
+
+A 64-bit argument goes in a single register. `XNotifyQueueUI`'s `Areas`
+argument is one, so the text pointer moves to r6.
+
+### The kernel calling back into the title
+
+The **title's entry point**, the **audio render-driver callback** and the
+**vectored exception handler** are all called by the kernel with the console
+ABI. GCC's prologues save only the low words of r14-r31, so the kernel would
+get corrupted registers back. Wrap these functions in `xbox360_entry`
+(`sdk/crt/entry.inc`), which saves r14-r31 with `std`/`ld` and reserves the
+home area. See `runtime/kernel_entries.S`.
+
+## Imports
+
+An import is a 16-byte thunk whose first word is
+`type << 24 | library << 16 | ordinal`, with library 0 = xboxkrnl and
+1 = xam. Add a missing one with `xbox360_stub Name, 0x0100xxxx` in
+`runtime/extra_imports.S`. Xenia's `xboxkrnl_table.inc` and `xam_table.inc`
+list the ordinals.
+
+Ordinals we needed beyond xenon-forge's headers:
+
+| Function | Record |
+|---|---|
+| `XNotifyQueueUI` (5 arguments, not `XNotifyQueueUICustom`) | 0x01010290 |
+| `VdQueryVideoMode` | 0x010001ca |
+| `VdInitializeScalerCommandBuffer` | 0x010001c5 |
+| `VdCallGraphicsNotificationRoutines` | 0x010001b1 |
+| `RtlSetVectoredExceptionHandler` | 0x0100036d |
+
+## Link script and C++ start-up
+
+`runtime/link.ld` places text, rodata+`.eh_frame`, data (with
+`__CTOR_LIST__`/`__CTOR_END__`) and bss in separate 64 KB pages. `crt.c`, in
+order:
+
+1. installs the fault handler (see [Crashes and debugging](Crashes-and-Debugging.md));
+2. registers `.eh_frame` with `__register_frame`, so C++ exceptions work;
+3. mounts the devices;
+4. runs `.ctors` **from the end towards the start**, as GCC expects;
+5. calls `main(1, {"game:\\default.xex"})`, then `exit()`, which ends in
+ `XamLoaderTerminateTitle`, back to the dashboard.
+
+The `.eh_frame` section has to be zero-terminated, and code that C++
+exceptions pass through has to be compiled as C++. Lua's C sources, for
+example, are built with `-x c++` when Lua errors are C++ exceptions.
+
+## Stack
+
+xex-link writes the main thread's stack size into the PE header, and the
+kernel uses it. Upstream writes 256 KB. Lua and emulator cores recurse deeper
+than that, and a **stack overflow hangs the console** without any report, so
+`tools/build-xex-link.sh` patches it to 1 MB. `tests/hello` recurses 896 KB
+deep to check it.
+
+Keep big arrays off the stack anyway: make them `static`, or put them on the
+heap.
+
+## Heap
+
+`malloc` comes from newlib's `_sbrk_r` over a 96 MB `.bss` arena
+(`XEX_HEAP_SIZE` in `runtime/sys.c`). Physical memory for the GPU and audio
+comes from `MmAllocatePhysicalMemoryEx`.
diff --git a/docs/wiki/Video.md b/docs/wiki/Video.md
new file mode 100644
index 0000000..0063a36
--- /dev/null
+++ b/docs/wiki/Video.md
@@ -0,0 +1,139 @@
+# Video
+
+This is the hardest part, and the one with the least public information. The
+picture took six attempts on hardware before it showed.
+
+## The path
+
+1. `VdInitializeEngines(0, NULL, NULL, NULL, NULL)` gives the GPU's command
+ processor to the title, with the kernel's own microcode. This is what
+ Direct3D does.
+2. A command ring of the title's own (`VdInitializeRingBuffer`, read-pointer
+ write-back, `VdSetSystemCommandBufferGpuIdentifierAddress` for the swap
+ fence). This is ported from xenon-forge's `xbox360-video`.
+3. `VdRetrainEDRAM` at init and after swaps, as Direct3D does.
+4. **The display LUT gets filled** with an identity ramp (see below).
+5. Two front buffers in physical memory (write-combined), tiled 32 bpp.
+6. Each frame: draw into the back buffer, then put into the ring a scanout
+ write plus the 64 dwords `VdSwap` writes. The fence `VdSwap` places tells
+ when the GPU got there.
+7. **After the flip has latched**, commit the surface through 0x60EC (see
+ below).
+
+## Why the screen stays black
+
+Everything above, minus the last two points, makes the registers point at the
+title's buffer (`D1GRPH_PRIMARY_SURFACE_ADDRESS` = 0x6110, the detiler base
+0x2840), latching at 60 fps. **The TV still shows black.** These were tried
+on hardware and **do nothing** for it:
+
+- the kernel's scaler program (`VdInitializeScalerCommandBuffer`), which
+ **hangs** the title with the arguments Direct3D passes;
+- `VdSetDisplayMode(0x40000000)`;
+- `VdTurnDisplayOn(0)`;
+- an alpha of 0xFF in the pixels;
+- the colour matrix (it already held libxenon's RGB values).
+
+What works, as [xsdk](https://github.com/jessenic/xsdk) found and we
+confirmed:
+
+1. **The LUT.** While a title runs, the display's LUT is all zero, which maps
+ every colour to black. Fill it with libxenon's autofill:
+ ```c
+ DC_LUTA_CONTROL (0x64C0) = 0; DC_LUT_RW_INDEX (0x6488) = 0;
+ DC_LUT_RW_MODE (0x6484) = 0; DC_LUT_WRITE_EN_MASK (0x649C) = 7;
+ DC_LUT_AUTOFILL (0x64A0) = 1; wait until 0x64A0 & 2
+ ```
+2. **The commit, as XAM does it.** Write the surface into 0x2840 (address) and
+ 0x2844 (pitch) and into D1GRPH (0x6110 address, 0x6120 pitch, 0x6134 x end,
+ 0x6138 y end). Then set **0x60EC (`D1CRTC_DOUBLE_BUFFER_CONTROL`) = 1**;
+ the display takes the surface and clears it again. Write 0 afterwards.
+
+GPU registers are at `0x7FC80000 + index * 4`, with index = byte offset / 4.
+
+Whether a display controller is there at all shows in the autofill: on a
+console it finishes, in Xenia it never does. xexkit uses the register path
+only when it finishes. Writing 0x6110 from the CPU in Xenia turns its picture
+white.
+
+## Sharp at 1080p: native surface, scaler off
+
+`VdGetCurrentDisplayInformation` reports a **640x480** surface to a starting
+title, whatever the output is. Kept like that, the display scaler stretches
+640x480 to the output (1920x1080): blurry, and 4:3 pulled to 16:9.
+
+xexkit instead asks `VdQueryVideoMode` for the output (width, height,
+interlaced at words 0-2). On a progressive output it makes the front buffers
+the output's size and writes the scaler registers for 1:1 (scaler off), as
+libxenon does:
+
+| Register | Value for w x h |
+|---|---|
+| 0x6590 scaler enable | 0 when the scale is 1:1 |
+| 0x6594 tap control | 0x101 |
+| 0x6584 viewport size | w << 16 \| h |
+| 0x65E8 | w / 4 - 1 |
+| 0x65B0 / 0x65C0 filter control | kernel's value \| 0x100 |
+| 0x65B4 / 0x65C4 scale (8.24) | source / output |
+| 0x65B8 / 0x65C8 phase | (3 << 15) + (scale >> 9) |
+
+Write them between 0x65CC = 0x10000 (update lock) and 0x65CC = 0. Save the
+kernel's values at init and put them back at exit, and after the Guide (see
+[The Guide](The-Guide.md)). Interlaced outputs (1080i) keep the kernel's
+surface.
+
+## Pixels and tiling
+
+A front buffer is tiled in 32x32-pixel tiles of 4 KB, the same layout as
+libxenon's console:
+
+```c
+index = (((y >> 5) * 32 * pitch + ((x >> 5) << 10)
+ + (x & 3) + ((y & 1) << 2) + (((x & 31) >> 2) << 3) + (((y & 31) >> 1) << 6))
+ ^ ((y & 8) << 2));
+```
+
+A pixel word is `B << 24 | G << 16 | R << 8 | A`. The display reads
+0xAARRGGBB little-endian. Use `xex_video_rgb(r, g, b)`.
+
+The fetch constant handed to `VdSwap` holds the buffer's **virtual** address.
+`VdSwap` makes it physical. Addresses in the 0xE0000000+ window map to
+physical memory with a 0x1000 offset; `MmGetPhysicalAddress` handles it.
+
+## Drawing fast into write-combined memory
+
+Front buffers are write-combined: stores are fast only in address order. At
+1080p a per-pixel `pixels[tiled_index(x, y)] = c` loop took **11.4 ms** for
+a 1080x1080 image, too slow next to a game's own work. Two things fix it:
+
+1. **Scale each source row across first**, into cached memory.
+2. **Fill whole tiles in address order.** Within a tile, each pair of rows is
+ 64 consecutive words: 8 groups of 4 pixels of the even row, then 4 of the
+ odd row. The group order is XORed with 4 when `y & 8`:
+ ```c
+ for (pair = 0; pair < 16; pair++) { // rows 2*pair, 2*pair+1
+ out = tile + pair * 64; flip = (pair & 4) ? 4 : 0;
+ for (g = 0; g < 8; g++) {
+ xg = (g ^ flip) * 4;
+ out[g*8+0..3] = even_row[xg+0..3];
+ out[g*8+4..7] = odd_row[xg+0..3];
+ }
+ }
+ ```
+ Only the edge tiles need the per-pixel path. FAKE-08's
+ `platform/xex/source/XexHost.cpp` has the complete code.
+
+## Pacing
+
+`xex_video_begin()` waits until the previous flip is on screen: the swap fence
+has landed, the scanout register holds the address, and its update bits
+(0x6144) have cleared. So drawing then presenting once per loop runs at the
+display's 60 Hz with no timer. A 30 fps program needs a timer on top; see
+[Time](Time.md).
+
+## Diagnostics
+
+`xex_video_trace` (a printf-like hook) logs init and the first flips.
+`xex_video_dump_registers()` logs the CRTC, graphics, scaler, colour matrix
+and LUT registers; `xex_video_dump_lut()` logs some LUT entries. These made
+the black-screen hunt possible.
diff --git a/docs/wiki/Xenia-vs-Hardware.md b/docs/wiki/Xenia-vs-Hardware.md
new file mode 100644
index 0000000..b824e81
--- /dev/null
+++ b/docs/wiki/Xenia-vs-Hardware.md
@@ -0,0 +1,33 @@
+# Xenia vs. hardware
+
+Xenia Canary is fast for smoke tests: does the title start, does it reach its
+loop, what does it print. It is **not** evidence for display, timing or file
+system behaviour:
+
+| Area | Xenia | Console |
+|---|---|---|
+| Display controller | none; it shows what `VdSwap` names | needs the LUT and the 0x60EC commit |
+| CPU writes to 0x1844 (scanout) | turn the picture **white** | normal |
+| `VdQueryVideoMode` | 1280x720 | the real output (1920x1080 on our TV, 1280x1024 through a capture card) |
+| `VdInitializeScalerCommandBuffer` | fills NOPs, returns | **hangs** with Direct3D's arguments |
+| Vertical blank pacing | none (200-400 fps) | 60 Hz |
+| Time base | 50 MHz | 49.875 MHz |
+| `game:` | read-only | writable |
+| FAT32 USB listing | fine | `NextEntryOffset` left unwritten |
+| `RtlSetVectoredExceptionHandler` | not implemented | works |
+| `VdTurnDisplayOn` | not implemented | no visible effect |
+| `VdCallGraphicsNotificationRoutines(1, NULL, NULL)` | hangs Xenia | not tried with NULL |
+| Audio | registers, calls back about 187/s | the same |
+
+Running Xenia from a script:
+
+```sh
+xenia_canary.AppImage --log_file=xenia.log --log_level=4 default.xex &
+sleep 10; pkill -f xenia_canary
+grep -a "DbgPrint)" xenia.log
+```
+
+Xenia doesn't close when the title ends, so stop it yourself. Lines like
+"Invalid instruction" about libgcc data after a `trap` are harmless. A title's
+log files go to Xenia's `cache` folder when `game:` is read-only
+(`~/.local/share/Xenia/cache/` on Linux).