diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 2564dd7f..85d6c30c 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -1,11 +1,12 @@ # SPDX-License-Identifier: GPL-3.0-only # (JIANT) the Android probe (android/probe, JIANT Probe: what a phone does with the FM-1's USB audio), built on every # push that touches it, the APK as a workflow artifact. On main the site's workflow (emulator.yml) also publishes it -# next to the installer (app/jiant-probe.apk). The JIANT Stems app is a separate product, not in this repository. +# next to the installer (app/jiant-probe.apk). FM-1 Rescue (android/rescue: unbricks an FM-1 with an RP2040 and +# the phone) is built the same way, with the rescue firmware from rescue/base as its assets. The JIANT Stems app is a separate product, not in this repository. name: android on: push: - paths: ["android/**", ".github/workflows/android.yml"] + paths: ["android/**", "rescue/base/**", ".github/workflows/android.yml"] workflow_dispatch: permissions: contents: read @@ -27,3 +28,22 @@ jobs: with: name: jiant-probe path: android/probe/app/build/outputs/apk/debug/app-debug.apk + rescue: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: "8.9" + - name: the public JIANT and the official V15 inside the APK + run: python3 android/rescue/fetch_firmware.py + - name: the APK + run: gradle -p android/rescue assembleDebug --no-daemon + - uses: actions/upload-artifact@v4 + with: + name: fm1-rescue + path: android/rescue/app/build/outputs/apk/debug/app-debug.apk diff --git a/.gitignore b/.gitignore index c15d0434..7ed5886c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ __pycache__/ android/probe/.gradle/ android/probe/build/ android/probe/app/build/ +android/rescue/app/src/main/assets-firmware/ diff --git a/android/README.md b/android/README.md index 71356951..d09e3e46 100644 --- a/android/README.md +++ b/android/README.md @@ -7,6 +7,7 @@ driver, the mic through the FM-1 and back). Kept for diagnosing a phone; see [pr | | What it is | APK | |---|---|---| | **JIANT Probe** (`android/probe`, 0.4) | What a phone does with the FM-1 over USB: the channels Android passes, the stream read directly, the round trip. | `jiant-probe.apk` | +| **FM-1 Rescue** (`android/rescue`, 0.1) | Unbricks a hard-bricked FM-1 with an RP2040 and the phone: programs the RP2040 over OTG, then shows the repair. See [LEEME](rescue/LEEME.md). | artifact `fm1-rescue` | Download it from the site (, once the change is on `main`) or from any branch: the Actions tab → the **android** run → **Artifacts** → `jiant-probe`. Android 10 or later and a diff --git a/android/rescue/LEEME.md b/android/rescue/LEEME.md new file mode 100644 index 00000000..d5c806be --- /dev/null +++ b/android/rescue/LEEME.md @@ -0,0 +1,143 @@ +# FM-1 Rescue para Android — LÉEME + +[English below](#english) + +Repara un **M-VAVE FM-1 en hard brick** (pantalla negra, no aparece por USB) con un **RP2040** y **tu móvil +Android**. No hace falta ordenador, ni Python, ni copiar archivos: la app graba el RP2040 por el cable OTG y +después te va diciendo qué hacer mientras repara el FM-1. + +> **Estado:** versión 0.1, **sin probar todavía en hardware real**. El núcleo (lectura de la V15, la imagen que +> se graba en el RP2040 y el protocolo con el bootrom) está probado en el ordenador contra un RP2040 simulado +> y el resultado es idéntico byte a byte al de la página web (`rescue/fm1-rescue.html`). Úsala con la batería +> del FM-1 cargada y bajo tu responsabilidad. + +## Qué necesitas + +| | | +|---|---| +| Móvil Android 7 o más nuevo | con USB OTG (casi todos los actuales) | +| Adaptador **OTG** USB-C (o micro-USB) a USB-A, o un cable USB-C a USB-C | para enchufar el RP2040 al móvil | +| **Waveshare RP2040-Zero**, **Seeed XIAO RP2040** o **Raspberry Pi Pico** (o una placa tipo Pico, como la morada **Ultimate Pico RP2040**) | la Zero es la de la guía de GoodPerson42 | +| Cable USB-C con 4 hilos sueltos | negro, rojo, blanco, verde | +| Nada más | JIANT, la V15 oficial y el loader van dentro de la app: no hace falta internet | + +## Instalar + +Descarga `fm1-rescue.apk`: pestaña **Actions** del repositorio → ejecución **android** → **Artifacts** → +`fm1-rescue` (dentro del zip está `app-debug.apk`). Ábrelo en el móvil y permite "instalar apps de origen +desconocido" si Android lo pide. + +## Usar + +1. **Elige qué instalar** (paso 1 de la app): + - **JIANT** (incluido, recomendado): funciona tanto en FM-1 que venían con la **V15** como con la **V16**, + porque arranca con la cabecera de arranque de las dos. + - **V15 oficial de M-VAVE** (incluida, comprobada por su hash). Con un FM-1 que venía en V16 **no está + comprobado** que arranque: en ese caso usa JIANT. + - "Elegir otro .fwsc": otra versión de JIANT o tu propio archivo de la V15 (cualquier otro se rechaza). +2. **Elige tu placa:** RP2040-Zero, XIAO RP2040 o Raspberry Pi Pico (también clones tipo Pico). +3. **Cableado**, con el FM-1 **apagado** (el rojo no se conecta): + + | Hilo | RP2040-Zero | XIAO RP2040 | Pico / tipo Pico | + |---|---|---|---| + | verde (D+) | `0` | `D6` | `GP0` (pin 1) | + | blanco (D−) | `1` | `D7` | `GP1` (pin 2) | + | negro (GND) | `GND` | `GND` | `GND` (pin 3) | + | rojo (5 V) | — | — | — | + + Enchufa el USB-C de esos hilos al FM-1. +4. **Conecta el RP2040 al móvil** con el adaptador OTG y acepta el aviso de acceso USB (marca "usar siempre" para + que no vuelva a salir). No hace falta pulsar BOOT si la placa trae MicroPython, un programa de demostración, el + firmware de rescate o el FM-1 Transporter: la app la pasa sola a modo de grabación. Si aun así no la detecta, + desconéctala y vuelve a enchufarla **manteniendo BOOT** pulsado. +5. La app **graba el RP2040 sola** (unos 15 segundos, con barra de progreso) y lo reinicia. +6. Cuando la app diga **"Enciende el FM-1 ahora"**, enciéndelo. Verás "Reparando el FM-1…" con el progreso + (1–3 minutos). **No desconectes nada.** +7. **"¡Listo!"** → apaga el FM-1, quita los cables y vuelve a encenderlo: arranca con lo que elegiste (JIANT o + V15). Desde ahí puedes cambiar de firmware con el instalador web de JIANT (incluido volver a la V16 oficial). + +Para reparar otro FM-1 basta con desconectar y volver a conectar el RP2040. + +## Si algo sale mal + +| La app dice | Qué hacer | +|---|---| +| "Permite el acceso USB" | Acepta el aviso de Android. | +| "No se pudo grabar el RP2040" | Desconéctalo y vuelve a conectarlo con BOOT pulsado. Prueba otro adaptador OTG. | +| "No responde al reinicio" | El programa que trae la placa no admite el reinicio automático: conéctala con BOOT pulsado. | +| "Apaga el FM-1" | El FM-1 estaba encendido con otro firmware. Apágalo, reconecta el RP2040, enciéndelo. | +| Error: "Se perdió la conexión…" | Revisa los cables; prueba a intercambiar verde y blanco. Batería cargada. | +| Error: "Esto no parece un FM-1" | No se escribió nada. Revisa que sea un FM-1. | +| Error: "Una escritura no se completó…" | Apaga el FM-1, reconecta el RP2040 y repite: retoma donde quedó. | + +El LED del RP2040 dice lo mismo sin mirar el móvil: amarillo parpadeando = esperando que enciendas el FM-1, +azul = trabajando, verde fijo = listo, rojo parpadeando rápido = error. La Pico tiene un LED de un solo color: +parpadeo lento = esperando, parpadeo irregular = trabajando, fijo = listo, parpadeo rápido = error. Las placas tipo +Pico que tengan el LED en otro pin funcionan igual, solo que sin LED: sigue el progreso en la app. + +## Diagnóstico + +La tarjeta **Diagnóstico** lee el registro interno del RP2040 y dice en palabras simples hasta dónde llegó: +"Enviando la señal de arranque… (envíos: N)", "¡El FM-1 respondió!", "Cables D+ y D− invertidos", +"Respondió, pero no se conecta por USB", "El FM-1 está en modo de arranque ✓"… con qué probar en cada caso. + +- **Paciencia con la señal de arranque:** en un FM-1 real hicieron falta más de 3 minutos (415.840 envíos) + hasta que respondió. Si pasa mucho tiempo, apaga y enciende el FM-1 sin tocar la app. +- **Reiniciar la señal de arranque:** reinicia el RP2040 en modo "señal de arranque" (útil después de apagar el + FM-1, si la app quedó en otro estado). +- **Guardar diagnóstico (.zip):** guarda en **Descargas** `fm1-rescue-diagnostico-FECHA.zip` y ofrece enviarlo. + Lleva `resumen.txt` (diagnóstico, móvil, placa, firmware elegido, dispositivos USB conectados), + `registro-app.txt` (todo lo que hizo la app), `consola-rp2040.txt` (el registro interno del RP2040, el mismo que + guardan los `logs\transporter-*.log` del método con Python) y `estados.txt` (el progreso del rescate). +- **Compartir registro:** manda el registro como texto por WhatsApp, correo, etc. + +## Qué hace exactamente + +- **En el RP2040** (por PICOBOOT, el protocolo del bootrom que usa `picotool`): borra, escribe y **relee** cada + sector del firmware de rescate (`rescue/firmware`, basado en el FM-1 Transporter) más la V15 y el loader, y lo + reinicia. +- **En el FM-1** (lo hace el RP2040): lo pone en modo de arranque de la ROM, comprueba que es un FM-1 (chip + `0x980F`, flash `0x856014`/`0xB36014`) y escribe **solo los sectores de `0x4000..0x92FFF` que difieren** del + firmware elegido, cada uno verificado, con una relectura final completa. +- **Nunca** toca la cabecera de arranque (`0x0000..0x3FFF`) ni tus datos (`0x93000..`: ajustes, sonidos, + canciones). A diferencia del método con Python, **no** guarda una copia completa del FM-1 antes. +- El móvil solo alimenta el RP2040 y lee su progreso. +- **JIANT** va dentro del APK: el paquete público que ofrece el instalador web (`fetch_firmware.py` lo mete al + compilar; GPL-3.0, con la licencia Apache-2.0 de los archivos del SDK de JieLi que lleva). +- **La V15** también va dentro: `fetch_firmware.py` la toma al compilar de + [Quixotic7/FM1Backups](https://github.com/Quixotic7/FM1Backups) en un commit fijado y solo la acepta si es el + archivo original de M-VAVE (sha256 `db1642b2…`); la app vuelve a comprobar el hash de su región de firmware. + No se guarda en git. Es software de M-VAVE: incluirla es decisión del autor de la app. Si una compilación no + la trae, la app la descarga de ese mismo sitio. +- El loader de JieLi va dentro (jl-uboot-tool, MIT, licencia en `assets/wl82loader-LICENSE.txt`). +- Si el FM-1 tenía otro firmware personalizado (Felucca, Skiff…) y con JIANT no arranca, repite el rescate + eligiendo la V15: los datos de otros firmwares pueden confundir a JIANT. + +### ¿Y la V16? + +No se escribe directamente: ocupa hasta `0xA8FFF` (pisaría el almacén de canciones desde `0x97000`) y trae su +propia cabecera de arranque, que este método nunca toca. Para un FM-1 que venía en V16, el rescate con **JIANT** +deja intacta su cabecera V16 y arranca; después, si quieres la V16 oficial, "Volver al oficial" del instalador. + +## Para desarrolladores + +| | | +|---|---| +| `app/src/main/java/fm/jiant/rescue/RescueImage.java` | `.fwsc` → región V15, payload, sectores a grabar (igual que `rescue/builder.js`) | +| `Picoboot.java` | protocolo PICOBOOT del bootrom del RP2040 | +| `RescueStatus.java` | la respuesta de `rescue` del firmware | +| `MainActivity.java` | la pantalla, USB OTG y permisos | +| `test/run.sh` | prueba en el ordenador con un RP2040 simulado (necesita la V15, la V16 y el loader) | + +Compilar: `gradle -p android/rescue assembleDebug` (JDK 17, Gradle 8.9); el firmware para cada placa sale de +`rescue/base/` (`rescue/build.sh`). Licencia MIT; créditos en `rescue/README.md`. + +## English + +FM-1 Rescue for Android unbricks an FM-1 with an RP2040 and the phone: firmware to restore: JIANT (bundled, the default; runs under both the V15 and the V16 boot head) or the +the official V15 (bundled too, hash-checked); JieLi's loader is bundled. Pick the board, wire green → GP0, white → GP1, black → GND (FM-1 off, red unconnected), hold BOOT and +plug the RP2040 into the phone with an OTG adapter. The app programs the board over PICOBOOT, reboots it, and +then shows the rescue's progress read from the board: "switch the FM-1 on now", "repairing…", "done". Only +the differing sectors of `0x4000..0x92FFF` are written, each verified; the boot head and user data are never +touched. A board running something else (MicroPython, a demo, a Pico SDK program) is sent to BOOTSEL by the +app (reset interface or 1200-baud touch), so BOOT is usually not needed. Version 0.1, **not yet tested on hardware**. diff --git a/android/rescue/app/build.gradle b/android/rescue/app/build.gradle new file mode 100644 index 00000000..c31ce230 --- /dev/null +++ b/android/rescue/app/build.gradle @@ -0,0 +1,34 @@ +plugins { + id "com.android.application" +} +android { + namespace "fm.jiant.rescue" + compileSdk 34 + defaultConfig { + applicationId "fm.jiant.rescue" + minSdk 24 + targetSdk 34 + versionCode 1 + versionName "0.1" + } + signingConfigs { + debug { // (one key for every build: a new APK installs over the last one) + storeFile file("rescue-debug.keystore") + storePassword "android" + keyAlias "androiddebugkey" + keyPassword "android" + } + } + buildTypes { + debug { signingConfig signingConfigs.debug } + } + sourceSets { + // The rescue firmware for each board, from rescue/base (rescue/build.sh). + // assets-firmware: the public JIANT and the official V15 (fetch_firmware.py, run by the android workflow; not in git). + main { assets.srcDirs += ["../../../rescue/base", "src/main/assets-firmware"] } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } +} diff --git a/android/rescue/app/rescue-debug.keystore b/android/rescue/app/rescue-debug.keystore new file mode 100644 index 00000000..29b3aa02 Binary files /dev/null and b/android/rescue/app/rescue-debug.keystore differ diff --git a/android/rescue/app/src/main/AndroidManifest.xml b/android/rescue/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..2de33d96 --- /dev/null +++ b/android/rescue/app/src/main/AndroidManifest.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/android/rescue/app/src/main/assets/wl82loader-LICENSE.txt b/android/rescue/app/src/main/assets/wl82loader-LICENSE.txt new file mode 100644 index 00000000..e917978b --- /dev/null +++ b/android/rescue/app/src/main/assets/wl82loader-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Andrey Grigoryev (kagaimiq) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/android/rescue/app/src/main/assets/wl82loader.bin b/android/rescue/app/src/main/assets/wl82loader.bin new file mode 100644 index 00000000..3b47cffa Binary files /dev/null and b/android/rescue/app/src/main/assets/wl82loader.bin differ diff --git a/android/rescue/app/src/main/java/fm/jiant/rescue/Diagnosis.java b/android/rescue/app/src/main/java/fm/jiant/rescue/Diagnosis.java new file mode 100644 index 00000000..faf4073f --- /dev/null +++ b/android/rescue/app/src/main/java/fm/jiant/rescue/Diagnosis.java @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: MIT +// Reads the rescue firmware's console (CDC 0: the FM-1 Transporter's log, src/recovery.c, pio_host.c, +// autorescue.c) and says in plain words how far the FM-1 got and what to try next. No Android classes: +// android/rescue/test runs it on real Transporter logs. +package fm.jiant.rescue; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class Diagnosis { + private static final Pattern PACKETS = Pattern.compile("KEY: (\\d+) packets"); + private static final Pattern ACK = Pattern.compile("(ACK \\(data line held low\\)|D\\+ high in gap).* after (\\d+) packets"); + private static final Pattern VIDPID = Pattern.compile("VID=([0-9A-Fa-f]{4}) PID=([0-9A-Fa-f]{4})"); + private static final Pattern CHIP = Pattern.compile("chip key ([0-9A-Fa-f]{4}), type \\d+, flash id ([0-9A-Fa-f]+)"); + + public boolean keying, ack, falseAck, swapped, handoff, mounted, uboot, ready, inquiryFailed, + noMountYet, reattach, attachedAtBoot, stockV15, otherDevice, done, error, chipBad; + public long packets, ackAfter; + public int falseAcks, reattaches; + public String vidPid = "", chip = "", errorLine = ""; + + /** Feeds one console line (with or without its "[ 123 us] " prefix). */ + public void feed(String line) { + if (line == null) return; + Matcher m; + if (line.contains("KEY: sending")) keying = true; + if ((m = PACKETS.matcher(line)).find()) { keying = true; packets = Long.parseLong(m.group(1)); } + if ((m = ACK.matcher(line)).find()) { ack = true; ackAfter = Long.parseLong(m.group(2)); } + if (line.contains("false ACK")) { falseAck = true; falseAcks++; } + if (line.contains("D- pulled up instead of D+")) swapped = true; + if (line.contains("HANDOFF:")) handoff = true; + if (line.contains("D+ already pulled up")) attachedAtBoot = true; + if (line.contains("HOST: device mounted")) mounted = true; + if ((m = VIDPID.matcher(line)).find()) { + vidPid = (m.group(1) + ":" + m.group(2)).toUpperCase(); + if (vidPid.equals("4C4A:8057")) uboot = true; + else if (vidPid.equals("4C4A:C755")) stockV15 = true; + else otherDevice = true; + } + if (line.contains("UBOOT READY")) { ready = true; uboot = true; } + if (line.contains("INQUIRY never accepted")) inquiryFailed = true; + if (line.contains("HOST: no device mounted yet")) noMountYet = true; + if (line.contains("rebooting the transporter to pulse and re-host")) { reattach = true; reattaches++; } + if ((m = CHIP.matcher(line)).find()) chip = m.group(1).toUpperCase() + " / " + m.group(2).toUpperCase(); + if (line.contains("RESCUE: DONE")) done = true; + if (line.contains("RESCUE: ERROR")) { + error = true; + errorLine = line.replaceFirst("^\\[[^]]*\\]\\s*", ""); + if (line.contains("not an FM-1")) chipBad = true; + } + } + + /** Lines that only make the on-screen log longer (TinyUSB host debug). */ + public static boolean noise(String line) { + return line.matches("^\\[\\d+\\] Aborted transfer.*") || line.matches("^\\s*(Open|Allocated|Bind) .*") + || line.matches("^\\[\\d+:\\d*\\] (Open EP|Get Descriptor|Set Address|Control data|Set Configuration).*") + || line.trim().isEmpty(); + } + + /** {headline, advice} in Spanish or English. */ + public String[] summary(boolean es) { + if (done) return pair(es, "El FM-1 quedó reparado", "The FM-1 is repaired", + "Todo el proceso terminó bien.", "The whole process finished fine."); + if (swapped) return pair(es, "Cables D+ y D− invertidos", "D+ and D− wires swapped", + "El RP2040 vio que el FM-1 respondía por el hilo equivocado. Intercambia los hilos de GP0 y GP1 " + + "(verde/celeste y blanco), apaga el FM-1, reconecta el RP2040 y vuelve a encenderlo.", + "The RP2040 saw the FM-1 answer on the wrong wire. Swap the GP0 and GP1 wires (green and white), " + + "switch the FM-1 off, re-plug the RP2040 and switch it on again."); + if (chipBad) return pair(es, "El chip no es el de un FM-1", "The chip is not an FM-1's", + "Respondió algo, pero con otra clave o memoria (" + chip + "). No se escribió nada.", + "Something answered, but with another key or flash (" + chip + "). Nothing was written."); + if (error) return pair(es, "Error durante la reparación", "Error during the repair", + "El FM-1 entró en modo de arranque, así que la conexión funciona. Mensaje: " + errorLine + + ". Apaga el FM-1, reconecta el RP2040 y repite.", + "The FM-1 entered boot mode, so the link works. Message: " + errorLine + + ". Switch the FM-1 off, re-plug the RP2040 and repeat."); + if (ready) return pair(es, "El FM-1 está en modo de arranque ✓", "The FM-1 is in boot mode ✓", + "La comunicación funciona" + (chip.isEmpty() ? "." : " (chip " + chip + ")."), + "The link works" + (chip.isEmpty() ? "." : " (chip " + chip + ").")); + if (mounted && inquiryFailed) return pair(es, "Se conectó pero no acepta órdenes", "Attached but takes no commands", + "El FM-1 apareció por USB (" + vidPid + ") pero no contestó a las órdenes. Suele ser un contacto " + + "flojo o cables largos: acorta los hilos, revisa las soldaduras y repite.", + "The FM-1 showed up on USB (" + vidPid + ") but did not answer commands. Usually a loose contact " + + "or long wires: shorten them, check the solder joints and repeat."); + if (stockV15) return pair(es, "El FM-1 arrancó con la V15 de fábrica", "The FM-1 booted stock V15", + "No está brickeado: arrancó su firmware. La app le envía la orden para entrar en modo de arranque.", + "It is not bricked: it booted its firmware. The app sends it the command to enter boot mode."); + if (otherDevice) return pair(es, "El FM-1 arrancó otro firmware", "The FM-1 booted another firmware", + "Apareció como " + vidPid + ". Apágalo, desconecta y reconecta el RP2040, y enciéndelo de nuevo.", + "It showed up as " + vidPid + ". Switch it off, re-plug the RP2040 and switch it on again."); + if (ack && !mounted && (noMountYet || reattach)) return pair(es, "Respondió, pero no se conecta por USB", "It answered but does not attach", + "El FM-1 contestó a la señal de arranque (tras " + ackAfter + " envíos) pero después no apareció por " + + "USB" + (reattaches > 0 ? " (" + reattaches + " reintentos)" : "") + ". Los cables y el FM-1 " + + "responden: suele ser ruido o un contacto flojo en D+/D−. Acorta los hilos, que no estén cerca del " + + "rojo, y repite apagando y encendiendo el FM-1.", + "The FM-1 answered the boot signal (after " + ackAfter + " packets) but then did not show up on " + + "USB" + (reattaches > 0 ? " (" + reattaches + " retries)" : "") + ". The wires and the FM-1 " + + "respond: usually noise or a loose contact on D+/D−. Shorten the wires and repeat, switching the " + + "FM-1 off and on."); + if (ack) return pair(es, "¡El FM-1 respondió! ✓", "The FM-1 answered! ✓", + "Contestó a la señal de arranque tras " + ackAfter + " envíos" + (mounted ? " y se conectó por USB." : "; conectando…"), + "It answered the boot signal after " + ackAfter + " packets" + (mounted ? " and attached on USB." : "; attaching…")); + if (attachedAtBoot) return pair(es, "El FM-1 ya estaba encendido", "The FM-1 was already on", + "Para un FM-1 brickeado: apágalo, desconecta y reconecta el RP2040, y enciende el FM-1 cuando la app lo diga.", + "For a bricked FM-1: switch it off, re-plug the RP2040 and switch the FM-1 on when the app says so."); + if (keying) { + String n = String.format("%,d", packets); + if (packets < 60000) return pair(es, "Enviando la señal de arranque…", "Sending the boot signal…", + "Envíos: " + n + (falseAcks > 0 ? " (" + falseAcks + " falsas respuestas)" : "") + ". Enciende el FM-1 " + + "ahora. Puede tardar: en un FM-1 real hicieron falta más de 3 minutos.", + "Packets: " + n + (falseAcks > 0 ? " (" + falseAcks + " false answers)" : "") + ". Switch the FM-1 " + + "on now. It can take a while: on a real FM-1 it took over 3 minutes."); + return pair(es, "El FM-1 todavía no responde", "The FM-1 does not answer yet", + "Envíos: " + n + ". Prueba en este orden: 1) apaga y enciende el FM-1 (deja la app así); 2) carga " + + "el FM-1 una hora con un cable normal y repite; 3) intercambia los hilos de GP0 y GP1; 4) revisa con " + + "un multímetro que cada hilo llegue a su contacto del USB-C (D+ = A6/B6, D− = A7/B7, GND = carcasa).", + "Packets: " + n + ". Try in this order: 1) switch the FM-1 off and on (leave the app as it is); 2) " + + "charge the FM-1 for an hour with a normal cable and repeat; 3) swap the GP0 and GP1 wires; 4) " + + "check with a multimeter that each wire reaches its USB-C contact (D+ = A6/B6, D− = A7/B7, GND = shell)."); + } + return pair(es, "Esperando el registro del RP2040", "Waiting for the RP2040's log", "", ""); + } + + private static String[] pair(boolean es, String hEs, String hEn, String aEs, String aEn) { + return es ? new String[] {hEs, aEs} : new String[] {hEn, aEn}; + } +} diff --git a/android/rescue/app/src/main/java/fm/jiant/rescue/MainActivity.java b/android/rescue/app/src/main/java/fm/jiant/rescue/MainActivity.java new file mode 100644 index 00000000..14daaa43 --- /dev/null +++ b/android/rescue/app/src/main/java/fm/jiant/rescue/MainActivity.java @@ -0,0 +1,1065 @@ +// SPDX-License-Identifier: MIT +// FM-1 Rescue for Android: one screen that does the whole unbrick. +// 1. What to restore: JIANT (the public package, inside the APK, the default: +// it runs under the boot head of V15 and of V16), the official V15 +// (also in the APK, hash-checked), or a .fwsc of your own. JieLi's +// wl82loader.bin ships in the APK. +// 2. The RP2040 (RP2040-Zero, XIAO or a Pico-style board) is plugged into the phone with an OTG +// adapter while BOOT is held: the app programs it over PICOBOOT, with the +// V15 inside (no file copy, no computer). A board that already runs the +// rescue firmware is sent back to BOOTSEL by the app itself. +// 3. The board reboots into the rescue firmware; the app reads its progress +// on the data port and says what to do: switch the FM-1 on, wait, done. +// The phone only powers the RP2040; the FM-1 runs on its battery. +package fm.jiant.rescue; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.Typeface; +import android.graphics.drawable.GradientDrawable; +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbDeviceConnection; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbInterface; +import android.hardware.usb.UsbManager; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.provider.MediaStore; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class MainActivity extends Activity { + private static final int PID_RESCUE = 0x000A; // rescue / Transporter firmware + private static final int PICK_FWSC = 1; + private static final String ACTION_PERMISSION = "fm.jiant.rescue.USB_PERMISSION"; + private static final int ACCENT = 0xFFFF7A00; + + private final boolean es = Locale.getDefault().getLanguage().equals("es"); + private final Handler ui = new Handler(Looper.getMainLooper()); + private final ExecutorService usb = Executors.newSingleThreadExecutor(); + private final ExecutorService net = Executors.newSingleThreadExecutor(); + private UsbManager usbManager; + private SharedPreferences prefs; + + private TextView fwscText, loaderText, stage, detail, log, diagHead, diagText; + private volatile Diagnosis diag = new Diagnosis(); + private final StringBuilder fullLog = new StringBuilder(); + private volatile String pendingCmd; // a data-port request from the UI (e.g. "rekey") + private final StringBuilder consoleLog = new StringBuilder(); // the RP2040's console, raw + private final StringBuilder statusLog = new StringBuilder(); // rescue status lines, when they change + private volatile String lastStatusLine = ""; + private RadioButton srcJiant, srcV15, srcCustom; + private ProgressBar progress; + private Button reflash; + + private byte[] loader; + private byte[] jiantPkg, v15Pkg, customPkg; // the three sources; null until available + private String jiantVersion = "", customLabel = ""; + private volatile boolean busy; // a USB job is running + private volatile String monitoring; // device name the status link is open on + private volatile boolean stopMonitor; + private final Set asked = new HashSet<>(); + private final Set autoReset = new HashSet<>(); + + private String t(String esText, String enText) { return es ? esText : enText; } + + // ------------------------------------------------------------ UI + + @Override + protected void onCreate(Bundle b) { + super.onCreate(b); + usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); + prefs = getSharedPreferences("rescue", MODE_PRIVATE); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + buildUi(); + loadFiles(); + poll.run(); + } + + private int dp(int v) { + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, getResources().getDisplayMetrics()); + } + + private TextView text(LinearLayout parent, String s, int sp, boolean bold) { + TextView v = new TextView(this); + v.setText(s); + v.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp); + v.setTextColor(0xFF1D1D1B); + if (bold) v.setTypeface(Typeface.DEFAULT_BOLD); + v.setPadding(0, dp(4), 0, dp(4)); + parent.addView(v); + return v; + } + + private LinearLayout card(LinearLayout parent) { + LinearLayout c = new LinearLayout(this); + c.setOrientation(LinearLayout.VERTICAL); + c.setPadding(dp(16), dp(12), dp(16), dp(12)); + GradientDrawable bg = new GradientDrawable(); + bg.setColor(Color.WHITE); + bg.setCornerRadius(dp(12)); + bg.setStroke(dp(1), 0xFFE2E0DA); + c.setBackground(bg); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, -2); + lp.bottomMargin = dp(12); + parent.addView(c, lp); + return c; + } + + private Button button(LinearLayout parent, String s) { + Button v = new Button(this); + v.setText(s); + v.setAllCaps(false); + parent.addView(v, new LinearLayout.LayoutParams(-2, -2)); + return v; + } + + private void buildUi() { + ScrollView scroll = new ScrollView(this); + scroll.setBackgroundColor(0xFFF6F5F1); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(dp(16), dp(20), dp(16), dp(32)); + scroll.addView(root); + + TextView title = text(root, "FM-1 Rescue", 24, true); + title.setTextColor(ACCENT); + text(root, t("Repara un FM-1 que no enciende con un RP2040 y este móvil. Sin ordenador.", + "Fix an FM-1 that does not turn on with an RP2040 and this phone. No computer."), 14, false); + + LinearLayout c1 = card(root); + text(c1, t("1 · Qué firmware instalar", "1 · Which firmware to install"), 16, true); + RadioGroup src = new RadioGroup(this); + srcJiant = new RadioButton(this); + srcV15 = new RadioButton(this); + srcCustom = new RadioButton(this); + for (RadioButton r : new RadioButton[] {srcJiant, srcV15, srcCustom}) { + r.setId(View.generateViewId()); + src.addView(r); + } + srcCustom.setVisibility(View.GONE); + switch (prefs.getString("src", "jiant")) { + case "v15": srcV15.setChecked(true); break; + case "custom": srcCustom.setChecked(true); break; + default: srcJiant.setChecked(true); + } + src.setOnCheckedChangeListener((gr, id) -> { + prefs.edit().putString("src", id == srcV15.getId() ? "v15" : id == srcCustom.getId() ? "custom" : "jiant").apply(); + if (id == srcV15.getId() && v15Pkg == null) net.execute(this::downloadV15); + updateFileTexts(); + }); + c1.addView(src); + fwscText = text(c1, "", 13, false); + button(c1, t("Elegir otro .fwsc (V15 o JIANT)", "Choose another .fwsc (V15 or JIANT)")).setOnClickListener(v -> { + Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT); + i.addCategory(Intent.CATEGORY_OPENABLE); + i.setType("*/*"); + startActivityForResult(i, PICK_FWSC); + }); + loaderText = text(c1, "", 12, false); + + LinearLayout c2 = card(root); + text(c2, t("2 · Tu placa", "2 · Your board"), 16, true); + RadioGroup g = new RadioGroup(this); + RadioButton zero = new RadioButton(this), xiao = new RadioButton(this), pico = new RadioButton(this); + zero.setText(t("Waveshare RP2040-Zero (verde → 0, blanco → 1, negro → GND)", + "Waveshare RP2040-Zero (green → 0, white → 1, black → GND)")); + xiao.setText(t("Seeed XIAO RP2040 (verde → D6, blanco → D7, negro → GND)", + "Seeed XIAO RP2040 (green → D6, white → D7, black → GND)")); + pico.setText(t("Raspberry Pi Pico, Ultimate Pico u otra placa tipo Pico (verde → GP0 pin 1, blanco → GP1 pin 2, negro → GND pin 3)", + "Raspberry Pi Pico, Ultimate Pico or another Pico-style board (green → GP0 pin 1, white → GP1 pin 2, black → GND pin 3)")); + for (RadioButton r : new RadioButton[] {zero, xiao, pico}) { + r.setId(View.generateViewId()); + g.addView(r); + } + (board().equals("xiao") ? xiao : board().equals("pico") ? pico : zero).setChecked(true); + g.setOnCheckedChangeListener((gr, id) -> prefs.edit() + .putString("board", id == xiao.getId() ? "xiao" : id == pico.getId() ? "pico" : "zero").apply()); + c2.addView(g); + + LinearLayout c3 = card(root); + text(c3, t("3 · Conectar", "3 · Connect"), 16, true); + text(c3, t("• FM-1 APAGADO. Cable rojo sin conectar.\n" + + "• Conecta los 3 cables del RP2040 al USB-C del FM-1.\n" + + "• Enchufa el RP2040 a este móvil con un adaptador OTG (si no lo detecta: con BOOT pulsado).\n" + + "• La app hace el resto y te dice cuándo encender el FM-1.", + "• FM-1 OFF. Red wire unconnected.\n" + + "• Connect the RP2040's 3 wires to the FM-1's USB-C.\n" + + "• Plug the RP2040 into this phone with an OTG adapter (if it is not seen: holding BOOT).\n" + + "• The app does the rest and tells you when to switch the FM-1 on."), 14, false); + + LinearLayout c4 = card(root); + stage = text(c4, "", 20, true); + detail = text(c4, "", 14, false); + progress = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); + progress.setMax(1000); + c4.addView(progress, new LinearLayout.LayoutParams(-1, dp(12))); + reflash = button(c4, t("Volver a grabar el RP2040", "Reprogram the RP2040")); + reflash.setVisibility(View.GONE); + reflash.setOnClickListener(v -> { + UsbDevice d = find(PID_RESCUE); + if (d != null && usbManager.hasPermission(d)) resetToBootsel(d); + }); + + LinearLayout c5 = card(root); + text(c5, t("Diagnóstico", "Diagnostics"), 16, true); + diagHead = text(c5, t("Esperando el registro del RP2040", "Waiting for the RP2040's log"), 15, true); + diagText = text(c5, t("Aparece cuando el RP2040 ya tiene el firmware de rescate y está conectado al móvil.", + "It shows up once the RP2040 runs the rescue firmware and is plugged into the phone."), 13, false); + button(c5, t("Guardar diagnóstico (.zip)", "Save diagnostics (.zip)")).setOnClickListener(v -> saveDiagnostics()); + button(c5, t("Compartir registro", "Share the log")).setOnClickListener(v -> shareLog()); + button(c5, t("Reiniciar la señal de arranque", "Restart the boot signal")).setOnClickListener(v -> { + pendingCmd = "rekey"; + logLine(t("Reiniciando la señal: apaga el FM-1, espera 3 s y enciéndelo cuando lo pida la app.", + "Restarting the signal: switch the FM-1 off, wait 3 s and switch it on when the app says so.")); + }); + + log = new TextView(this); + log.setTypeface(Typeface.MONOSPACE); + log.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11); + log.setTextColor(0xFF6F6E69); + root.addView(log); + + TextView foot = text(root, t("Solo se escribe la zona del firmware del FM-1 (0x4000–0x92FFF), cada sector verificado; " + + "tus ajustes, sonidos y canciones no se tocan. Herramienta no oficial: úsala con la batería cargada.", + "Only the FM-1's firmware area (0x4000–0x92FFF) is written, each sector verified; your settings, " + + "sounds and songs are not touched. Unofficial tool: use it on a charged battery."), 12, false); + foot.setTextColor(0xFF6F6E69); + foot.setGravity(Gravity.START); + setContentView(scroll); + show(t("Conecta el RP2040", "Plug in the RP2040"), "", 0); + } + + private void show(String s, String d, int permille) { + ui.post(() -> { + stage.setText(s); + detail.setText(d); + progress.setProgress(permille); + }); + } + + private void logLine(String s) { + synchronized (fullLog) { + fullLog.append(new java.text.SimpleDateFormat("HH:mm:ss", Locale.ROOT).format(new java.util.Date())) + .append(" ").append(s).append('\n'); + if (fullLog.length() > 400_000) fullLog.delete(0, fullLog.length() - 300_000); + } + ui.post(() -> { + String all = log.getText() + s + "\n"; + if (all.length() > 4000) all = all.substring(all.length() - 4000); + log.setText(all); + }); + } + + private String board() { return prefs.getString("board", "zero"); } + + /** Console line from the RP2040: into the full log, the diagnosis, and (unless noise) the screen. */ + private void consoleLine(String line) { + Diagnosis d = diag; + d.feed(line); + synchronized (fullLog) { + fullLog.append("RP2040 ").append(line).append('\n'); + } + synchronized (consoleLog) { + consoleLog.append(line).append('\n'); + if (consoleLog.length() > 2_000_000) consoleLog.delete(0, consoleLog.length() - 1_500_000); + if (fullLog.length() > 400_000) fullLog.delete(0, fullLog.length() - 300_000); + } + if (!Diagnosis.noise(line) && !line.contains("KEY: ") ) { + ui.post(() -> { + String all = log.getText() + "› " + line + "\n"; + if (all.length() > 4000) all = all.substring(all.length() - 4000); + log.setText(all); + }); + } + String[] sum = d.summary(es); + ui.post(() -> { + diagHead.setText(sum[0]); + diagText.setText(sum[1]); + }); + } + + private static String stamp() { + return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT).format(new java.util.Date()); + } + + private static byte[] readFile(File f) throws IOException { + try (InputStream in = new FileInputStream(f)) { return readAll(in); } + } + + /** What the phone, the app and the USB bus look like now, for the diagnostics zip. */ + private String diagReport() { + StringBuilder r = new StringBuilder(); + String[] sum = diag.summary(es); + r.append("FM-1 Rescue diagnostics\n").append(stamp()).append("\n\n"); + r.append("Diagnosis: ").append(sum[0]).append("\n ").append(sum[1]).append("\n\n"); + String ver = "?"; + try { ver = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (Exception e) { } + r.append("App ").append(ver).append(", board ").append(board()).append(", firmware ").append(installedName()) + .append(" (source ").append(source()).append(")\n"); + r.append("Bundled: JIANT ").append(jiantPkg != null ? jiantVersion : "no").append(", V15 ") + .append(v15Pkg != null ? "yes" : "no").append(", loader ").append(loader != null ? "ok" : "no").append("\n"); + r.append("Phone: ").append(Build.MANUFACTURER).append(' ').append(Build.MODEL).append(", Android ") + .append(Build.VERSION.RELEASE).append(" (API ").append(Build.VERSION.SDK_INT).append(")\n"); + r.append("Last rescue status: ").append(lastStatusLine.isEmpty() ? "(none)" : lastStatusLine).append("\n\n"); + Diagnosis d = diag; + r.append("Keying=").append(d.keying).append(" packets=").append(d.packets).append(" ack=").append(d.ack) + .append(" ackAfter=").append(d.ackAfter).append(" falseAcks=").append(d.falseAcks).append(" swapped=").append(d.swapped) + .append("\nhandoff=").append(d.handoff).append(" mounted=").append(d.mounted).append(" vidpid=").append(d.vidPid) + .append(" uboot=").append(d.uboot).append(" ready=").append(d.ready).append(" inquiryFailed=").append(d.inquiryFailed) + .append("\nnoMountYet=").append(d.noMountYet).append(" reattaches=").append(d.reattaches).append(" chip=").append(d.chip) + .append(" done=").append(d.done).append(" error=").append(d.error).append(' ').append(d.errorLine).append("\n\n"); + r.append("USB devices:\n"); + for (UsbDevice u : usbManager.getDeviceList().values()) { + r.append(String.format(Locale.ROOT, " %s %04X:%04X", u.getDeviceName(), u.getVendorId(), u.getProductId())); + try { r.append(" \"").append(u.getProductName()).append("\" by \"").append(u.getManufacturerName()).append('"'); } + catch (Exception e) { } + r.append(usbManager.hasPermission(u) ? " (permission)" : " (no permission)").append('\n'); + for (int i = 0; i < u.getInterfaceCount(); i++) { + UsbInterface f = u.getInterface(i); + r.append(String.format(Locale.ROOT, " itf %d class %02X/%02X/%02X, %d endpoints\n", f.getId(), + f.getInterfaceClass(), f.getInterfaceSubclass(), f.getInterfaceProtocol(), f.getEndpointCount())); + } + } + return r.toString(); + } + + /** Saves a zip with everything that explains a run into Downloads, then offers to share it. */ + private void saveDiagnostics() { + String name = "fm1-rescue-diagnostico-" + + new java.text.SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ROOT).format(new java.util.Date()) + ".zip"; + net.execute(() -> { + try { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(bo)) { + String a, c, st; + synchronized (fullLog) { a = fullLog.toString(); } + synchronized (consoleLog) { c = consoleLog.toString(); } + synchronized (statusLog) { st = statusLog.toString(); } + String[][] files = { + {"LEEME.txt", t("Diagnóstico de FM-1 Rescue. resumen.txt: estado y equipo; registro-app.txt: todo " + + "lo que hizo la app; consola-rp2040.txt: el registro interno del RP2040 (FM-1 Transporter); " + + "estados.txt: el progreso del rescate.\n", + "FM-1 Rescue diagnostics. resumen.txt: state and devices; registro-app.txt: everything the " + + "app did; consola-rp2040.txt: the RP2040's own log (FM-1 Transporter); estados.txt: the " + + "rescue's progress.\n")}, + {"resumen.txt", diagReport()}, + {"registro-app.txt", a}, + {"consola-rp2040.txt", c.isEmpty() ? "(no console read yet)\n" : c}, + {"estados.txt", st.isEmpty() ? "(no status yet)\n" : st}, + }; + for (String[] f : files) { + z.putNextEntry(new ZipEntry(f[0])); + z.write(f[1].getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + } + } + byte[] zip = bo.toByteArray(); + Uri uri = null; + String where; + if (Build.VERSION.SDK_INT >= 29) { + ContentValues cv = new ContentValues(); + cv.put(MediaStore.MediaColumns.DISPLAY_NAME, name); + cv.put(MediaStore.MediaColumns.MIME_TYPE, "application/zip"); + cv.put(MediaStore.MediaColumns.RELATIVE_PATH, "Download"); + uri = getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cv); + if (uri == null) throw new IOException("Downloads not available"); + try (OutputStream o = getContentResolver().openOutputStream(uri)) { o.write(zip); } + where = t("Descargas/", "Download/") + name; + } else { + File dir = getExternalFilesDir(android.os.Environment.DIRECTORY_DOWNLOADS); + if (dir == null) dir = getFilesDir(); + File f = new File(dir, name); + try (FileOutputStream o = new FileOutputStream(f)) { o.write(zip); } + where = f.getAbsolutePath(); + } + logLine(t("Diagnóstico guardado: ", "Diagnostics saved: ") + where); + final Uri shareUri = uri; + ui.post(() -> { + android.widget.Toast.makeText(this, t("Guardado en ", "Saved to ") + where, + android.widget.Toast.LENGTH_LONG).show(); + if (shareUri != null) { + Intent i = new Intent(Intent.ACTION_SEND); + i.setType("application/zip"); + i.putExtra(Intent.EXTRA_STREAM, shareUri); + i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivity(Intent.createChooser(i, t("Enviar diagnóstico", "Send diagnostics"))); + } + }); + } catch (Exception e) { + logLine(t("No se pudo guardar el diagnóstico: ", "Could not save diagnostics: ") + e); + } + }); + } + + private void shareLog() { + String text; + synchronized (fullLog) { text = fullLog.toString(); } + String[] sum = diag.summary(es); + String head = "FM-1 Rescue " + board() + " · " + installedName() + "\n" + sum[0] + "\n" + sum[1] + "\n\n"; + Intent i = new Intent(Intent.ACTION_SEND); + i.setType("text/plain"); + i.putExtra(Intent.EXTRA_SUBJECT, "FM-1 Rescue log"); + String body = head + text; + if (body.length() > 90_000) body = head + "…\n" + text.substring(text.length() - 90_000 + head.length()); + i.putExtra(Intent.EXTRA_TEXT, body); + startActivity(Intent.createChooser(i, t("Compartir registro", "Share the log"))); + } + + // ------------------------------------------------------------ files + + private File v15File() { return new File(getFilesDir(), "FM-1-V15.fwsc"); } + private File customFile() { return new File(getFilesDir(), "custom.fwsc"); } + + private String source() { return prefs.getString("src", "jiant"); } + + /** The package to restore, or null while it is not available. */ + private byte[] selected() { + switch (source()) { + case "v15": return v15Pkg; + case "custom": return customPkg; + default: return jiantPkg; + } + } + + /** What the board logs and the payload carries. */ + private String label() { + switch (source()) { + case "v15": return "FM-1_015 official V15"; + case "custom": return customLabel; + default: return "JIANT " + jiantVersion; + } + } + + private String installedName() { + switch (source()) { + case "v15": return "V15"; + case "custom": return customLabel; + default: return "JIANT " + jiantVersion; + } + } + + private void loadFiles() { + // The public JIANT, put in by android/rescue/fetch_firmware.py when the APK is built. + try (InputStream in = getAssets().open("jiant.fwsc"); InputStream js = getAssets().open("jiant.json")) { + byte[] d = readAll(in); + RescueImage.checkFirmware(d); + String meta = new String(readAll(js), StandardCharsets.UTF_8); + java.util.regex.Matcher m = java.util.regex.Pattern.compile("\"version\"\\s*:\\s*\"([^\"]*)\"").matcher(meta); + jiantVersion = m.find() ? m.group(1) : ""; + jiantPkg = d; + } catch (Exception e) { + jiantPkg = null; + logLine("JIANT: " + e.getMessage()); + } + // The official V15: inside the APK (fetch_firmware.py), else the copy downloaded or chosen earlier. + try (InputStream in = getAssets().open("FM-1-V15.fwsc")) { + byte[] d = readAll(in); + RescueImage.checkV15(d); + v15Pkg = d; + } catch (Exception e) { v15Pkg = null; } + try { + if (v15Pkg == null && v15File().exists()) { + byte[] d = readFile(v15File()); + RescueImage.checkV15(d); + v15Pkg = d; + } + } catch (Exception e) { v15Pkg = null; } + try { + if (customFile().exists()) { + byte[] d = readFile(customFile()); + RescueImage.Firmware f = RescueImage.checkFirmware(d); + customLabel = prefs.getString("customLabel", f.identity); + customPkg = d; + } + } catch (Exception e) { customPkg = null; } + // jl-uboot-tool's loader ships in the APK (MIT, assets/wl82loader-LICENSE.txt). + try (InputStream in = getAssets().open("wl82loader.bin")) { + loader = RescueImage.checkLoader(readAll(in)); + } catch (Exception e) { + loader = null; + logLine("loader: " + e.getMessage()); + } + if (jiantPkg == null && source().equals("jiant")) { + prefs.edit().putString("src", "v15").apply(); + ui.post(() -> srcV15.setChecked(true)); + } + updateFileTexts(); + if (v15Pkg == null && source().equals("v15")) net.execute(this::downloadV15); + } + + private volatile boolean downloading; + + private void updateFileTexts() { + ui.post(() -> { + srcJiant.setText(jiantPkg != null + ? t("JIANT " + jiantVersion + " (incluido · recomendado: sirve para FM-1 que venían en V15 o en V16)", + "JIANT " + jiantVersion + " (included · recommended: works on FM-1s that came with V15 or V16)") + : t("JIANT (no incluido en esta compilación)", "JIANT (not included in this build)")); + srcJiant.setEnabled(jiantPkg != null); + srcV15.setText(v15Pkg != null || !downloading + ? t("V15 oficial de M-VAVE (incluida)", "Official M-VAVE V15 (included)") + : t("V15 oficial de M-VAVE (descargando…)", "Official M-VAVE V15 (downloading…)")); + srcCustom.setText(t("Mi archivo: ", "My file: ") + customLabel); + srcCustom.setVisibility(customPkg != null ? View.VISIBLE : View.GONE); + + String st; + int color = 0xFF2E8B57; + if (selected() != null) { + st = t("✓ Listo para instalar: ", "✓ Ready to install: ") + installedName(); + if (source().equals("v15")) st += t(". Ojo: si tu FM-1 venía en V16, usa JIANT.", + ". Note: if your FM-1 came with V16, use JIANT."); + } else if (source().equals("v15")) { + st = downloading ? t("Descargando la V15 oficial…", "Downloading the official V15…") + : t("No se pudo descargar la V15 (¿sin internet?). Se reintenta sola.", + "Could not download V15 (no internet?). It retries by itself."); + color = 0xFF1D1D1B; + } else { + st = t("No disponible.", "Not available."); + color = 0xFFC0392B; + } + fwscText.setText(st); + fwscText.setTextColor(color); + loaderText.setText(loader != null ? t("✓ Loader de JieLi incluido", "✓ JieLi loader included") + : t("✗ El loader incluido está dañado: reinstala la app.", "✗ The bundled loader is damaged: reinstall the app.")); + }); + } + + /** The official V15, downloaded once and kept; accepted only if its firmware region hash is V15's. */ + private void downloadV15() { + if (v15Pkg != null || downloading) return; + downloading = true; + updateFileTexts(); + try { + HttpURLConnection c = (HttpURLConnection) new URL(RescueImage.V15_URL).openConnection(); + c.setConnectTimeout(15000); + c.setReadTimeout(30000); + byte[] d; + try (InputStream in = c.getInputStream()) { d = readAll(in); } + RescueImage.checkV15(d); + try (FileOutputStream o = new FileOutputStream(v15File())) { o.write(d); } + v15Pkg = d; + logLine(t("V15 descargada y verificada", "V15 downloaded and verified")); + downloading = false; + updateFileTexts(); + } catch (Exception e) { + downloading = false; + logLine("V15: " + e.getMessage()); + updateFileTexts(); + if (source().equals("v15")) ui.postDelayed(() -> net.execute(this::downloadV15), 15000); + } + } + + private static byte[] readAll(InputStream in) throws IOException { + ByteArrayOutputStream o = new ByteArrayOutputStream(); + byte[] buf = new byte[16384]; + for (int n; (n = in.read(buf)) > 0; ) o.write(buf, 0, n); + return o.toByteArray(); + } + + @Override + protected void onActivityResult(int req, int res, Intent data) { + super.onActivityResult(req, res, data); + if (req != PICK_FWSC || res != RESULT_OK || data == null) return; + Uri u = data.getData(); + try (InputStream in = getContentResolver().openInputStream(u)) { + byte[] d = readAll(in); + RescueImage.Firmware f = RescueImage.checkFirmware(d); + if (f.official) { + try (FileOutputStream o = new FileOutputStream(v15File())) { o.write(d); } + v15Pkg = d; + prefs.edit().putString("src", "v15").apply(); + ui.post(() -> srcV15.setChecked(true)); + logLine("V15 OK"); + } else { + try (FileOutputStream o = new FileOutputStream(customFile())) { o.write(d); } + customPkg = d; + String name = u.getLastPathSegment() == null ? "" : u.getLastPathSegment(); + name = name.substring(name.lastIndexOf('/') + 1).replaceAll("\\.fwsc$", ""); + customLabel = (name.isEmpty() ? f.identity : name + " (" + f.identity + ")"); + if (customLabel.length() > 60) customLabel = customLabel.substring(0, 60); + prefs.edit().putString("src", "custom").putString("customLabel", customLabel).apply(); + ui.post(() -> srcCustom.setChecked(true)); + logLine(t("Paquete aceptado: ", "Package accepted: ") + customLabel); + } + } catch (RescueImage.Refused e) { + logLine(t("Rechazado: ", "Refused: ") + e.getMessage()); + String why = e.getMessage().contains("FM-1_016") + ? t("Esto es la V16 oficial: no cabe en la zona que escribe el rescate. Usa JIANT; después, si quieres, " + + "instala la V16 con \"Volver al oficial\" del instalador web.", + "This is the official V16: it does not fit the area the rescue writes. Use JIANT; then, if you " + + "like, install V16 with the web installer's \"Return to official\".") + : e.getMessage(); + ui.post(() -> { + fwscText.setText(t("✗ Rechazado: ", "✗ Refused: ") + why); + fwscText.setTextColor(0xFFC0392B); + }); + return; + } catch (IOException e) { + logLine("read: " + e.getMessage()); + return; + } + updateFileTexts(); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); // USB_DEVICE_ATTACHED: the poll picks the board up + } + + @Override + protected void onDestroy() { + stopMonitor = true; + ui.removeCallbacksAndMessages(null); + usb.shutdownNow(); + net.shutdownNow(); + super.onDestroy(); + } + + // ------------------------------------------------------------ USB + + private UsbDevice find(int pid) { + for (UsbDevice d : usbManager.getDeviceList().values()) { + if (d.getVendorId() == Picoboot.VID && d.getProductId() == pid) return d; + } + return null; + } + + private boolean permitted(UsbDevice d) { + if (usbManager.hasPermission(d)) return true; + if (asked.add(d.getDeviceName())) { + int flags = Build.VERSION.SDK_INT >= 31 ? PendingIntent.FLAG_MUTABLE : 0; + Intent i = new Intent(ACTION_PERMISSION).setPackage(getPackageName()); + usbManager.requestPermission(d, PendingIntent.getBroadcast(this, 0, i, flags)); + } + show(t("Permite el acceso USB", "Allow USB access"), + t("Acepta el aviso de Android (marca \"usar siempre\" para no volver a verlo).", + "Accept Android's prompt (tick \"always\" not to see it again)."), 0); + return false; + } + + private final Runnable poll = new Runnable() { + @Override public void run() { + try { tick(); } catch (Exception e) { logLine("poll: " + e); } + ui.postDelayed(this, 700); + } + }; + + private void tick() { + if (busy) return; + UsbDevice boot = find(Picoboot.PID_BOOTSEL), fw = find(PID_RESCUE); + if (monitoring != null && (fw == null || !fw.getDeviceName().equals(monitoring))) stopMonitor = true; + reflash.setVisibility(fw != null && monitoring != null ? View.VISIBLE : View.GONE); + + if (boot != null) { + if (selected() == null || loader == null) { + show(t("RP2040 conectado", "RP2040 connected"), + selected() == null ? t("Esperando el firmware del paso 1 (la V15 necesita internet la primera vez).", + "Waiting for the firmware of step 1 (V15 needs the internet the first time).") + : t("El loader incluido está dañado: reinstala la app.", "The bundled loader is damaged: reinstall the app."), 0); + return; + } + if (!permitted(boot)) return; + busy = true; + usb.execute(() -> program(boot)); + return; + } + if (fw != null) { + if (monitoring == null) { + if (!permitted(fw)) return; + monitoring = fw.getDeviceName(); + stopMonitor = false; + usb.execute(() -> monitor(fw)); + } + return; + } + UsbDevice other = otherRp2040(); + if (other != null) { + // An RP2040 with some other firmware (MicroPython, a demo, a Pico SDK program): send it to BOOTSEL + // ourselves, once per plug-in, so BOOT does not have to be held. + if (!permitted(other)) return; + if (kicked.add(other.getDeviceName())) { + show(t("RP2040 con otro programa", "RP2040 with another program"), + t("Pasándolo a modo de grabación…", "Switching it to programming mode…"), 0); + usb.execute(() -> kickToBootsel(other)); + } else { + show(t("No responde al reinicio", "It does not answer the reset"), + t("Desconéctalo, mantén BOOT pulsado y vuelve a enchufarlo.", + "Unplug it, hold BOOT and plug it in again."), 0); + } + return; + } + if (monitoring == null) { + show(t("Conecta el RP2040", "Plug in the RP2040"), + t("Enchúfalo al móvil con un adaptador OTG. Si la app no lo detecta, desconéctalo y vuelve a " + + "enchufarlo manteniendo BOOT pulsado.", + "Plug it into the phone with an OTG adapter. If the app does not see it, unplug it and plug " + + "it in again holding BOOT."), 0); + } + } + + private final Set kicked = new HashSet<>(); + + /** A Raspberry Pi VID device that is neither the boot ROM nor the rescue firmware. */ + private UsbDevice otherRp2040() { + for (UsbDevice d : usbManager.getDeviceList().values()) { + if (d.getVendorId() == Picoboot.VID && d.getProductId() != Picoboot.PID_BOOTSEL + && d.getProductId() != PID_RESCUE) return d; + } + return null; + } + + /** + * Reboots a running RP2040 into BOOTSEL: the Raspberry Pi reset interface (Pico SDK programs, + * picotool's way), else the "1200 baud touch" on each CDC port (MicroPython, Arduino, Pico SDK). + * Runs on the USB thread; the board drops off the bus if it worked. + */ + private void kickToBootsel(UsbDevice d) { + UsbDeviceConnection c = usbManager.openDevice(d); + if (c == null) return; + try { + boolean done = false; + for (int i = 0; i < d.getInterfaceCount() && !done; i++) { + UsbInterface f = d.getInterface(i); + if (f.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC && f.getInterfaceSubclass() == 0 + && f.getInterfaceProtocol() == 1) { + c.claimInterface(f, true); + logLine(t("Reinicio a BOOT por la interfaz de reset", "Reset to BOOT via the reset interface")); + c.controlTransfer(0x41, 0x01, 0, f.getId(), null, 0, 1000); // RESET_REQUEST_BOOTSEL + done = true; + } + } + for (int i = 0; i < d.getInterfaceCount() && !done; i++) { + UsbInterface f = d.getInterface(i); + if (f.getInterfaceClass() != UsbConstants.USB_CLASS_COMM) continue; + c.claimInterface(f, true); + byte[] coding = {(byte) 0xB0, 0x04, 0, 0, 0, 0, 8}; // 1200 baud, 8N1 + logLine(t("Reinicio a BOOT con 1200 baudios (puerto ", "Reset to BOOT with 1200 baud (port ") + + f.getId() + ")"); + c.controlTransfer(0x21, 0x22, 0x0003, f.getId(), null, 0, 500); // DTR + RTS on + c.controlTransfer(0x21, 0x20, 0, f.getId(), coding, coding.length, 500); // SET_LINE_CODING + c.controlTransfer(0x21, 0x22, 0x0000, f.getId(), null, 0, 500); // DTR off: the "touch" + } + } catch (Exception e) { + logLine("reset: " + e.getMessage()); + } finally { + c.close(); + } + sleep(2500); + } + + /** Programs the board in BOOTSEL over PICOBOOT. Runs on the USB thread. */ + private void program(UsbDevice d) { + UsbDeviceConnection conn = null; + try { + show(t("Preparando…", "Preparing…"), "", 0); + byte[] base = readAll(getAssets().open("fm1-rescue-base-" + board() + ".uf2")); + byte[] pkg = selected(); + if (pkg == null) throw new IOException(t("no hay firmware elegido", "no firmware chosen")); + TreeMap plan = RescueImage.build(base, pkg, label(), loader); + prefs.edit().putString("lastInstalled", installedName()).apply(); + + UsbInterface itf = null; + UsbEndpoint in = null, out = null; + for (int i = 0; i < d.getInterfaceCount() && itf == null; i++) { + UsbInterface f = d.getInterface(i); + if (f.getInterfaceClass() != UsbConstants.USB_CLASS_VENDOR_SPEC) continue; + for (int e = 0; e < f.getEndpointCount(); e++) { + UsbEndpoint ep = f.getEndpoint(e); + if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) continue; + if (ep.getDirection() == UsbConstants.USB_DIR_IN) in = ep; else out = ep; + } + if (in != null && out != null) itf = f; + } + if (itf == null) throw new IOException("no PICOBOOT interface"); + conn = usbManager.openDevice(d); + if (conn == null || !conn.claimInterface(itf, true)) throw new IOException("cannot open the RP2040"); + final UsbDeviceConnection c = conn; + final UsbEndpoint fin = in, fout = out; + final int itfId = itf.getId(); + Picoboot pb = new Picoboot(new Picoboot.Transport() { + public int bulkOut(byte[] b, int len, int to) { return c.bulkTransfer(fout, b, len, to); } + public int bulkIn(byte[] b, int len, int to) { return c.bulkTransfer(fin, b, len, to); } + public int controlOut(int req, int to) { return c.controlTransfer(0x41, req, 0, itfId, null, 0, to); } + }); + logLine(t("Grabando ", "Programming ") + plan.size() + t(" sectores (", " sectors (") + board() + ")"); + pb.program(plan, (what, n, total) -> { + boolean w = what.equals("write"); + show(t("Grabando el RP2040…", "Programming the RP2040…"), + (w ? t("Escribiendo ", "Writing ") : t("Comprobando ", "Checking ")) + n + " / " + total, + w ? n * 700 / total : 700 + n * 300 / total); + }); + logLine(t("RP2040 grabado y verificado; reiniciando", "RP2040 programmed and verified; rebooting")); + show(t("RP2040 listo", "RP2040 ready"), t("Reiniciando…", "Rebooting…"), 1000); + } catch (Exception e) { + logLine("ERROR: " + e.getMessage()); + show(t("No se pudo grabar el RP2040", "Could not program the RP2040"), + e.getMessage() + t("\nDesconéctalo y vuelve a conectarlo con BOOT pulsado.", + "\nUnplug it and plug it in again with BOOT held."), 0); + sleep(4000); + } finally { + if (conn != null) conn.close(); + sleep(1500); + busy = false; + } + } + + /** Sends a board running the rescue firmware back to BOOTSEL (Raspberry Pi reset interface). */ + private void resetToBootsel(UsbDevice d) { + stopMonitor = true; + usb.execute(() -> { + UsbDeviceConnection c = usbManager.openDevice(d); + if (c == null) return; + try { + for (int i = 0; i < d.getInterfaceCount(); i++) { + UsbInterface f = d.getInterface(i); + if (f.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC && f.getInterfaceProtocol() == 1) { + c.claimInterface(f, true); + logLine(t("Pasando el RP2040 a modo BOOT", "Sending the RP2040 to BOOT mode")); + c.controlTransfer(0x41, 0x01, 0, f.getId(), null, 0, 1000); // RESET_REQUEST_BOOTSEL + } + } + } finally { + c.close(); + } + }); + } + + /** Reads the rescue progress from the board's data port. Runs on the USB thread until detach. */ + private void monitor(UsbDevice d) { + UsbDeviceConnection c = usbManager.openDevice(d); + try { + if (c == null) throw new IOException("cannot open the board"); + UsbInterface data = null; + UsbEndpoint in = null, out = null; + for (int i = 0; i < d.getInterfaceCount(); i++) { + UsbInterface f = d.getInterface(i); + if (f.getId() == 3 && f.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) data = f; + } + if (data == null) throw new IOException("no data port"); + for (int e = 0; e < data.getEndpointCount(); e++) { + UsbEndpoint ep = data.getEndpoint(e); + if (ep.getDirection() == UsbConstants.USB_DIR_IN) in = ep; else out = ep; + } + if (!c.claimInterface(data, true)) throw new IOException("data port busy"); + c.controlTransfer(0x21, 0x22, 0x0001, 2, null, 0, 1000); // DTR on CDC 1 (interface 2) + + // The console (CDC 0, data interface 1): the Transporter's log, read all the time (an + // unread console can stall it) and turned into the diagnosis. + UsbEndpoint cin = null; + for (int i = 0; i < d.getInterfaceCount(); i++) { + UsbInterface f = d.getInterface(i); + if (f.getId() == 1 && f.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA && c.claimInterface(f, true)) { + for (int e = 0; e < f.getEndpointCount(); e++) { + UsbEndpoint ep = f.getEndpoint(e); + if (ep.getDirection() == UsbConstants.USB_DIR_IN && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) cin = ep; + } + } + } + diag = new Diagnosis(); + if (cin != null) c.controlTransfer(0x21, 0x22, 0x0001, 0, null, 0, 1000); // DTR on CDC 0 + else logLine(t("Sin consola del RP2040: no habrá diagnóstico", "No RP2040 console: no diagnostics")); + + byte[] req = "rescue\n".getBytes(StandardCharsets.US_ASCII); + byte[] buf = new byte[512], cbuf = new byte[512]; + StringBuilder pending = new StringBuilder(), cpending = new StringBuilder(); + long nextReq = 0, lastStatus = System.currentTimeMillis(); + boolean warned = false; + while (!stopMonitor) { + long now = System.currentTimeMillis(); + String cmd = pendingCmd; + if (cmd != null) { + pendingCmd = null; + byte[] cb = (cmd + "\n").getBytes(StandardCharsets.US_ASCII); + c.bulkTransfer(out, cb, cb.length, 500); + if (cmd.equals("rekey")) diag = new Diagnosis(); + } + if (now >= nextReq) { + c.bulkTransfer(out, req, req.length, 300); + nextReq = now + 700; + } + if (cin != null) { + int n = c.bulkTransfer(cin, cbuf, cbuf.length, 40); + if (n > 0) { + cpending.append(new String(cbuf, 0, n, StandardCharsets.ISO_8859_1)); + int nl; + while ((nl = cpending.indexOf("\n")) >= 0) { + String line = cpending.substring(0, nl).replace("\r", ""); + cpending.delete(0, nl + 1); + consoleLine(line); + } + if (cpending.length() > 4096) cpending.setLength(0); + } + } + int n = c.bulkTransfer(in, buf, buf.length, 40); + if (n > 0) { + pending.append(new String(buf, 0, n, StandardCharsets.US_ASCII)); + int nl; + while ((nl = pending.indexOf("\n")) >= 0) { + String raw = pending.substring(0, nl).trim(); + RescueStatus st = RescueStatus.parse(raw); + pending.delete(0, nl + 1); + if (st != null && !raw.equals(lastStatusLine)) { + lastStatusLine = raw; + synchronized (statusLog) { + statusLog.append(stamp()).append(" ").append(raw).append('\n'); + if (statusLog.length() > 500_000) statusLog.delete(0, statusLog.length() - 400_000); + } + } + if (st != null) { + lastStatus = now; + warned = false; + report(d, st); + } + } + if (pending.length() > 4096) pending.setLength(0); + } + if (!warned && now - lastStatus > 5000) { + warned = true; + show(t("La placa no responde", "The board does not answer"), + t("¿Es una placa con el firmware FM-1 Rescue? Desconéctala y vuelve a conectarla.", + "Is it a board with the FM-1 Rescue firmware? Unplug and re-plug it."), 0); + } + } + } catch (Exception e) { + logLine("monitor: " + e.getMessage()); + sleep(1500); + } finally { + if (c != null) c.close(); + monitoring = null; + } + } + + private String lastState = ""; + private long offSince; + + /** The board's identity for "once per board": its serial number (unique RP2040 ID), else the port. */ + private String boardKey(UsbDevice d) { + try { + String sn = d.getSerialNumber(); + if (sn != null && !sn.isEmpty()) return sn; + } catch (SecurityException e) { /* no permission yet */ } + return d.getDeviceName(); + } + + private void report(UsbDevice d, RescueStatus s) { + if (!s.state.equals(lastState)) { + logLine("FM-1 Rescue: " + s.state + (s.err.equals("none") ? "" : " (" + s.err + " @ " + s.addr + ")")); + lastState = s.state; + } + if (!s.state.equals("off")) offSince = 0; + switch (s.state) { + case "boot": + show(t("Iniciando el RP2040…", "Starting the RP2040…"), "", 0); + break; + case "off": + // "off" for a few seconds in a row: a plain Transporter (no payload). Older rescue firmware + // also said "off" for its first seconds, so a single "off" proves nothing. + if (offSince == 0) offSince = System.currentTimeMillis(); + if (System.currentTimeMillis() - offSince < 4000) { + show(t("Comprobando el RP2040…", "Checking the RP2040…"), "", 0); + break; + } + // fall through + case "bad-payload": + // A plain Transporter, or a damaged payload: reprogram it, once per board. + if (selected() != null && loader != null && autoReset.add(boardKey(d))) { + show(t("Actualizando el RP2040…", "Updating the RP2040…"), "", 0); + resetToBootsel(d); + } else { + show(t("El RP2040 no tiene la V15 dentro", "The RP2040 has no V15 inside"), + t("Espera a que la V15 esté lista y pulsa \"Volver a grabar el RP2040\".", + "Wait for V15 to be ready and press \"Reprogram the RP2040\"."), 0); + } + break; + case "wait": + if (s.foreign) { + show(t("Apaga el FM-1", "Switch the FM-1 off"), + t("Está encendido con otro firmware. Apágalo, desconecta y vuelve a conectar el RP2040, y enciéndelo.", + "It is running another firmware. Switch it off, re-plug the RP2040, switch it on."), 0); + } else { + show(t("Enciende el FM-1 ahora", "Switch the FM-1 on now"), + board().equals("pico") + ? t("Tiene que haber estado apagado. El LED de la Pico parpadea lento.", + "It must have been off. The Pico's LED blinks slowly.") + : t("Tiene que haber estado apagado. El LED del RP2040 parpadea en amarillo.", + "It must have been off. The RP2040's LED blinks yellow."), 0); + } + break; + case "run": + String ph = s.phase.equals("verify") ? t("comprobando", "checking") + : s.phase.equals("write") ? t("escribiendo", "writing") : t("conectando", "connecting"); + show(t("Reparando el FM-1…", "Repairing the FM-1…"), + ph + " " + s.sector + " / " + s.sectors + t(" (no desconectes nada)", " (do not unplug anything)"), + s.permille()); + break; + case "done": + show(t("¡Listo! ✓", "Done! ✓"), + t("Apaga el FM-1, quita los cables y vuelve a encenderlo: arranca con " + + prefs.getString("lastInstalled", "el firmware instalado") + ". Los datos guardados (canciones, ajustes) no se tocaron.", + "Switch the FM-1 off, remove the wires and switch it on: it boots " + + prefs.getString("lastInstalled", "the installed firmware") + ". Saved data (songs, settings) was not touched."), 1000); + break; + case "error": + show(t("Error", "Error"), errorText(s), 0); + break; + default: + show(s.state, "", 0); + } + } + + private String errorText(RescueStatus s) { + String again = t("Apaga el FM-1, desconecta y vuelve a conectar el RP2040, y enciende el FM-1 otra vez.", + "Switch the FM-1 off, unplug and re-plug the RP2040, switch the FM-1 on again."); + switch (s.err) { + case "chip": return t("Esto no parece un FM-1 (chip o memoria distintos). No se escribió nada.", + "This does not look like an FM-1 (other chip or flash). Nothing was written."); + case "link": return t("Se perdió la conexión antes de escribir nada. Revisa los cables (prueba a cambiar verde y blanco). ", + "The connection was lost before anything was written. Check the wires (try swapping green and white). ") + again; + case "write": return t("Una escritura no se completó en " + s.addr + ": el firmware quedó a medias. Repite: ", + "A write did not complete at " + s.addr + ": the firmware is incomplete. Repeat: ") + again; + default: return t("La comprobación final no coincide. Repite: ", "The final check does not match. Repeat: ") + again; + } + } + + private static void sleep(long ms) { + try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + } +} diff --git a/android/rescue/app/src/main/java/fm/jiant/rescue/Picoboot.java b/android/rescue/app/src/main/java/fm/jiant/rescue/Picoboot.java new file mode 100644 index 00000000..9d230d3a --- /dev/null +++ b/android/rescue/app/src/main/java/fm/jiant/rescue/Picoboot.java @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MIT +// PICOBOOT: the RP2040 boot ROM's vendor USB interface (the one picotool uses), +// spoken directly, so the app programs the board with no RPI-RP2 drive and no +// file copy. Commands: 32-byte header on bulk OUT, optional data stage, then a +// zero-length ack in the opposite direction (RP2040 datasheet, 2.8.5). +package fm.jiant.rescue; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; +import java.util.Map; +import java.util.TreeMap; + +public final class Picoboot { + public static final int VID = 0x2E8A, PID_BOOTSEL = 0x0003; + static final int MAGIC = 0x431FD10B; + static final int CMD_EXCLUSIVE_ACCESS = 0x01, CMD_REBOOT = 0x02, CMD_FLASH_ERASE = 0x03, + CMD_READ = 0x84, CMD_WRITE = 0x05, CMD_EXIT_XIP = 0x06, CMD_ENTER_CMD_XIP = 0x07; + static final int REQ_INTERFACE_RESET = 0x41; + static final int TIMEOUT_MS = 5000; + + /** The USB side: bulk endpoints of the PICOBOOT interface and its control requests. */ + public interface Transport { + /** Returns bytes sent, or < 0 on error. */ + int bulkOut(byte[] data, int len, int timeoutMs); + /** Returns bytes received, or < 0 on error. */ + int bulkIn(byte[] data, int len, int timeoutMs); + /** Host-to-device vendor request to the interface (no data). */ + int controlOut(int request, int timeoutMs); + } + + public interface Progress { + void step(String what, int done, int total); + } + + private final Transport t; + private int token = 1; + + public Picoboot(Transport t) { this.t = t; } + + private void cmd(int id, int cmdSize, int transferLen, byte[] args, byte[] data) throws IOException { + ByteBuffer b = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN); + b.putInt(MAGIC).putInt(token++).put((byte) id).put((byte) cmdSize).putShort((short) 0).putInt(transferLen); + if (args != null) b.put(args); + byte[] c = b.array(); + if (t.bulkOut(c, 32, TIMEOUT_MS) != 32) throw new IOException("PICOBOOT: command " + hex(id) + " not accepted"); + boolean in = (id & 0x80) != 0; + if (transferLen > 0) { + int n = in ? t.bulkIn(data, transferLen, TIMEOUT_MS) : t.bulkOut(data, transferLen, TIMEOUT_MS); + if (n != transferLen) throw new IOException("PICOBOOT: data stage of " + hex(id) + " failed"); + } + byte[] zlp = new byte[0]; + int ack = in ? t.bulkOut(zlp, 0, TIMEOUT_MS) : t.bulkIn(new byte[64], 64, TIMEOUT_MS); + if (ack != 0) throw new IOException("PICOBOOT: command " + hex(id) + " failed (no ack)"); + } + + private static byte[] args(int... v) { + ByteBuffer b = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN); + for (int x : v) b.putInt(x); + return Arrays.copyOf(b.array(), v.length * 4); + } + + private static String hex(int v) { return String.format("%02X", v); } + + public void reset() { t.controlOut(REQ_INTERFACE_RESET, 1000); } + + public void exclusive() throws IOException { cmd(CMD_EXCLUSIVE_ACCESS, 1, 0, new byte[] {1}, null); } + public void exitXip() throws IOException { cmd(CMD_EXIT_XIP, 0, 0, null, null); } + public void enterCmdXip() throws IOException { cmd(CMD_ENTER_CMD_XIP, 0, 0, null, null); } + public void erase(int addr, int size) throws IOException { cmd(CMD_FLASH_ERASE, 8, 0, args(addr, size), null); } + public void write(int addr, byte[] d) throws IOException { cmd(CMD_WRITE, 8, d.length, args(addr, d.length), d); } + public byte[] read(int addr, int size) throws IOException { + byte[] d = new byte[size]; + cmd(CMD_READ, 8, size, args(addr, size), d); + return d; + } + /** Reboot into the flash firmware (pc = 0, sp = 0). */ + public void reboot(int delayMs) throws IOException { cmd(CMD_REBOOT, 12, 0, args(0, 0, delayMs), null); } + + /** Erase, write and read back every sector of the plan, then boot it. */ + public void program(TreeMap plan, Progress p) throws IOException { + int total = plan.size(), i = 0; + reset(); + exclusive(); + exitXip(); + for (Map.Entry e : plan.entrySet()) { + p.step("write", ++i, total); + erase(e.getKey(), RescueImage.SECTOR); + write(e.getKey(), e.getValue()); + } + enterCmdXip(); + i = 0; + for (Map.Entry e : plan.entrySet()) { + p.step("verify", ++i, total); + if (!Arrays.equals(read(e.getKey(), RescueImage.SECTOR), e.getValue())) { + throw new IOException(String.format("RP2040 flash verify failed at %08X", e.getKey())); + } + } + p.step("reboot", total, total); + reboot(300); + } +} diff --git a/android/rescue/app/src/main/java/fm/jiant/rescue/RescueImage.java b/android/rescue/app/src/main/java/fm/jiant/rescue/RescueImage.java new file mode 100644 index 00000000..28778ed7 --- /dev/null +++ b/android/rescue/app/src/main/java/fm/jiant/rescue/RescueImage.java @@ -0,0 +1,278 @@ +// SPDX-License-Identifier: MIT +// FM-1 Rescue: what gets programmed into the RP2040. The same steps as +// rescue/builder.js (the web page), in Java: the official V15 region out of +// FM-1.fwsc, JieLi's loader, the payload (rescue/firmware/src/payload.h) and +// the base rescue firmware (a .uf2 in the app's assets), merged into the +// 4 KiB flash sectors the app writes over PICOBOOT. No Android classes here, +// so android/rescue/test runs it on a computer. +package fm.jiant.rescue; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Map; +import java.util.TreeMap; +import java.util.zip.CRC32; + +public final class RescueImage { + public static final int FW_START = 0x4000; + public static final int FW_LEN = 0x8F000; + public static final int FW_END = FW_START + FW_LEN; + public static final String V15_REGION_SHA256 = + "6edf3c37fb5bbbc33607c89375ee024d5477c17914d72221c8c68e58a8255686"; + public static final int LOADER_LEN = 24064; + public static final String LOADER_SHA256 = + "d41da6126760c9d66660bcc0cac8d27d221806c5e369a8036921efe68dca5376"; + /** The official M-VAVE V15 FM-1.fwsc (file sha256 db1642b2..., the genuine one), as kept in + * Quixotic7/FM1Backups at a pinned commit; checkV15 accepts it only by its region hash. */ + public static final String V15_URL = "https://raw.githubusercontent.com/Quixotic7/FM1Backups/" + + "8cbc3b066ed15ec6a0d5a990efb78b56f6c17183/V15-FM-1.fwsc"; + public static final String LOADER_URL = + "https://raw.githubusercontent.com/kagaimiq/jl-uboot-tool/" + + "adb3f18889e88ac512ce0a3c4d8cc3d3cb30696a/data/loaderblobs/usb/wl82loader.bin"; + + static final int FLASH_BASE = 0x10000000; + static final int PL_FLASH = 0x10100000; + static final int PL_LOADER_OFF = 0x1000; + static final int PL_IMAGE_OFF = 0x8000; + static final int SECTOR = 4096; + + private static final int FWSC_BLOCK = 0x2F, FWSC_MARKED_BLOCKS = 20, FWSC_NO_CHAR = 0x7D; + private static final int UF2_MAGIC0 = 0x0A324655, UF2_MAGIC1 = 0x9E5D5157, + UF2_MAGIC_END = 0x0AB16F30, UF2_FLAG_FAMILY = 0x2000, RP2040_FAMILY = 0xE48BFF56; + + public static final class Refused extends Exception { + public Refused(String msg) { super(msg); } + } + + /** A firmware the rescue can write: its region 0x4000..0x92FFF and what it is. */ + public static final class Firmware { + public final String identity; // "FM-1_015", "FM-1_9xx" + public final boolean official; // the official M-VAVE V15 + public final byte[] region; + public final String sha256; // of the region + Firmware(String identity, boolean official, byte[] region, String sha256) { + this.identity = identity; this.official = official; this.region = region; this.sha256 = sha256; + } + } + + /** Kept for the V15-only callers and tests. */ + public static final class V15 { + public final String identity; + public final byte[] region; + public final String sha256; + V15(Firmware f) { identity = f.identity; region = f.region; sha256 = f.sha256; } + } + + private RescueImage() {} + + // ---- checksums ---- + + public static String sha256(byte[] d) { + try { + byte[] h = MessageDigest.getInstance("SHA-256").digest(d); + StringBuilder s = new StringBuilder(); + for (byte b : h) s.append(String.format("%02x", b & 0xFF)); + return s.toString(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + static int crc32(byte[] d, int off, int len) { + CRC32 c = new CRC32(); + c.update(d, off, len); + return (int) c.getValue(); + } + + private static int crc16(byte[] d, int off, int len) { + int c = 0; + for (int i = off; i < off + len; i++) { + c ^= (d[i] & 0xFF) << 8; + for (int k = 0; k < 8; k++) c = (c & 0x8000) != 0 ? ((c << 1) ^ 0x1021) & 0xFFFF : (c << 1) & 0xFFFF; + } + return c; + } + + private static byte[] jlEnc(byte[] src, int off, int len) { + byte[] out = Arrays.copyOfRange(src, off, off + len); + int k = 0xFFFF; + for (int i = 0; i < out.length; i++) { + out[i] ^= (byte) k; + k = ((k << 1) ^ ((k & 0x8000) != 0 ? 0x1021 : 0)) & 0xFFFF; + } + return out; + } + + private static int u16(byte[] p, int o) { return (p[o] & 0xFF) | (p[o + 1] & 0xFF) << 8; } + private static int u32(byte[] p, int o) { return u16(p, o) | u16(p, o + 2) << 16; } + + // ---- .fwsc ---- + + private static final class Parsed { + String identity; byte[] region; long flashLen; + } + + private static Parsed parse(byte[] data) throws Refused { + int stride = FWSC_BLOCK + 1, head = stride * FWSC_MARKED_BLOCKS; + if (data.length < head) throw new Refused("not an FM-1 .fwsc package (too short)"); + ByteArrayOutputStream img = new ByteArrayOutputStream(data.length); + StringBuilder id = new StringBuilder(); + for (int i = 0; i < FWSC_MARKED_BLOCKS; i++) { + img.write(data, i * stride, FWSC_BLOCK); + int m = data[i * stride + FWSC_BLOCK] & 0xFF; + if (m != FWSC_NO_CHAR) id.append((char) ((m - i - 1) & 0xFF)); + } + img.write(data, head, data.length - head); + byte[] image = img.toByteArray(); + + if (image.length < 0x400) throw new Refused("not a UFW package"); + byte[] hdr = jlEnc(image, 0, 0x40); + if (crc16(hdr, 2, 0x3E) != u16(hdr, 0)) throw new Refused("not an FM-1 .fwsc (UFW header CRC)"); + int nent = u16(hdr, 8); + if (nent == 0 || nent > 11) throw new Refused("UFW header lists " + nent + " entries"); + if (crc16(image, 0x40, nent * 0x50) != u16(hdr, 2)) throw new Refused("damaged package (UFW entry CRC)"); + long off = -1, len = 0; + for (int i = 0; i < nent; i++) { + byte[] e = jlEnc(image, 0x40 + i * 0x50, 0x50); + if (u16(e, 0) == 0) { off = u32(e, 8) & 0xFFFFFFFFL; len = u32(e, 12) & 0xFFFFFFFFL; } + } + if (off < 0) throw new Refused("no flash.bin in the package"); + if (off + len > image.length) throw new Refused("flash.bin runs past the package"); + if (len < FW_END) throw new Refused("not a complete FM-1 package"); + Parsed p = new Parsed(); + p.identity = id.toString(); + p.region = Arrays.copyOfRange(image, (int) off + FW_START, (int) off + FW_END); + p.flashLen = len; + return p; + } + + public static V15 checkV15(byte[] data) throws Refused { + Firmware f = checkFirmware(data); + if (!f.official) throw new Refused("this is not the official V15 (" + f.identity + ")"); + return new V15(f); + } + + private static final byte[] FELUCCA_LOADER = "FELUCCA-LOADER-1".getBytes(StandardCharsets.US_ASCII); + + private static boolean contains(byte[] hay, byte[] needle) { + outer: + for (int i = 0; i + needle.length <= hay.length; i++) { + for (int k = 0; k < needle.length; k++) if (hay[i + k] != needle[k]) continue outer; + return true; + } + return false; + } + + /** + * The official V15 (by its region hash), or a JIANT / Felucca-family package made by + * tools/fm1pkg_make.py: identity FM-1_9xx, flash.bin exactly 0x93000 (nothing past the + * region the rescue writes), Felucca's own update loader in it, a non-blank region. + */ + public static Firmware checkFirmware(byte[] data) throws Refused { + Parsed p = parse(data); + String sha = sha256(p.region); + if (sha.equals(V15_REGION_SHA256)) return new Firmware(p.identity, true, p.region, sha); + if (p.identity.equals("FM-1_015")) + throw new Refused("it says V15 but its firmware hash is not V15's: damaged or modified"); + if (!p.identity.matches("FM-1_9\\d\\d")) + throw new Refused("not the official V15 nor a JIANT package (identity " + + (p.identity.isEmpty() ? "none" : p.identity) + "). The official V16 does not fit the rescue."); + if (p.flashLen != FW_END) throw new Refused("this package runs past 0x92FFF; the rescue cannot write it"); + if (!contains(data, FELUCCA_LOADER)) throw new Refused("not a package made by JIANT's tools"); + boolean blank = true; + for (byte b : p.region) if (b != (byte) 0xFF && b != 0) { blank = false; break; } + if (blank) throw new Refused("the firmware region of this package is blank"); + return new Firmware(p.identity, false, p.region, sha); + } + + public static byte[] checkLoader(byte[] b) throws Refused { + if (b.length != LOADER_LEN) throw new Refused("wl82loader.bin must be " + LOADER_LEN + " bytes"); + if (!sha256(b).equals(LOADER_SHA256)) throw new Refused("wl82loader.bin has the wrong sha256"); + return b; + } + + // ---- payload ---- + + public static byte[] buildPayload(V15 v, byte[] loader) { + return buildPayload(new Firmware(v.identity, true, v.region, v.sha256), + (v.identity.isEmpty() ? "FM-1_015" : v.identity) + " official V15", loader); + } + + /** label: what the board logs and restores, e.g. "JIANT V10.7.58 (FM-1_910)". */ + public static byte[] buildPayload(Firmware v, String label, byte[] loader) { + byte[] p = new byte[PL_IMAGE_OFF + FW_LEN]; + Arrays.fill(p, (byte) 0xFF); + ByteBuffer h = ByteBuffer.wrap(p, 0, 256).order(ByteOrder.LITTLE_ENDIAN); + Arrays.fill(p, 0, 256, (byte) 0); + byte[] magic = "FM1-RESCUE-PL-1".getBytes(StandardCharsets.US_ASCII); + System.arraycopy(magic, 0, p, 0, magic.length); + h.putInt(16, 1).putInt(20, 256).putInt(24, PL_LOADER_OFF).putInt(28, LOADER_LEN) + .putInt(32, crc32(loader, 0, loader.length)).putInt(36, PL_IMAGE_OFF).putInt(40, FW_START) + .putInt(44, FW_LEN).putInt(48, crc32(v.region, 0, v.region.length)); + byte[] lab = label.replaceAll("[^\\x20-\\x7E]", "?").getBytes(StandardCharsets.US_ASCII); + System.arraycopy(lab, 0, p, 52, Math.min(lab.length, 63)); + for (int i = 0; i < 32; i++) p[116 + i] = (byte) Integer.parseInt(v.sha256.substring(2 * i, 2 * i + 2), 16); + h.putInt(252, crc32(p, 0, 252)); + System.arraycopy(loader, 0, p, PL_LOADER_OFF, LOADER_LEN); + System.arraycopy(v.region, 0, p, PL_IMAGE_OFF, FW_LEN); + return p; + } + + // ---- UF2 / flash sectors ---- + + /** Flash address -> 4 KiB sector content, for every sector the UF2 touches (rest 0xFF). */ + public static TreeMap sectorsOfUf2(byte[] uf2) throws Refused { + if (uf2.length == 0 || uf2.length % 512 != 0) throw new Refused("base firmware is not a UF2"); + TreeMap out = new TreeMap<>(); + ByteBuffer b = ByteBuffer.wrap(uf2).order(ByteOrder.LITTLE_ENDIAN); + for (int o = 0; o < uf2.length; o += 512) { + if (b.getInt(o) != UF2_MAGIC0 || b.getInt(o + 4) != UF2_MAGIC1 || b.getInt(o + 508) != UF2_MAGIC_END) + throw new Refused("base firmware: bad UF2 block"); + int flags = b.getInt(o + 8), addr = b.getInt(o + 12), size = b.getInt(o + 16), fam = b.getInt(o + 28); + if ((flags & UF2_FLAG_FAMILY) == 0 || fam != RP2040_FAMILY) throw new Refused("base firmware is not for the RP2040"); + if (size <= 0 || size > 476) throw new Refused("base firmware: bad UF2 block size"); + put(out, addr, uf2, o + 32, size); + } + return out; + } + + private static void put(TreeMap map, int addr, byte[] src, int off, int len) throws Refused { + long a = addr & 0xFFFFFFFFL; + if (a < FLASH_BASE || a + len > FLASH_BASE + 0x200000L) throw new Refused("write outside the 2 MiB flash"); + for (int i = 0; i < len; ) { + int sec = (int) ((a + i) & ~(SECTOR - 1L)); + int in = (int) ((a + i) - (sec & 0xFFFFFFFFL)); + int n = Math.min(len - i, SECTOR - in); + byte[] s = map.get(sec); + if (s == null) { s = new byte[SECTOR]; Arrays.fill(s, (byte) 0xFF); map.put(sec, s); } + System.arraycopy(src, off + i, s, in, n); + i += n; + } + } + + /** Base firmware + payload, as the flash sectors to write. */ + public static TreeMap flashPlan(byte[] baseUf2, byte[] payload) throws Refused { + TreeMap plan = sectorsOfUf2(baseUf2); + for (Map.Entry e : plan.entrySet()) { + if ((e.getKey() & 0xFFFFFFFFL) >= (PL_FLASH & 0xFFFFFFFFL)) throw new Refused("base firmware overlaps the payload"); + } + int[][] ranges = {{0, 256}, {PL_LOADER_OFF, PL_LOADER_OFF + LOADER_LEN}, {PL_IMAGE_OFF, PL_IMAGE_OFF + FW_LEN}}; + for (int[] r : ranges) put(plan, PL_FLASH + r[0], payload, r[0], r[1] - r[0]); + return plan; + } + + public static TreeMap build(byte[] baseUf2, byte[] fwsc, byte[] loader) throws Refused { + return build(baseUf2, fwsc, null, loader); + } + + /** label null: " official V15" or " JIANT". */ + public static TreeMap build(byte[] baseUf2, byte[] fwsc, String label, byte[] loader) throws Refused { + Firmware f = checkFirmware(fwsc); + if (label == null) label = f.identity + (f.official ? " official V15" : " JIANT"); + return flashPlan(baseUf2, buildPayload(f, label, checkLoader(loader))); + } +} diff --git a/android/rescue/app/src/main/java/fm/jiant/rescue/RescueStatus.java b/android/rescue/app/src/main/java/fm/jiant/rescue/RescueStatus.java new file mode 100644 index 00000000..0a219f9f --- /dev/null +++ b/android/rescue/app/src/main/java/fm/jiant/rescue/RescueStatus.java @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT +// The rescue firmware's answer to `rescue` on its data port (ar_status_line in +// rescue/firmware/src/autorescue.c), e.g. +// OK state=run phase=write sector=17/143 written=5 same=12 err=none addr=000000 +package fm.jiant.rescue; + +import java.util.HashMap; +import java.util.Map; + +public final class RescueStatus { + public final String state, phase, err, addr; + public final int sector, sectors, written, same; + public final boolean foreign; + + private RescueStatus(Map m) { + state = m.getOrDefault("state", "?"); + phase = m.getOrDefault("phase", "idle"); + err = m.getOrDefault("err", "none"); + addr = m.getOrDefault("addr", ""); + foreign = "1".equals(m.get("foreign")); + written = num(m.get("written")); + same = num(m.get("same")); + String s = m.getOrDefault("sector", "0/143"); + int slash = s.indexOf('/'); + sector = slash > 0 ? num(s.substring(0, slash)) : 0; + sectors = slash > 0 ? Math.max(1, num(s.substring(slash + 1))) : 143; + } + + private static int num(String s) { + try { return s == null ? 0 : Integer.parseInt(s.trim()); } catch (NumberFormatException e) { return 0; } + } + + /** null if the line is not a rescue status line. */ + public static RescueStatus parse(String line) { + if (line == null) return null; + line = line.trim(); + if (!line.startsWith("OK state=")) return null; + Map m = new HashMap<>(); + for (String tok : line.substring(3).split("\\s+")) { + int eq = tok.indexOf('='); + if (eq > 0) m.put(tok.substring(0, eq), tok.substring(eq + 1)); + } + return new RescueStatus(m); + } + + /** 0..1000 over the whole restore: check, write pass, verify pass. */ + public int permille() { + if ("done".equals(state)) return 1000; + if (!"run".equals(state)) return 0; + double f = (double) sector / sectors; + switch (phase) { + case "write": return (int) (20 + 600 * f); + case "verify": return (int) (620 + 380 * f); + default: return 10; + } + } +} diff --git a/android/rescue/app/src/main/res/xml/device_filter.xml b/android/rescue/app/src/main/res/xml/device_filter.xml new file mode 100644 index 00000000..d44f0a47 --- /dev/null +++ b/android/rescue/app/src/main/res/xml/device_filter.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/android/rescue/build.gradle b/android/rescue/build.gradle new file mode 100644 index 00000000..6352e2f6 --- /dev/null +++ b/android/rescue/build.gradle @@ -0,0 +1,3 @@ +plugins { + id "com.android.application" version "8.5.2" apply false +} diff --git a/android/rescue/fetch_firmware.py b/android/rescue/fetch_firmware.py new file mode 100644 index 00000000..8f74948d --- /dev/null +++ b/android/rescue/fetch_firmware.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Put the firmware the FM-1 Rescue restores into its APK (android/rescue/app/src/main/assets-firmware/): + + jiant.fwsc the package the site's installer offers (web/PUBLIC_RELEASE.json's version when listed, + else the first of firmware/versions.json) + jiant.json {"version", "product", "sha256"} + LICENSE-GPL-3.0.txt, LICENSE-Apache-2.0.txt (the package holds JieLi SDK files under Apache-2.0) + FM-1-V15.fwsc M-VAVE's official V15 (the owner's decision, 2026-11-20): Quixotic7/FM1Backups at a pinned + commit, accepted only with the genuine file's sha256 + + python3 android/rescue/fetch_firmware.py [SITE_URL] (the android workflow runs it before gradle) + python3 android/rescue/fetch_firmware.py --file PKG.fwsc VERSION (a local JIANT package instead) + +Same checks as web/make_site.py: identity FM-1_9xx and Felucca's own loader in it (no vendor files). +""" +import hashlib +import json +import re +import shutil +import sys +import urllib.request +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +OUT = HERE / "app" / "src" / "main" / "assets-firmware" +V15_URL = ("https://raw.githubusercontent.com/Quixotic7/FM1Backups/" + "8cbc3b066ed15ec6a0d5a990efb78b56f6c17183/V15-FM-1.fwsc") +V15_SHA256 = "db1642b2b6fa5c2cccb11ffd13878068bb28601678d3644049f99dc40e7edb8a" # M-VAVE's FM-1.fwsc, V15 +SITE = "https://juanjiant-bit.github.io/JIANT/" +BLOCKS, BLK, KEEP, NO_CHAR = 20, 0x30, 0x2F, 0x7D + + +def product_of(raw): + chars = [] + for i in range(BLOCKS): + m = raw[i * BLK + KEEP] + if m != NO_CHAR: + chars.append(chr((m - i - 1) & 0xFF)) + return "".join(chars) + + +def get(url): + req = urllib.request.Request(url, headers={"User-Agent": "fm1-rescue-build"}) + with urllib.request.urlopen(req, timeout=60) as r: + return r.read() + + +def write(raw, version): + product = product_of(raw) + if not re.fullmatch(r"FM-1_9\d\d", product): + raise SystemExit("identity %r is not a JIANT package (FM-1_9xx)" % product) + if b"FELUCCA-LOADER-1" not in raw: + raise SystemExit("no Felucca loader in the package: not one made by tools/fm1pkg_make.py") + OUT.mkdir(parents=True, exist_ok=True) + (OUT / "jiant.fwsc").write_bytes(raw) + sha = hashlib.sha256(raw).hexdigest() + (OUT / "jiant.json").write_text(json.dumps({"version": version, "product": product, "sha256": sha}) + "\n") + shutil.copy(ROOT / "LICENSE", OUT / "LICENSE-GPL-3.0.txt") + shutil.copy(ROOT / "LICENSES" / "Apache-2.0.txt", OUT / "LICENSE-Apache-2.0.txt") + print("assets-firmware: JIANT %s (%s), %d bytes, sha256 %s" % (version, product, len(raw), sha)) + + +def write_v15(): + raw = get(V15_URL) + sha = hashlib.sha256(raw).hexdigest() + if sha != V15_SHA256: + raise SystemExit("V15: sha256 %s is not the genuine FM-1.fwsc (%s)" % (sha, V15_SHA256)) + OUT.mkdir(parents=True, exist_ok=True) + (OUT / "FM-1-V15.fwsc").write_bytes(raw) + print("assets-firmware: official V15, %d bytes, sha256 %s" % (len(raw), sha)) + + +def main(): + if len(sys.argv) == 4 and sys.argv[1] == "--file": + write(Path(sys.argv[2]).read_bytes(), sys.argv[3]) + write_v15() + return + site = sys.argv[1] if len(sys.argv) > 1 else SITE + versions = json.loads(get(site + "firmware/versions.json")) + want = json.loads((ROOT / "web" / "PUBLIC_RELEASE.json").read_text()).get("version") + pick = next((v for v in versions if v.get("version") == want), versions[0]) + if not re.fullmatch(r"felucca-[A-Za-z0-9.-]+\.fwsc", pick["file"]): + raise SystemExit("unexpected file name %r" % pick["file"]) + write(get(site + "firmware/" + pick["file"]), pick["version"]) + write_v15() + + +if __name__ == "__main__": + main() diff --git a/android/rescue/gradle.properties b/android/rescue/gradle.properties new file mode 100644 index 00000000..89fd5629 --- /dev/null +++ b/android/rescue/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx2g +android.useAndroidX=false diff --git a/android/rescue/settings.gradle b/android/rescue/settings.gradle new file mode 100644 index 00000000..620e4e07 --- /dev/null +++ b/android/rescue/settings.gradle @@ -0,0 +1,9 @@ +// FM-1 Rescue for Android (android/rescue/LEEME.md) +pluginManagement { + repositories { google(); mavenCentral(); gradlePluginPortal() } +} +dependencyResolutionManagement { + repositories { google(); mavenCentral() } +} +rootProject.name = "fm1-rescue" +include ":app" diff --git a/android/rescue/test/DiagTest.java b/android/rescue/test/DiagTest.java new file mode 100644 index 00000000..d2e0d51a --- /dev/null +++ b/android/rescue/test/DiagTest.java @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT +// Diagnosis on real FM-1 Transporter logs: android/rescue/test/run_diag.sh LOG... +import fm.jiant.rescue.Diagnosis; +import java.nio.file.Files; +import java.nio.file.Path; + +public class DiagTest { + public static void main(String[] a) throws Exception { + for (String f : a) { + Diagnosis d = new Diagnosis(); + int n = 0; + for (String line : Files.readAllLines(Path.of(f))) { + int i = line.indexOf("console: "); + d.feed(i >= 0 ? line.substring(i + 9) : line); + n++; + } + String[] s = d.summary(true); + System.out.println(Path.of(f).getFileName() + " (" + n + " lines)\n -> " + s[0] + "\n " + s[1]); + } + // synthetic cases + String[][] cases = { + {"[ 1 us] KEY: sending 0x16EF", "[ 2 us] KEY: 4070 packets"}, + {"[ 1 us] KEY: sending 0x16EF", "[ 2 us] KEY: 300000 packets"}, + {"[ 1 us] KEY: sending", "D- pulled up instead of D+ - are D+/D- wired swapped?"}, + {"[ 1 us] ACK (data line held low) after 10 packets", "[ 2 us] HANDOFF: x", "[ 9 us] HOST: no device mounted yet (2.0 s after host start)"}, + {"[1 us] RESCUE: ERROR at 000000: this is not an FM-1 (chip key / flash ID)", "RESCUE: chip key 1234, type 3, flash id EF4014"}, + {"RESCUE: DONE in 80.1 s."}, + }; + for (String[] c : cases) { + Diagnosis d = new Diagnosis(); + for (String l : c) d.feed(l); + String[] s = d.summary(true); + System.out.println("synthetic: " + c[c.length - 1].substring(0, Math.min(40, c[c.length - 1].length())) + "\n -> " + s[0] + "\n " + s[1]); + } + } +} diff --git a/android/rescue/test/RescueTest.java b/android/rescue/test/RescueTest.java new file mode 100644 index 00000000..a5997cbd --- /dev/null +++ b/android/rescue/test/RescueTest.java @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MIT +// Computer-side test of the app's core (no Android, no phone): +// android/rescue/test/run.sh FM-1.fwsc V16.fwsc wl82loader.bin WEB.uf2 BASE_ZERO.uf2 +// WEB.uf2 is what rescue/fm1-rescue.html makes for the RP2040-Zero; the app +// must leave exactly that in the board's flash. The RP2040 is a mock that +// speaks PICOBOOT with real flash rules (erase to 0xFF, program only clears +// bits, flash reads only in command XIP mode, writes only after EXIT_XIP). +import fm.jiant.rescue.Picoboot; +import fm.jiant.rescue.RescueImage; +import fm.jiant.rescue.RescueStatus; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.TreeMap; + +public class RescueTest { + static int failures; + static void check(boolean ok, String what) { + if (!ok) { failures++; System.out.println(" FAIL: " + what); } + } + + static class MockRp2040 implements Picoboot.Transport { + final byte[] flash = new byte[2 * 1024 * 1024]; + boolean exclusive, xipOff, rebooted; + int erases, writes; + // command in progress + ByteBuffer cmd; int stage; // 0 = expect command, 1 = data, 2 = ack + byte[] readBack; + MockRp2040() { Arrays.fill(flash, (byte) 0x5A); } + + int addr() { return cmd.getInt(16) - 0x10000000; } + int size() { return cmd.getInt(20); } + + public int bulkOut(byte[] d, int len, int to) { + if (stage == 0) { + if (len != 32) return -1; + cmd = ByteBuffer.wrap(Arrays.copyOf(d, 32)).order(ByteOrder.LITTLE_ENDIAN); + if (cmd.getInt(0) != 0x431FD10B) return -1; + int id = cmd.get(8) & 0xFF, tl = cmd.getInt(12); + switch (id) { + case 0x01: exclusive = cmd.get(16) == 1; break; + case 0x06: xipOff = true; break; + case 0x07: xipOff = false; break; + case 0x02: rebooted = true; break; + case 0x03: + if (!exclusive || !xipOff || addr() % 4096 != 0 || size() % 4096 != 0) return -1; + Arrays.fill(flash, addr(), addr() + size(), (byte) 0xFF); + erases++; + break; + case 0x84: + if (xipOff) return -1; // flash not readable with XIP off + readBack = Arrays.copyOfRange(flash, addr(), addr() + size()); + break; + case 0x05: + if (!exclusive || !xipOff || addr() % 256 != 0 || size() % 256 != 0 || tl != size()) return -1; + break; + default: return -1; + } + stage = tl > 0 ? 1 : 2; + return 32; + } + int id = cmd.get(8) & 0xFF; + if (stage == 1 && id == 0x05) { + if (len != size()) return -1; + for (int i = 0; i < len; i++) flash[addr() + i] &= d[i]; // program only clears bits + writes++; + stage = 2; + return len; + } + if (stage == 2 && (id & 0x80) != 0 && len == 0) { stage = 0; return 0; } + return -1; + } + + public int bulkIn(byte[] d, int len, int to) { + int id = cmd == null ? 0 : cmd.get(8) & 0xFF; + if (stage == 1 && id == 0x84) { + System.arraycopy(readBack, 0, d, 0, size()); + stage = 2; + return size(); + } + if (stage == 2 && (id & 0x80) == 0) { stage = 0; return 0; } + return -1; + } + + public int controlOut(int req, int to) { stage = 0; return 0; } + } + + static byte[] flashOfUf2(byte[] uf2) { + byte[] f = new byte[2 * 1024 * 1024]; + Arrays.fill(f, (byte) 0x5A); // untouched sectors keep old contents + ByteBuffer b = ByteBuffer.wrap(uf2).order(ByteOrder.LITTLE_ENDIAN); + // The boot ROM erases each 4 KiB sector it writes, then programs the pages. + java.util.Set erased = new java.util.HashSet<>(); + for (int o = 0; o < uf2.length; o += 512) { + int a = b.getInt(o + 12) - 0x10000000, n = b.getInt(o + 16); + if (erased.add(a & ~4095)) Arrays.fill(f, a & ~4095, (a & ~4095) + 4096, (byte) 0xFF); + System.arraycopy(uf2, o + 32, f, a, n); + } + return f; + } + + public static void main(String[] a) throws Exception { + byte[] v15 = Files.readAllBytes(Path.of(a[0])), v16 = Files.readAllBytes(Path.of(a[1])); + byte[] loader = Files.readAllBytes(Path.of(a[2])), web = Files.readAllBytes(Path.of(a[3])); + byte[] base = Files.readAllBytes(Path.of(a[4])); + byte[] jiant = a.length > 5 ? Files.readAllBytes(Path.of(a[5])) : null; + byte[] jiantRegion = a.length > 6 ? Files.readAllBytes(Path.of(a[6])) : null; + + System.out.println("1. V15 accepted, V16 and a damaged package refused, loader checked"); + RescueImage.V15 v = RescueImage.checkV15(v15); + check(v.identity.equals("FM-1_015"), "identity " + v.identity); + try { RescueImage.checkV15(v16); check(false, "V16 accepted"); } catch (RescueImage.Refused e) { } + byte[] bad = v15.clone(); bad[40000] ^= 1; + try { RescueImage.checkV15(bad); check(false, "damaged V15 accepted"); } catch (RescueImage.Refused e) { } + byte[] badLoader = loader.clone(); badLoader[5] ^= 1; + try { RescueImage.checkLoader(badLoader); check(false, "bad loader accepted"); } catch (RescueImage.Refused e) { } + + System.out.println("2. PICOBOOT programming leaves exactly the web page's .uf2 in the flash"); + TreeMap plan = RescueImage.build(base, v15, loader); + MockRp2040 rp = new MockRp2040(); + int[] last = {0}; + new Picoboot(rp).program(plan, (w, d, t) -> last[0] = d); + check(rp.rebooted, "not rebooted"); + check(rp.erases == plan.size() && rp.writes == plan.size(), "erases " + rp.erases + " writes " + rp.writes); + check(Arrays.equals(rp.flash, flashOfUf2(web)), "flash differs from the web .uf2"); + + System.out.println("3. a flash that does not take the write is reported"); + MockRp2040 stuck = new MockRp2040() { + @Override public int bulkOut(byte[] d, int len, int to) { + int r = super.bulkOut(d, len, to); + if (stage == 2 && (cmd.get(8) & 0xFF) == 0x05 && addr() == 0x108000) flash[addr()] = 0; + return r; + } + }; + try { new Picoboot(stuck).program(plan, (w, d, t) -> {}); check(false, "no error"); } + catch (IOException e) { check(e.getMessage().contains("10108000"), e.getMessage()); } + + if (jiant != null) { + System.out.println("3b. a JIANT package (fm1pkg_make.py) is accepted and written as is"); + RescueImage.Firmware f = RescueImage.checkFirmware(jiant); + check(!f.official && f.identity.equals("FM-1_910"), "identity " + f.identity); + check(Arrays.equals(f.region, jiantRegion), "JIANT region differs from builder.js's"); + TreeMap jp = RescueImage.build(base, jiant, "JIANT V10.7.58 (FM-1_910)", loader); + MockRp2040 r2 = new MockRp2040(); + new Picoboot(r2).program(jp, (w, d, t) -> {}); + check(Arrays.equals(Arrays.copyOfRange(r2.flash, 0x108000, 0x108000 + RescueImage.FW_LEN), jiantRegion), + "payload region != JIANT region"); + check(new String(r2.flash, 0x100000 + 52, 25, java.nio.charset.StandardCharsets.US_ASCII) + .equals("JIANT V10.7.58 (FM-1_910)"), "label"); + byte[] noLoader = jiant.clone(); + for (int i = 0; i + 16 <= noLoader.length; i++) + if (new String(noLoader, i, 16, java.nio.charset.StandardCharsets.US_ASCII).equals("FELUCCA-LOADER-1")) noLoader[i] = 'X'; + try { RescueImage.checkFirmware(noLoader); check(false, "package without Felucca loader accepted"); } + catch (RescueImage.Refused e) { } + try { RescueImage.checkFirmware(v16); check(false, "V16 accepted"); } catch (RescueImage.Refused e) { } + } + + System.out.println("4. status lines"); + RescueStatus s = RescueStatus.parse("OK state=run phase=write sector=72/143 written=3 same=69 err=none addr=000000"); + check(s != null && s.state.equals("run") && s.sector == 72 && s.written == 3 && s.permille() > 300 && s.permille() < 340, + "run line"); + s = RescueStatus.parse("OK state=wait foreign=1 phase=idle sector=0/143 written=0 same=0 err=none addr=000000"); + check(s != null && s.foreign && s.permille() == 0, "foreign line"); + s = RescueStatus.parse("OK state=error phase=write sector=9/143 written=8 same=0 err=write addr=00C000"); + check(s != null && s.err.equals("write") && s.addr.equals("00C000"), "error line"); + check(RescueStatus.parse("PONG") == null, "PONG parsed"); + + System.out.println(failures == 0 ? "\nall app core tests passed" : "\n" + failures + " FAILURE(S)"); + System.exit(failures == 0 ? 0 : 1); + } +} diff --git a/android/rescue/test/run.sh b/android/rescue/test/run.sh new file mode 100755 index 00000000..33e3baed --- /dev/null +++ b/android/rescue/test/run.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# android/rescue/test/run.sh V15.fwsc V16.fwsc wl82loader.bin WEB.uf2 BASE_ZERO.uf2 [JIANT.fwsc JIANT_REGION.bin] +# WEB.uf2: node rescue/make_uf2.mjs BASE_ZERO.uf2 V15.fwsc wl82loader.bin WEB.uf2 +set -e +HERE="$(cd "$(dirname "$0")" && pwd)" +OUT="${TMPDIR:-/tmp}/fm1-rescue-app-test" +rm -rf "$OUT" && mkdir -p "$OUT" +javac -d "$OUT" "$HERE/../app/src/main/java/fm/jiant/rescue/RescueImage.java" \ + "$HERE/../app/src/main/java/fm/jiant/rescue/Picoboot.java" \ + "$HERE/../app/src/main/java/fm/jiant/rescue/RescueStatus.java" "$HERE/RescueTest.java" +java -cp "$OUT" RescueTest "$@" diff --git a/android/rescue/test/run_diag.sh b/android/rescue/test/run_diag.sh new file mode 100755 index 00000000..b95f653c --- /dev/null +++ b/android/rescue/test/run_diag.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# The diagnosis on FM-1 Transporter console logs: android/rescue/test/run_diag.sh LOG... +set -e +HERE="$(cd "$(dirname "$0")" && pwd)" +OUT="${TMPDIR:-/tmp}/fm1-rescue-diag-test" +rm -rf "$OUT" && mkdir -p "$OUT" +javac -d "$OUT" "$HERE/../app/src/main/java/fm/jiant/rescue/Diagnosis.java" "$HERE/DiagTest.java" +java -cp "$OUT" DiagTest "$@" diff --git a/rescue/README.md b/rescue/README.md new file mode 100644 index 00000000..8ed24d62 --- /dev/null +++ b/rescue/README.md @@ -0,0 +1,71 @@ +# FM-1 Rescue — unbrick an FM-1 with only an RP2040 + +[English below](#english) + +Repara un M-VAVE FM-1 en **hard brick** (no enciende, no aparece por USB) **sin Python ni terminal**. +El RP2040 lleva dentro el firmware oficial V15 y hace todo él solo; el PC solo sirve para copiar un archivo +(o ni eso: después basta un cargador USB). + +1. Abre **`fm1-rescue.html`** (Chrome, Edge o Firefox; funciona también como archivo local), elige tu placa + (RP2040-Zero, XIAO RP2040 o Raspberry Pi Pico / tipo Pico) y el firmware: un paquete **JIANT** (`.fwsc` del instalador) o el `FM-1.fwsc` + **V15** oficial. Si el FM-1 venía con la **V16**, usa JIANT (arranca con la cabecera de la V16; la V15 no + está comprobada con ella). Pulsa **Crear fm1-rescue.uf2**. +2. Mantén **BOOT** y conecta el RP2040 al PC; arrastra `fm1-rescue.uf2` a la unidad `RPI-RP2`. +3. Desconéctalo. FM-1 **apagado**; cables: verde → `0` (Pico: `GP0`, pin 1), blanco → `1` (Pico: `GP1`, pin 2), + negro → `GND`, rojo sin conectar. +4. Conecta el RP2040 a un PC o cargador (LED amarillo parpadeando) y **enciende el FM-1**. +5. LED azul = trabajando; **verde fijo** = listo: apaga el FM-1, quita los cables, enciéndelo (arranca V15). + Rojo parpadeando = error: apaga el FM-1, reconecta el RP2040 y repite. + +**Sin ordenador:** la app Android **FM-1 Rescue** (`android/rescue`, ver su [LÉEME](../android/rescue/LEEME.md)) hace +todo desde el móvil: graba el RP2040 por OTG y muestra el progreso de la reparación. + +Comparado con la guía con Python: no hay que instalar Python, ni `setup`, ni `wizard`, ni escribir `WRITE`, +ni puertos serie; el orden "primero el RP2040, después encender el FM-1" lo marca el LED. + +## Qué hace (y qué no) + +- Envía el USB_KEY al encender (o la *soft key* si el FM-1 ya corre la V15 de fábrica) → modo UBOOT de la ROM. +- Sube `wl82loader.bin`, comprueba chip key `0x980F` y flash ID `0x856014` / `0xB36014`. +- Escribe **solo los sectores de 4 KiB de `0x4000..0x92FFF` que difieren** de la V15, cada uno borrado, escrito y + releído; al final relee toda la zona y la compara. +- **Nunca** escribe la cabecera de arranque (`0x0000..0x3FFF`) ni los datos (`0x93000..`: ajustes, sonidos, + canciones). No hace la copia de seguridad doble del método con Python: si quieres un volcado previo, usa la + placa sin V15 (es un FM-1 Transporter normal) con su web app o `fm1t.py`. +- Acepta la V15 oficial (hash de la región `6edf3c37…`) o un paquete de JIANT hecho con `tools/fm1pkg_make.py` + (identidad `FM-1_9xx`, `flash.bin` de exactamente `0x93000`, con el loader de Felucca). La V16 no cabe. +- Con la V15, el `.uf2` final no se distribuye (contiene firmware de M-VAVE). Con JIANT sí se podría (GPL). + +**Estado:** probado en PC (lógica del firmware real contra un FM-1 simulado, `firmware/test/`), **aún no +probado en hardware**. Úsalo con la batería cargada y bajo tu responsabilidad. + +## English + +Unbrick an FM-1 with an RP2040 and no Python: open `fm1-rescue.html`, pick the board and the official V15 +`FM-1.fwsc`, make `fm1-rescue.uf2`, copy it to the board in BOOT mode, wire green → GP0 (D+), white → GP1 (D-), +black → GND, power the board (computer or charger), switch the FM-1 on, wait for steady green. Same safety +rules as above: only differing sectors of `0x4000..0x92FFF`, each verified; head and data never written. +Not yet tested on hardware. + +## Files + +| | | +|---|---| +| `fm1-rescue.html` | the page (generated, self-contained: builder + both base firmwares inlined) | +| `builder.js` | `.fwsc` → V15 region, payload, merged UF2 (browser and Node) | +| `make_uf2.mjs` | command-line builder: `node make_uf2.mjs BASE.uf2 FM-1.fwsc wl82loader.bin OUT.uf2` | +| `base/` | prebuilt rescue firmware for RP2040-Zero, XIAO RP2040 and Raspberry Pi Pico (one-colour LED on GP25: blink patterns) | +| `firmware/` | FM-1 Transporter `14fd4df` + `src/payload.c`, `src/autorescue.c`, WS2812 LED for the Zero | +| `firmware/test/` | host test of `payload.c` + `autorescue.c` against a mock FM-1 | +| `build.sh` | rebuilds `base/` and the page; with `FM1_V15` and `FM1_LOADER` also runs the host test | + +Payload layout: `firmware/src/payload.h` (at 1 MiB in the RP2040 flash). Without a payload the firmware is +a plain FM-1 Transporter; its data port also answers `rescue` with the rescue state and progress (on core 0, +also while a restore runs), which the Android app (`android/rescue`) polls. + +## Credits and licence + +MIT (`firmware/LICENSE`). FM-1 Transporter by Leo Kuroshita / Hügelton Instruments (MIT), Pico-PIO-USB by +sekigon-gonnoc (MIT, `firmware/lib/`), `.fwsc` parsing and V15 hashes from Quixotic7's MvaveFM1Unbricker (MIT), +`wl82loader.bin` from kagaimiq's jl-uboot-tool (MIT, downloaded at build time, not stored here), WS2812 PIO +program from pico-examples (BSD-3-Clause). Procedure after GoodPerson42's "FM1 Unbricking for Dummies". diff --git a/rescue/base/fm1-rescue-base-pico.uf2 b/rescue/base/fm1-rescue-base-pico.uf2 new file mode 100644 index 00000000..67bc0d03 Binary files /dev/null and b/rescue/base/fm1-rescue-base-pico.uf2 differ diff --git a/rescue/base/fm1-rescue-base-xiao.uf2 b/rescue/base/fm1-rescue-base-xiao.uf2 new file mode 100644 index 00000000..19ad06e6 Binary files /dev/null and b/rescue/base/fm1-rescue-base-xiao.uf2 differ diff --git a/rescue/base/fm1-rescue-base-zero.uf2 b/rescue/base/fm1-rescue-base-zero.uf2 new file mode 100644 index 00000000..e3084578 Binary files /dev/null and b/rescue/base/fm1-rescue-base-zero.uf2 differ diff --git a/rescue/build.sh b/rescue/build.sh new file mode 100755 index 00000000..643f5012 --- /dev/null +++ b/rescue/build.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Build the FM-1 Rescue: the base firmware for each board, then the page. +# PICO_SDK_PATH=~/pico-sdk rescue/build.sh +# Needs pico-sdk 2.2.0 (with lib/tinyusb), CMake and an Arm GCC with newlib. +# Optional host test of the rescue logic against a mock FM-1 (needs the +# official V15 and the loader, which are not in this repository): +# FM1_V15=FM-1.fwsc FM1_LOADER=wl82loader.bin rescue/build.sh +set -e +HERE="$(cd "$(dirname "$0")" && pwd)" +: "${PICO_SDK_PATH:?set PICO_SDK_PATH to pico-sdk 2.2.0}" +BUILD="${BUILD:-$HERE/firmware/build}" +mkdir -p "$HERE/base" +for spec in zero:waveshare_rp2040_zero xiao:seeed_xiao_rp2040 pico:pico; do + board=${spec%%:*} + pico_board=${spec#*:} + cmake -S "$HERE/firmware" -B "$BUILD/$board" -DPICO_SDK_PATH="$PICO_SDK_PATH" \ + -DPICO_BOARD="$pico_board" -DFM1T_BOARD="$board" >/dev/null + make -C "$BUILD/$board" -j8 fm1_transporter >/dev/null + cp "$BUILD/$board/fm1_transporter.uf2" "$HERE/base/fm1-rescue-base-$board.uf2" + echo "base/fm1-rescue-base-$board.uf2" +done +python3 "$HERE/make_page.py" + +if [ -n "$FM1_V15" ] && [ -n "$FM1_LOADER" ]; then + T="${TMPDIR:-/tmp}" + node "$HERE/make_uf2.mjs" "$HERE/base/fm1-rescue-base-zero.uf2" "$FM1_V15" "$FM1_LOADER" \ + "$T/fm1-rescue-test.uf2" "$T/fm1-v15-region.bin" + "$HERE/firmware/test/run.sh" "$T/fm1-rescue-test.uf2" "$T/fm1-v15-region.bin" +fi diff --git a/rescue/builder.js b/rescue/builder.js new file mode 100644 index 00000000..ba010730 --- /dev/null +++ b/rescue/builder.js @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: MIT +// FM-1 Rescue builder: turns the official FM-1.fwsc (V15) and JieLi's +// wl82loader.bin into ONE .uf2 for an RP2040 board. The .uf2 holds the rescue +// firmware (rescue/firmware, a fork of Leo Kuroshita's FM-1 Transporter) and, +// 1 MiB into the board's flash, the payload it restores by itself +// (rescue/firmware/src/payload.h). Runs in the browser and in Node (tests). +// +// The .fwsc parsing is a port of fm1_unbrick.py (Quixotic7/MvaveFM1Unbricker, +// MIT): parse_fwsc, ufw_flash and the V15 region hash. + +export const FW_START = 0x4000; +export const FW_LEN = 0x8f000; +export const FW_END = FW_START + FW_LEN; +export const V15_REGION_SHA256 = "6edf3c37fb5bbbc33607c89375ee024d5477c17914d72221c8c68e58a8255686"; +export const LOADER_LEN = 24064; +export const LOADER_SHA256 = "d41da6126760c9d66660bcc0cac8d27d221806c5e369a8036921efe68dca5376"; +export const LOADER_URL = + "https://raw.githubusercontent.com/kagaimiq/jl-uboot-tool/adb3f18889e88ac512ce0a3c4d8cc3d3cb30696a/data/loaderblobs/usb/wl82loader.bin"; + +// payload.h +const PL_FLASH = 0x10100000; // XIP address of the payload (1 MiB into the flash) +const PL_MAGIC = "FM1-RESCUE-PL-1"; +const PL_LOADER_OFF = 0x1000; +const PL_IMAGE_OFF = 0x8000; + +const FWSC_BLOCK = 0x2f, FWSC_MARKED_BLOCKS = 20, FWSC_NO_CHAR = 0x7d; + +const UF2_MAGIC0 = 0x0a324655, UF2_MAGIC1 = 0x9e5d5157, UF2_MAGIC_END = 0x0ab16f30; +const UF2_FLAG_FAMILY = 0x00002000; +const RP2040_FAMILY = 0xe48bff56; + +//--------------------------------------------------------------------+ +// checksums +//--------------------------------------------------------------------+ + +const CRC_T = new Uint32Array(256).map((_, i) => { + let c = i; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +export function crc32(d, crc = 0) { + let c = ~crc >>> 0; + for (let i = 0; i < d.length; i++) c = CRC_T[(c ^ d[i]) & 255] ^ (c >>> 8); + return ~c >>> 0; +} + +function crc16(d, c = 0) { + for (let i = 0; i < d.length; i++) { + c ^= d[i] << 8; + for (let k = 0; k < 8; k++) c = c & 0x8000 ? ((c << 1) ^ 0x1021) & 0xffff : (c << 1) & 0xffff; + } + return c; +} + +export async function sha256hex(data) { + const subtle = globalThis.crypto && globalThis.crypto.subtle; + if (!subtle) throw new Error("this browser has no WebCrypto (open the page over https or as a local file)"); + const h = new Uint8Array(await subtle.digest("SHA-256", data)); + return Array.from(h, b => b.toString(16).padStart(2, "0")).join(""); +} + +//--------------------------------------------------------------------+ +// .fwsc -> FM-1 flash region 0x4000..0x92FFF +//--------------------------------------------------------------------+ + +function jlEnc(buf) { + const out = Uint8Array.from(buf); + let k = 0xffff; + for (let i = 0; i < out.length; i++) { + out[i] ^= k & 0xff; + k = ((k << 1) ^ (k & 0x8000 ? 0x1021 : 0)) & 0xffff; + } + return out; +} + +const u16 = (p, o) => p[o] | (p[o + 1] << 8); +const u32 = (p, o) => (u16(p, o) | (u16(p, o + 2) << 16)) >>> 0; + +export function parseFwsc(data) { + const stride = FWSC_BLOCK + 1; + if (data.length < stride * FWSC_MARKED_BLOCKS) throw new Error("not an FM-1 .fwsc package (too short)"); + const head = stride * FWSC_MARKED_BLOCKS; + const image = new Uint8Array(FWSC_BLOCK * FWSC_MARKED_BLOCKS + data.length - head); + let identity = ""; + for (let i = 0; i < FWSC_MARKED_BLOCKS; i++) { + image.set(data.subarray(i * stride, i * stride + FWSC_BLOCK), i * FWSC_BLOCK); + const m = data[i * stride + FWSC_BLOCK]; + if (m !== FWSC_NO_CHAR) identity += String.fromCharCode((m - i - 1) & 0xff); + } + image.set(data.subarray(head), FWSC_BLOCK * FWSC_MARKED_BLOCKS); + + if (image.length < 0x400) throw new Error("not a UFW package"); + const hdr = jlEnc(image.subarray(0, 0x40)); + if (crc16(hdr.subarray(2, 0x40)) !== u16(hdr, 0)) throw new Error("not an FM-1 .fwsc (UFW header CRC)"); + const nent = u16(hdr, 8); + if (nent === 0 || nent > 11) throw new Error("UFW header lists " + nent + " entries"); + if (crc16(image.subarray(0x40, 0x40 + nent * 0x50)) !== u16(hdr, 2)) throw new Error("UFW entry list CRC: damaged package"); + let fl = null; + for (let i = 0; i < nent; i++) { + const e = jlEnc(image.subarray(0x40 + i * 0x50, 0x90 + i * 0x50)); + if (u16(e, 0) === 0) fl = [u32(e, 8), u32(e, 12)]; + } + if (!fl) throw new Error("no flash.bin in the package"); + const [off, len] = fl; + if (off + len > image.length) throw new Error("flash.bin runs past the package"); + if (len < FW_END) throw new Error("flash.bin is too short: not a complete FM-1 package"); + const flash = image.subarray(off, off + len); + return { identity, region: flash.slice(FW_START, FW_END), flashLen: len }; +} + +// The V15 package, checked by the hash of its firmware region. +export async function checkV15(fwscBytes) { + const { identity, region } = parseFwsc(fwscBytes); + const sha = await sha256hex(region); + if (sha !== V15_REGION_SHA256) { + throw new Error( + `this is not the official V15 (identity ${identity || "none"}, region sha256 ${sha.slice(0, 16)}…). ` + + "Only the official M-VAVE V15 FM-1.fwsc (699,956 bytes) is accepted."); + } + return { identity, region, sha }; +} + +const LOADER_MARK = new TextEncoder().encode("FELUCCA-LOADER-1"); +function hasMark(d) { + outer: for (let i = 0; i + LOADER_MARK.length <= d.length; i++) { + for (let k = 0; k < LOADER_MARK.length; k++) if (d[i + k] !== LOADER_MARK[k]) continue outer; + return true; + } + return false; +} + +// The official V15 (by its region hash), or a JIANT / Felucca-family package made by tools/fm1pkg_make.py: +// identity FM-1_9xx, flash.bin exactly 0x93000, Felucca's own loader in it. JIANT runs under the boot head of +// V15 and of V16, so it is the one for an FM-1 that came with V16. Same rules as RescueImage.checkFirmware. +export async function checkPackage(fwscBytes) { + const { identity, region, flashLen } = parseFwsc(fwscBytes); + const sha = await sha256hex(region); + if (sha === V15_REGION_SHA256) return { identity, region, sha, official: true, label: `${identity || "FM-1_015"} official V15` }; + if (identity === "FM-1_015") throw new Error("it says V15 but its firmware hash is not V15's: damaged or modified"); + if (!/^FM-1_9\d\d$/.test(identity)) + throw new Error(`not the official V15 nor a JIANT package (identity ${identity || "none"}); the official V16 does not fit the rescue`); + if (flashLen !== FW_END) throw new Error("this package runs past 0x92FFF; the rescue cannot write it"); + if (!hasMark(fwscBytes)) throw new Error("not a package made by JIANT's tools"); + if (region.every(b => b === 0xff || b === 0)) throw new Error("the firmware region of this package is blank"); + return { identity, region, sha, official: false, label: `${identity} JIANT` }; +} + +export async function checkLoader(bytes) { + if (bytes.length !== LOADER_LEN) throw new Error(`wl82loader.bin must be ${LOADER_LEN} bytes, not ${bytes.length}`); + const sha = await sha256hex(bytes); + if (sha !== LOADER_SHA256) throw new Error("wl82loader.bin has the wrong sha256 " + sha.slice(0, 16) + "…"); + return bytes; +} + +//--------------------------------------------------------------------+ +// payload + UF2 +//--------------------------------------------------------------------+ + +function hexToBytes(h) { + return Uint8Array.from(h.match(/../g), x => parseInt(x, 16)); +} + +export function buildPayload(region, loader, sha, label) { + const p = new Uint8Array(PL_IMAGE_OFF + FW_LEN).fill(0xff); + const h = new Uint8Array(256); + const dv = new DataView(h.buffer); + for (let i = 0; i < PL_MAGIC.length; i++) h[i] = PL_MAGIC.charCodeAt(i); + const w = (o, v) => dv.setUint32(o, v >>> 0, true); + w(16, 1); // version + w(20, 256); // hdr_size + w(24, PL_LOADER_OFF); + w(28, LOADER_LEN); + w(32, crc32(loader)); + w(36, PL_IMAGE_OFF); + w(40, FW_START); + w(44, FW_LEN); + w(48, crc32(region)); + const lab = label.slice(0, 63); + for (let i = 0; i < lab.length; i++) h[52 + i] = lab.charCodeAt(i) & 0x7f; + h.set(hexToBytes(sha), 116); + w(252, crc32(h.subarray(0, 252))); + p.set(h, 0); + p.set(loader, PL_LOADER_OFF); + p.set(region, PL_IMAGE_OFF); + return p; +} + +export function parseUf2(uf2) { + if (uf2.length % 512) throw new Error("base .uf2 is not a whole number of blocks"); + const blocks = []; + for (let o = 0; o < uf2.length; o += 512) { + const b = uf2.subarray(o, o + 512); + const dv = new DataView(b.buffer, b.byteOffset, 512); + if (dv.getUint32(0, true) !== UF2_MAGIC0 || dv.getUint32(4, true) !== UF2_MAGIC1 || + dv.getUint32(508, true) !== UF2_MAGIC_END) throw new Error("base .uf2: bad block magic"); + blocks.push({ + flags: dv.getUint32(8, true), addr: dv.getUint32(12, true), size: dv.getUint32(16, true), + family: dv.getUint32(28, true), data: b.slice(32, 32 + dv.getUint32(16, true)), + }); + } + return blocks; +} + +function emitUf2(blocks) { + const out = new Uint8Array(blocks.length * 512); + blocks.forEach((bl, i) => { + const b = out.subarray(i * 512, i * 512 + 512); + const dv = new DataView(out.buffer, i * 512, 512); + dv.setUint32(0, UF2_MAGIC0, true); + dv.setUint32(4, UF2_MAGIC1, true); + dv.setUint32(8, bl.flags, true); + dv.setUint32(12, bl.addr, true); + dv.setUint32(16, bl.data.length, true); + dv.setUint32(20, i, true); + dv.setUint32(24, blocks.length, true); + dv.setUint32(28, bl.family, true); + b.set(bl.data, 32); + dv.setUint32(508, UF2_MAGIC_END, true); + }); + return out; +} + +// base firmware .uf2 + payload -> one .uf2 the RP2040 boot ROM takes in one copy. +export function mergeUf2(baseUf2, payload) { + const base = parseUf2(baseUf2); + let end = 0; + for (const b of base) { + if (b.family !== RP2040_FAMILY || !(b.flags & UF2_FLAG_FAMILY)) throw new Error("base .uf2 is not an RP2040 image"); + if (b.addr < 0x10000000) throw new Error("base .uf2 writes outside the flash"); + end = Math.max(end, b.addr + b.size); + } + if (end > PL_FLASH) throw new Error("base firmware overlaps the payload area"); + const blocks = base.map(b => ({ ...b })); + // Header page, loader, image: pages of 256 bytes. The 0xFF gap between the + // loader and the image is not sent (its sectors are erased by the boot ROM + // or never read). + const ranges = [[0, 256], [PL_LOADER_OFF, PL_LOADER_OFF + LOADER_LEN], + [PL_IMAGE_OFF, PL_IMAGE_OFF + FW_LEN]]; + for (const [lo, hi] of ranges) { + for (let o = lo; o < hi; o += 256) { + const data = new Uint8Array(256).fill(0xff); + data.set(payload.subarray(o, Math.min(o + 256, hi))); + blocks.push({ flags: UF2_FLAG_FAMILY, addr: PL_FLASH + o, size: 256, family: RP2040_FAMILY, data }); + } + } + return emitUf2(blocks); +} + +export async function buildRescueUf2({ baseUf2, fwsc, loader, label }) { + const v = await checkPackage(fwsc); + await checkLoader(loader); + const payload = buildPayload(v.region, loader, v.sha, label || v.label); + return { uf2: mergeUf2(baseUf2, payload), identity: v.identity, official: v.official }; +} diff --git a/rescue/firmware/CMakeLists.txt b/rescue/firmware/CMakeLists.txt new file mode 100644 index 00000000..0a29ccd7 --- /dev/null +++ b/rescue/firmware/CMakeLists.txt @@ -0,0 +1,123 @@ +cmake_minimum_required(VERSION 3.13) + +# Pico-PIO-USB is vendored as a submodule, pinned to the release TinyUSB in +# the SDK expects. The build uses a patched copy in the build directory +# (lib/pico-pio-usb-bulk-multi-xact.patch: several bulk packets per frame +# instead of one), so the submodule itself stays pristine. The path must be +# set before the SDK pulls in TinyUSB. +set(FM1T_PIO_USB_SRC ${CMAKE_CURRENT_LIST_DIR}/lib/Pico-PIO-USB) +set(FM1T_PIO_USB_PATCH ${CMAKE_CURRENT_LIST_DIR}/lib/pico-pio-usb-bulk-multi-xact.patch) +set(PICO_PIO_USB_PATH ${CMAKE_BINARY_DIR}/Pico-PIO-USB-patched) +file(REMOVE_RECURSE ${PICO_PIO_USB_PATH}) +file(COPY ${FM1T_PIO_USB_SRC}/src DESTINATION ${PICO_PIO_USB_PATH}) +execute_process( + COMMAND patch -p1 --forward --quiet -i ${FM1T_PIO_USB_PATCH} + WORKING_DIRECTORY ${PICO_PIO_USB_PATH} + RESULT_VARIABLE FM1T_PATCH_RESULT) +if (NOT FM1T_PATCH_RESULT EQUAL 0) + message(FATAL_ERROR "Applying ${FM1T_PIO_USB_PATCH} failed") +endif() +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${FM1T_PIO_USB_PATCH}) + +# Which board drives the FM-1: xiao (Seeed XIAO RP2040, GP0 = D+, GP1 = D-) or +# debugprobe (Raspberry Pi Debug Probe, UART connector: GP4 = D+, GP6 = D-). +# On the Debug Probe D- is two pins above D+, which Pico-PIO-USB does not +# support, so lib/pico-pio-usb-debugprobe.patch teaches it that, and the +# headers it ships are removed so the ones generated from the patched .pio +# files are used. +# zero: Waveshare RP2040-Zero (GP0 = D+, GP1 = D-, WS2812 status LED on GP16). +# pico: Raspberry Pi Pico and Pico-style RP2040 boards (GP0 = D+, GP1 = D-, plain LED on GP25). +set(FM1T_BOARD xiao CACHE STRING "Board: xiao, zero or debugprobe") +set_property(CACHE FM1T_BOARD PROPERTY STRINGS xiao zero pico debugprobe) +set(FM1T_LED_WS2812 0) +set(FM1T_LED_MONO 0) +if (FM1T_BOARD STREQUAL "debugprobe") + set(FM1T_PROBE_PATCH ${CMAKE_CURRENT_LIST_DIR}/lib/pico-pio-usb-debugprobe.patch) + execute_process( + COMMAND patch -p1 --forward --quiet -i ${FM1T_PROBE_PATCH} + WORKING_DIRECTORY ${PICO_PIO_USB_PATH} + RESULT_VARIABLE FM1T_PATCH_RESULT) + if (NOT FM1T_PATCH_RESULT EQUAL 0) + message(FATAL_ERROR "Applying ${FM1T_PROBE_PATCH} failed") + endif() + file(REMOVE ${PICO_PIO_USB_PATH}/src/usb_tx.pio.h ${PICO_PIO_USB_PATH}/src/usb_rx.pio.h) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${FM1T_PROBE_PATCH}) + set(FM1T_BOARD_DEBUGPROBE 1) +elseif (FM1T_BOARD STREQUAL "xiao") + set(FM1T_BOARD_DEBUGPROBE 0) +elseif (FM1T_BOARD STREQUAL "zero") + set(FM1T_BOARD_DEBUGPROBE 0) + set(FM1T_LED_WS2812 1) +elseif (FM1T_BOARD STREQUAL "pico") + set(FM1T_BOARD_DEBUGPROBE 0) + set(FM1T_LED_MONO 1) +else() + message(FATAL_ERROR "FM1T_BOARD must be xiao, zero, pico or debugprobe, not ${FM1T_BOARD}") +endif() + +# TinyUSB debug level (CFG_TUSB_DEBUG). 2 logs host enumeration during M0. +set(LOG 2) + +include(pico_sdk_import.cmake) + +project(fm1_transporter C CXX ASM) +set(CMAKE_C_STANDARD 11) +set(CMAKE_CXX_STANDARD 17) + +pico_sdk_init() + +function(fm1t_add_firmware TARGET) + add_executable(${TARGET} + src/main.c + src/recovery.c + src/pio_host.c + src/usb_device.c + src/log.c + src/jieli_uboot.c + src/transporter_proto.c + src/payload.c + src/autorescue.c + ) + + pico_generate_pio_header(${TARGET} + ${CMAKE_CURRENT_LIST_DIR}/pio/usb_key.pio + ) + pico_generate_pio_header(${TARGET} + ${CMAKE_CURRENT_LIST_DIR}/pio/ws2812.pio + ) + + # tusb_config.h + target_include_directories(${TARGET} PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src) + target_compile_definitions(${TARGET} PRIVATE FM1T_BOARD_DEBUGPROBE=${FM1T_BOARD_DEBUGPROBE} + FM1T_LED_WS2812=${FM1T_LED_WS2812} + FM1T_LED_MONO=${FM1T_LED_MONO}) + + target_link_libraries(${TARGET} + pico_stdlib + pico_multicore + pico_unique_id + pico_usb_reset_interface_headers + hardware_pio + hardware_gpio + hardware_clocks + hardware_dma + hardware_flash + tinyusb_device + tinyusb_host + tinyusb_pico_pio_usb + ) + + # The console is our own TinyUSB CDC device (see src/usb_device.c, + # src/log.c); pico_stdio_usb cannot coexist with the TinyUSB host stack. + pico_enable_stdio_usb(${TARGET} 0) + pico_enable_stdio_uart(${TARGET} 0) + + pico_add_extra_outputs(${TARGET}) +endfunction() + +# M0 firmware: USB_KEY recovery -> PIO USB host. +fm1t_add_firmware(fm1_transporter) + +# Host bring-up firmware: PIO USB host only, no USB_KEY. +fm1t_add_firmware(fm1_transporter_hostonly) +target_compile_definitions(fm1_transporter_hostonly PRIVATE FM1T_HOST_ONLY=1) diff --git a/rescue/firmware/LICENSE b/rescue/firmware/LICENSE new file mode 100644 index 00000000..4a26b2a4 --- /dev/null +++ b/rescue/firmware/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 kurogedelic + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/rescue/firmware/lib/Pico-PIO-USB/LICENSE b/rescue/firmware/lib/Pico-PIO-USB/LICENSE new file mode 100644 index 00000000..780f9c4f --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 sekigon-gonnoc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb.c b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb.c new file mode 100644 index 00000000..e84b6fa8 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb.c @@ -0,0 +1,586 @@ +/** + * Copyright (c) 2021 sekigon-gonnoc + */ + +#pragma GCC push_options +#pragma GCC optimize("-O3") + +#include +#include +#include // memcpy + +#include "hardware/clocks.h" +#include "hardware/dma.h" +#include "hardware/pio.h" +#include "hardware/pio_instructions.h" +#include "hardware/sync.h" +#include "pico/bootrom.h" +#include "pico/stdlib.h" +#include "pico/platform.h" + +#include "pio_usb.h" +#include "usb_definitions.h" +#include "pio_usb_configuration.h" +#include "pio_usb_ll.h" +#include "usb_crc.h" +#include "usb_tx.pio.h" +#include "usb_rx.pio.h" + +#define UNUSED_PARAMETER(x) (void)x + +usb_device_t pio_usb_device[PIO_USB_DEVICE_CNT]; +pio_port_t pio_port[1]; +root_port_t pio_usb_root_port[PIO_USB_ROOT_PORT_CNT]; +endpoint_t pio_usb_ep_pool[PIO_USB_EP_POOL_CNT]; + +static uint8_t ack_encoded[5]; +static uint8_t nak_encoded[5]; +static uint8_t stall_encoded[5]; +static uint8_t pre_encoded[5]; + +//--------------------------------------------------------------------+ +// Bus functions +//--------------------------------------------------------------------+ + +static void __no_inline_not_in_flash_func(send_pre)(const pio_port_t *pp) { + // send PRE token in full-speed + uint16_t instr = pp->fs_tx_pre_program->instructions[0]; + pp->pio_usb_tx->instr_mem[pp->offset_tx] = instr; + + SM_SET_CLKDIV(pp->pio_usb_tx, pp->sm_tx, pp->clk_div_fs_tx); + + pio_sm_exec(pp->pio_usb_tx, pp->sm_tx, pp->tx_start_instr); + dma_channel_transfer_from_buffer_now(pp->tx_ch, pre_encoded, + sizeof(pre_encoded)); + pp->pio_usb_tx->irq = IRQ_TX_ALL_MASK; // clear complete flag + + while ((pp->pio_usb_tx->irq & IRQ_TX_EOP_MASK) == 0) { + continue; + } + pio_sm_clear_fifos(pp->pio_usb_tx, pp->sm_tx); + + // change bus speed to low-speed + pio_sm_set_enabled(pp->pio_usb_tx, pp->sm_tx, false); + instr = pp->fs_tx_program->instructions[0]; + pp->pio_usb_tx->instr_mem[pp->offset_tx] = instr; + SM_SET_CLKDIV(pp->pio_usb_tx, pp->sm_tx, pp->clk_div_ls_tx); + pio_sm_set_enabled(pp->pio_usb_tx, pp->sm_tx, true); + + // pio_sm_clear_fifos(pp->pio_usb_tx, pp->sm_tx); + // pio_sm_exec(pp->pio_usb_tx, pp->sm_tx, pp->tx_start_instr); + // SM_SET_CLKDIV_MAXSPEED(pp->pio_usb_rx, pp->sm_rx); + + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_eop, false); + SM_SET_CLKDIV(pp->pio_usb_rx, pp->sm_eop, pp->clk_div_ls_rx); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_eop, true); +} + +void __not_in_flash_func(pio_usb_bus_usb_transfer)(const pio_port_t *pp, + uint8_t *data, uint16_t len) { + if (pp->need_pre) { + send_pre(pp); + } + + pio_sm_exec(pp->pio_usb_tx, pp->sm_tx, pp->tx_start_instr); + dma_channel_transfer_from_buffer_now(pp->tx_ch, data, len); + pp->pio_usb_tx->irq = IRQ_TX_ALL_MASK; // clear complete flag + + io_ro_32 *pc = &pp->pio_usb_tx->sm[pp->sm_tx].addr; + while ((pp->pio_usb_tx->irq & IRQ_TX_ALL_MASK) == 0) { + continue; + } + pio_sm_clear_fifos(pp->pio_usb_tx, pp->sm_tx); + while (*pc < PIO_USB_TX_ENCODED_DATA_COMP) { + continue; + } +} + +void __no_inline_not_in_flash_func(pio_usb_bus_send_handshake)( + const pio_port_t *pp, uint8_t pid) { + switch (pid) { + case USB_PID_ACK: + pio_usb_bus_usb_transfer(pp, ack_encoded, 5); + break; + + case USB_PID_NAK: + pio_usb_bus_usb_transfer(pp, nak_encoded, 5); + break; + + case USB_PID_STALL: + default: + pio_usb_bus_usb_transfer(pp, stall_encoded, 5); + break; + } +} + +void __no_inline_not_in_flash_func(pio_usb_bus_send_token)(const pio_port_t *pp, + uint8_t token, + uint8_t addr, + uint8_t ep_num) { + + uint8_t packet[4] = {USB_SYNC, token, 0, 0}; + uint16_t dat = ((uint16_t)(ep_num & 0xf) << 7) | (addr & 0x7f); + uint8_t crc = calc_usb_crc5(dat); + packet[2] = dat & 0xff; + packet[3] = (crc << 3) | ((dat >> 8) & 0x1f); + + uint8_t packet_encoded[sizeof(packet) * 2 * 7 / 6 + 2]; + uint8_t encoded_len = pio_usb_ll_encode_tx_data(packet, sizeof(packet), packet_encoded); + + pio_usb_bus_usb_transfer(pp, packet_encoded, encoded_len); +} + +void __no_inline_not_in_flash_func(pio_usb_bus_prepare_receive)(const pio_port_t *pp) { + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); + pio_sm_restart(pp->pio_usb_rx, pp->sm_rx); + pio_sm_exec(pp->pio_usb_rx, pp->sm_rx, pp->rx_reset_instr); + pio_sm_exec(pp->pio_usb_rx, pp->sm_rx, pp->rx_reset_instr2); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, true); +} + +void __no_inline_not_in_flash_func(pio_usb_bus_start_receive)(const pio_port_t *pp) { + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; +} + +uint8_t __no_inline_not_in_flash_func(pio_usb_bus_wait_handshake)(pio_port_t* pp) { + int16_t t = 240; + int16_t idx = 0; + + while (t--) { + if (pio_sm_get_rx_fifo_level(pp->pio_usb_rx, pp->sm_rx)) { + uint8_t data = pio_sm_get(pp->pio_usb_rx, pp->sm_rx) >> 24; + pp->usb_rx_buffer[idx++] = data; + if (idx == 2) { + break; + } + } + } + + if (t > 0) { + while ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + continue; + } + } + + // pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, true); + + return pp->usb_rx_buffer[1]; +} + +int __no_inline_not_in_flash_func(pio_usb_bus_receive_packet_and_handshake)( + pio_port_t *pp, uint8_t handshake) { + uint16_t crc = 0xffff; + uint16_t crc_prev = 0xffff; + uint16_t crc_prev2 = 0xffff; + uint16_t crc_receive = 0xffff; + uint16_t crc_receive_inverse; + bool crc_match = false; + int16_t t = 240; + uint16_t idx = 0; + + while (t--) { + if (pio_sm_get_rx_fifo_level(pp->pio_usb_rx, pp->sm_rx)) { + uint8_t data = pio_sm_get(pp->pio_usb_rx, pp->sm_rx) >> 24; + pp->usb_rx_buffer[idx++] = data; + if (idx == 2) { + break; + } + } + } + + // timing critical start + if (t > 0) { + if (handshake == USB_PID_ACK) { + while ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + if (pio_sm_get_rx_fifo_level(pp->pio_usb_rx, pp->sm_rx)) { + uint8_t data = pio_sm_get(pp->pio_usb_rx, pp->sm_rx) >> 24; + crc_prev2 = crc_prev; + crc_prev = crc; + crc = update_usb_crc16(crc, data); + pp->usb_rx_buffer[idx++] = data; + crc_receive = (crc_receive >> 8) | (data << 8); + crc_receive_inverse = crc_receive ^ 0xffff; + crc_match = (crc_receive_inverse == crc_prev2); + } + } + + if (idx >= 4 && crc_match) { + pio_usb_bus_send_handshake(pp, USB_PID_ACK); + // timing critical end + return idx - 4; + } + } else { + // just discard received data since we NAK/STALL anyway + while ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + continue; + } + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); + + pio_usb_bus_send_handshake(pp, handshake); + } + } + + return -1; +} + +static __always_inline void add_pio_host_rx_program(PIO pio, + const pio_program_t *program, + const pio_program_t *debug_program, + uint *offset, int debug_pin) { + if (debug_pin < 0) { + *offset = pio_add_program(pio, program); + } else { + *offset = pio_add_program(pio, debug_program); + } +} + +static void __no_inline_not_in_flash_func(initialize_host_programs)( + pio_port_t *pp, const pio_usb_configuration_t *c, root_port_t *port) { + // TX program should be placed at address 0 + pio_add_program_at_offset(pp->pio_usb_tx, pp->fs_tx_program, 0); + pp->offset_tx = 0; + usb_tx_fs_program_init(pp->pio_usb_tx, pp->sm_tx, pp->offset_tx, port->pin_dp, + port->pin_dm); + pp->tx_start_instr = pio_encode_jmp(pp->offset_tx + 4); + pp->tx_reset_instr = pio_encode_jmp(pp->offset_tx + 2); + + add_pio_host_rx_program(pp->pio_usb_rx, &usb_nrzi_decoder_program, + &usb_nrzi_decoder_debug_program, &pp->offset_rx, + c->debug_pin_rx); + usb_rx_fs_program_init(pp->pio_usb_rx, pp->sm_rx, pp->offset_rx, port->pin_dp, + port->pin_dm, c->debug_pin_rx); + pp->rx_reset_instr = pio_encode_jmp(pp->offset_rx); + pp->rx_reset_instr2 = pio_encode_set(pio_x, 0); + + add_pio_host_rx_program(pp->pio_usb_rx, &usb_edge_detector_program, + &usb_edge_detector_debug_program, &pp->offset_eop, + c->debug_pin_eop); + eop_detect_fs_program_init(pp->pio_usb_rx, c->sm_eop, pp->offset_eop, + port->pin_dp, port->pin_dm, true, + c->debug_pin_eop); + + usb_tx_configure_pins(pp->pio_usb_tx, pp->sm_tx, port->pin_dp, port->pin_dm); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_rx, port->pin_dp); + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_eop, port->pin_dm); + pio_sm_set_in_pins(pp->pio_usb_rx, pp->sm_eop, port->pin_dp); +} + +static void configure_tx_channel(uint8_t ch, PIO pio, uint sm) { + dma_channel_config conf = dma_channel_get_default_config(ch); + + channel_config_set_read_increment(&conf, true); + channel_config_set_write_increment(&conf, false); + channel_config_set_transfer_data_size(&conf, DMA_SIZE_8); + channel_config_set_dreq(&conf, pio_get_dreq(pio, sm, true)); + + dma_channel_set_config(ch, &conf, false); + dma_channel_set_write_addr(ch, &pio->txf[sm], false); +} + +static void apply_config(pio_port_t *pp, const pio_usb_configuration_t *c, + root_port_t *port) { + pp->pio_usb_tx = c->pio_tx_num == 0 ? pio0 : pio1; + pp->sm_tx = c->sm_tx; + pp->tx_ch = c->tx_ch; + pp->pio_usb_rx = c->pio_rx_num == 0 ? pio0 : pio1; + pp->sm_rx = c->sm_rx; + pp->sm_eop = c->sm_eop; + port->pin_dp = c->pin_dp; + + if (c->pinout == PIO_USB_PINOUT_DPDM) { + port->pin_dm = c->pin_dp + 1; + pp->fs_tx_program = &usb_tx_dpdm_program; + pp->fs_tx_pre_program = &usb_tx_pre_dpdm_program; + pp->ls_tx_program = &usb_tx_dmdp_program; + } else { + port->pin_dm = c->pin_dp - 1; + pp->fs_tx_program = &usb_tx_dmdp_program; + pp->fs_tx_pre_program = &usb_tx_pre_dmdp_program; + pp->ls_tx_program = &usb_tx_dpdm_program; + } + port->pinout = c->pinout; + + pp->debug_pin_rx = c->debug_pin_rx; + pp->debug_pin_eop = c->debug_pin_eop; + + pio_sm_claim(pp->pio_usb_tx, pp->sm_tx); + pio_sm_claim(pp->pio_usb_rx, pp->sm_rx); + pio_sm_claim(pp->pio_usb_rx, pp->sm_eop); +} + +static void port_pin_drive_setting(const root_port_t *port) { + gpio_set_slew_rate(port->pin_dp, GPIO_SLEW_RATE_FAST); + gpio_set_slew_rate(port->pin_dm, GPIO_SLEW_RATE_FAST); + gpio_set_drive_strength(port->pin_dp, GPIO_DRIVE_STRENGTH_12MA); + gpio_set_drive_strength(port->pin_dm, GPIO_DRIVE_STRENGTH_12MA); +} + +void pio_usb_bus_init(pio_port_t *pp, const pio_usb_configuration_t *c, + root_port_t *root) { + memset(root, 0, sizeof(root_port_t)); + + pp->pio_usb_tx = c->pio_tx_num == 0 ? pio0 : pio1; + dma_claim_mask(1<tx_ch); + configure_tx_channel(c->tx_ch, pp->pio_usb_tx, c->sm_tx); + + apply_config(pp, c, root); + initialize_host_programs(pp, c, root); + port_pin_drive_setting(root); + root->initialized = true; + root->dev_addr = 0; + + // pre-encode handshake packets + uint8_t raw_packet[] = {USB_SYNC, USB_PID_ACK}; + pio_usb_ll_encode_tx_data(raw_packet, 2, ack_encoded); + raw_packet[1] = USB_PID_NAK; + pio_usb_ll_encode_tx_data(raw_packet, 2, nak_encoded); + raw_packet[1] = USB_PID_STALL; + pio_usb_ll_encode_tx_data(raw_packet, 2, stall_encoded); + raw_packet[1] = USB_PID_PRE; + pio_usb_ll_encode_tx_data(raw_packet, 2, pre_encoded); +} + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +endpoint_t *pio_usb_get_endpoint(usb_device_t *device, uint8_t idx) { + uint8_t ep_id = device->endpoint_id[idx]; + if (ep_id == 0) { + return NULL; + } else if (ep_id >= 1) { + return &pio_usb_ep_pool[ep_id - 1]; + } + return NULL; +} + +int __no_inline_not_in_flash_func(pio_usb_get_in_data)(endpoint_t *ep, + uint8_t *buffer, + uint8_t len) { + if (ep->has_transfer || ep->is_tx) { + return -1; + } + + if (ep->new_data_flag) { + len = len < ep->actual_len ? len : ep->actual_len; + memcpy(buffer, (void *)ep->buffer, len); + + ep->new_data_flag = false; + + return pio_usb_ll_transfer_start(ep, ep->buffer, ep->size) ? len : -1; + } + + return -1; +} + +int __no_inline_not_in_flash_func(pio_usb_set_out_data)(endpoint_t *ep, + const uint8_t *buffer, + uint8_t len) { + if (ep->has_transfer || !ep->is_tx) { + return -1; + } + + return pio_usb_ll_transfer_start(ep, (uint8_t *)buffer, len) ? 0 : -1; +} + +//--------------------------------------------------------------------+ +// Low Level Function +//--------------------------------------------------------------------+ + +void __no_inline_not_in_flash_func(pio_usb_ll_configure_endpoint)( + endpoint_t *ep, uint8_t const *desc_endpoint) { + const endpoint_descriptor_t *d = (const endpoint_descriptor_t *)desc_endpoint; + ep->size = d->max_size[0] | (d->max_size[1] << 8); + ep->ep_num = d->epaddr; + ep->attr = d->attr; + ep->interval = d->interval; + ep->interval_counter = 0; + ep->data_id = 0; +} + +// Encode transfer data to 2bit sequence represents TX PIO instruction address +uint8_t __no_inline_not_in_flash_func(pio_usb_ll_encode_tx_data)( + uint8_t const *buffer, uint8_t buffer_len, uint8_t *encoded_data) { + uint16_t bit_idx = 0; + int current_state = 1; + int bit_stuffing = 6; + for (int idx = 0; idx < buffer_len; idx++) { + uint8_t byte = buffer[idx]; + for (int b = 0; b < 8; b++) { + uint8_t byte_idx = bit_idx >> 2; + encoded_data[byte_idx] <<= 2; + if (byte & (1 << b)) { + if (current_state) { + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_K; + } else { + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_J; + } + bit_stuffing--; + } else { + if (current_state) { + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_J; + current_state = 0; + } else { + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_K; + current_state = 1; + } + bit_stuffing = 6; + } + + bit_idx++; + + if (bit_stuffing == 0) { + byte_idx = bit_idx >> 2; + encoded_data[byte_idx] <<= 2; + + if (current_state) { + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_J; + current_state = 0; + } else { + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_K; + current_state = 1; + } + bit_stuffing = 6; + bit_idx++; + } + } + } + + uint8_t byte_idx = bit_idx >> 2; + encoded_data[byte_idx] <<= 2; + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_SE0; + bit_idx++; + + byte_idx = bit_idx >> 2; + encoded_data[byte_idx] <<= 2; + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_COMP; + bit_idx++; + + // terminate buffers with K + do { + byte_idx = bit_idx >> 2; + encoded_data[byte_idx] <<= 2; + encoded_data[byte_idx] |= PIO_USB_TX_ENCODED_DATA_K; + bit_idx++; + } while (bit_idx & 0x03); + + byte_idx = bit_idx >> 2; + return byte_idx; +} + +static inline __force_inline void prepare_tx_data(endpoint_t *ep) { + uint16_t const xact_len = pio_usb_ll_get_transaction_len(ep); + uint8_t buffer[PIO_USB_EP_SIZE + 4]; + buffer[0] = USB_SYNC; + buffer[1] = (ep->data_id == 1) ? USB_PID_DATA1 + : USB_PID_DATA0; // USB_PID_SETUP also DATA0 + memcpy(buffer + 2, ep->app_buf, xact_len); + + uint16_t const crc16 = calc_usb_crc16(ep->app_buf, xact_len); + buffer[2 + xact_len] = crc16 & 0xff; + buffer[2 + xact_len + 1] = crc16 >> 8; + + ep->encoded_data_len = + pio_usb_ll_encode_tx_data(buffer, xact_len + 4, ep->buffer); +} + +bool __no_inline_not_in_flash_func(pio_usb_ll_transfer_start)(endpoint_t *ep, + uint8_t *buffer, + uint16_t buflen) { + if (ep->has_transfer) { + return false; + } + + ep->app_buf = buffer; + ep->total_len = buflen; + ep->actual_len = 0; + + if (ep->is_tx) { + prepare_tx_data(ep); + } else { + ep->new_data_flag = false; + } + + ep->transfer_started = false; + ep->transfer_aborted = false; + ep->has_transfer = true; + + return true; +} + +bool __no_inline_not_in_flash_func(pio_usb_ll_transfer_continue)( + endpoint_t *ep, uint16_t xferred_bytes) { + ep->app_buf += xferred_bytes; + ep->actual_len += xferred_bytes; + ep->data_id ^= 1; + + if ((xferred_bytes < ep->size) || (ep->actual_len >= ep->total_len)) { + // complete if all bytes transferred or short packet + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_COMPLETE_BITS); + return false; + } else { + if (ep->is_tx) { + prepare_tx_data(ep); + } + + return true; + } +} + +void __no_inline_not_in_flash_func(pio_usb_ll_transfer_complete)( + endpoint_t *ep, uint32_t flag) { + root_port_t *rport = PIO_USB_ROOT_PORT(ep->root_idx); + uint32_t const ep_mask = (1u << (ep - pio_usb_ep_pool)); + + rport->ints |= flag; + + if (flag == PIO_USB_INTS_ENDPOINT_COMPLETE_BITS) { + rport->ep_complete |= ep_mask; + if (!ep->is_tx) { + ep->new_data_flag = true; + } + } else if (flag == PIO_USB_INTS_ENDPOINT_ERROR_BITS) { + rport->ep_error |= ep_mask; + } else if (flag == PIO_USB_INTS_ENDPOINT_STALLED_BITS) { + rport->ep_stalled |= ep_mask; + } else { + // something wrong + } + + ep->has_transfer = false; +} + +int pio_usb_host_add_port(uint8_t pin_dp, PIO_USB_PINOUT pinout) { + for (int idx = 0; idx < PIO_USB_ROOT_PORT_CNT; idx++) { + root_port_t *root = PIO_USB_ROOT_PORT(idx); + if (!root->initialized) { + root->pin_dp = pin_dp; + + if (pinout == PIO_USB_PINOUT_DPDM) { + root->pin_dm = pin_dp + 1; + } else { + root->pin_dm = pin_dp - 1; + } + root->pinout = pinout; + + gpio_pull_down(pin_dp); + gpio_pull_down(root->pin_dm); + pio_gpio_init(pio_port[0].pio_usb_tx, pin_dp); + pio_gpio_init(pio_port[0].pio_usb_tx, root->pin_dm); + gpio_set_inover(pin_dp, GPIO_OVERRIDE_INVERT); + gpio_set_inover(root->pin_dm, GPIO_OVERRIDE_INVERT); + pio_sm_set_pindirs_with_mask(pio_port[0].pio_usb_tx, pio_port[0].sm_tx, 0, + (1 << pin_dp) | (1 << root->pin_dm)); + port_pin_drive_setting(root); + root->initialized = true; + + return 0; + } + } + + return -1; +} + +#pragma GCC pop_options diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb.h b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb.h new file mode 100644 index 00000000..30a87d35 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb.h @@ -0,0 +1,34 @@ + +#pragma once + +#include "pio_usb_configuration.h" +#include "usb_definitions.h" + +#ifdef __cplusplus + extern "C" { +#endif + +// Host functions +usb_device_t *pio_usb_host_init(const pio_usb_configuration_t *c); +int pio_usb_host_add_port(uint8_t pin_dp, PIO_USB_PINOUT pinout); +void pio_usb_host_task(void); +void pio_usb_host_stop(void); +void pio_usb_host_restart(void); +uint32_t pio_usb_host_get_frame_number(void); + +// Call this every 1ms when skip_alarm_pool is true. +void pio_usb_host_frame(void); + +// Device functions +usb_device_t *pio_usb_device_init(const pio_usb_configuration_t *c, + const usb_descriptor_buffers_t *buffers); +void pio_usb_device_task(void); + +// Common functions +endpoint_t *pio_usb_get_endpoint(usb_device_t *device, uint8_t idx); +int pio_usb_get_in_data(endpoint_t *ep, uint8_t *buffer, uint8_t len); +int pio_usb_set_out_data(endpoint_t *ep, const uint8_t *buffer, uint8_t len); + +#ifdef __cplusplus + } +#endif diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_configuration.h b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_configuration.h new file mode 100644 index 00000000..3635db45 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_configuration.h @@ -0,0 +1,52 @@ + +#pragma once + +typedef enum { + PIO_USB_PINOUT_DPDM = 0, // DM = DP+1 + PIO_USB_PINOUT_DMDP, // DM = DP-1 +} PIO_USB_PINOUT; + +typedef struct { + uint8_t pin_dp; + uint8_t pio_tx_num; + uint8_t sm_tx; + uint8_t tx_ch; + uint8_t pio_rx_num; + uint8_t sm_rx; + uint8_t sm_eop; + void* alarm_pool; + int8_t debug_pin_rx; + int8_t debug_pin_eop; + bool skip_alarm_pool; + PIO_USB_PINOUT pinout; +} pio_usb_configuration_t; + +#ifndef PIO_USB_DP_PIN_DEFAULT +#define PIO_USB_DP_PIN_DEFAULT 0 +#endif + +#define PIO_USB_TX_DEFAULT 0 +#define PIO_SM_USB_TX_DEFAULT 0 +#define PIO_USB_DMA_TX_DEFAULT 0 + +#define PIO_USB_RX_DEFAULT 0 +#define PIO_SM_USB_RX_DEFAULT 1 +#define PIO_SM_USB_EOP_DEFAULT 2 + +#define PIO_USB_DEBUG_PIN_NONE (-1) + +#define PIO_USB_DEFAULT_CONFIG \ + { \ + PIO_USB_DP_PIN_DEFAULT, PIO_USB_TX_DEFAULT, PIO_SM_USB_TX_DEFAULT, \ + PIO_USB_DMA_TX_DEFAULT, PIO_USB_RX_DEFAULT, PIO_SM_USB_RX_DEFAULT, \ + PIO_SM_USB_EOP_DEFAULT, NULL, PIO_USB_DEBUG_PIN_NONE, \ + PIO_USB_DEBUG_PIN_NONE, false, PIO_USB_PINOUT_DPDM \ + } + +#define PIO_USB_EP_POOL_CNT 32 +#define PIO_USB_DEV_EP_CNT 16 +#define PIO_USB_DEVICE_CNT 4 +#define PIO_USB_HUB_PORT_CNT 8 +#define PIO_USB_ROOT_PORT_CNT 2 + +#define PIO_USB_EP_SIZE 64 diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_device.c b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_device.c new file mode 100644 index 00000000..a11e7860 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_device.c @@ -0,0 +1,570 @@ +/** + * Copyright (c) 2021 sekigon-gonnoc + * Ha Thach (thach@tinyusb.org) + */ + +#pragma GCC push_options +#pragma GCC optimize("-O3") + +#include +#include +#include +#include + +#include "pio_usb.h" +#include "pio_usb_ll.h" +#include "usb_crc.h" + +#include "usb_rx.pio.h" +#include "usb_tx.pio.h" + +#include "hardware/dma.h" +#include "hardware/irq.h" +#include "hardware/gpio.h" +#include "hardware/pio.h" + +static uint8_t new_devaddr = 0; +static uint8_t ep0_crc5_lut[16]; +static __unused usb_descriptor_buffers_t descriptor_buffers; + +static uint8_t nak_encoded[5]; +static uint8_t stall_encoded[5]; + +static void __no_inline_not_in_flash_func(update_ep0_crc5_lut)(uint8_t addr) { + uint16_t dat; + uint8_t crc; + + for (int epnum = 0; epnum < 16; epnum++) { + dat = (addr) | (epnum << 7); + crc = calc_usb_crc5(dat); + ep0_crc5_lut[epnum] = (crc << 3) | ((epnum >> 1) & 0x07); + } +} + +static __always_inline void restart_usb_receiver(pio_port_t *pp) { + pio_sm_exec(pp->pio_usb_rx, pp->sm_rx, pp->rx_reset_instr2); + pio_sm_restart(pp->pio_usb_rx, pp->sm_rx); + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; +} + +static __always_inline uint8_t device_receive_token(void) { + pio_port_t *pp = PIO_USB_PIO_PORT(0); + uint8_t idx = 0; + uint8_t buffer[2]; + + if ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + while ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + if (pio_sm_get_rx_fifo_level(pp->pio_usb_rx, pp->sm_rx)) { + buffer[idx++] = pio_sm_get(pp->pio_usb_rx, pp->sm_rx) >> 24; + if (idx == 2) { + return buffer[1]; + } + } + } + } else { + // host is probably timeout. Ignore this packets. + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); + } + + return 0; +} + +static __always_inline int8_t device_receive_ep_address(uint8_t token, + uint8_t dev_addr) { + pio_port_t *pp = PIO_USB_PIO_PORT(0); + uint8_t idx = 0; + uint8_t addr; + uint8_t ep; + uint8_t ep_num = 0; + uint8_t buffer[3]; + bool match = false; + + static uint8_t eplut[2][8] = {{0, 2, 4, 6, 8, 10, 12, 14}, + {1, 3, 5, 7, 9, 11, 13, 15}}; + uint8_t *current_lut; + + if ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + while ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + if (pio_sm_get_rx_fifo_level(pp->pio_usb_rx, pp->sm_rx)) { + buffer[idx++] = pio_sm_get(pp->pio_usb_rx, pp->sm_rx) >> 24; + if ((idx == 1) && (token != USB_PID_SOF)) { + addr = buffer[0] & 0x7f; + current_lut = &eplut[buffer[0] >> 7][0]; + match = dev_addr == addr ? true : false; + } else if (idx == 2) { + ep_num = buffer[1]; + break; + } + } + } + } else { + // host is probably timeout. Ignore this packets. + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); + } + + if (match) { + ep = current_lut[ep_num & 0x07]; + if (ep0_crc5_lut[ep] == ep_num) { + return ep; + } else { + return -1; + } + } + + return -1; +} + +static __always_inline void wait_receive_complete(pio_port_t *pp) { + while ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + continue; + } + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); +} + +static void __no_inline_not_in_flash_func(usb_device_packet_handler)(void) { + pio_port_t *pp = PIO_USB_PIO_PORT(0); + root_port_t *rport = PIO_USB_ROOT_PORT(0); + + gpio_clr_mask(1<<3); + // + // time critical start + // + uint8_t addr = rport->dev_addr; + uint8_t token = device_receive_token(); + + if (token == USB_PID_IN) { + int8_t ep_num = device_receive_ep_address(token, addr); + if (ep_num < 0) { + gpio_set_mask(1 << 3); + return; + } + + endpoint_t *ep = PIO_USB_ENDPOINT((ep_num << 1) | 0x01); + + pio_sm_exec(pp->pio_usb_tx, pp->sm_tx, pp->tx_start_instr); + volatile bool has_transfer = ep->has_transfer; + + if (has_transfer) { + dma_channel_transfer_from_buffer_now(pp->tx_ch, ep->buffer, ep->encoded_data_len); + } else if (ep->stalled) { + dma_channel_transfer_from_buffer_now(pp->tx_ch, stall_encoded, sizeof(stall_encoded)); + } else { + dma_channel_transfer_from_buffer_now(pp->tx_ch, nak_encoded, sizeof(nak_encoded)); + } + + pp->pio_usb_tx->irq = IRQ_TX_ALL_MASK; // clear complete flag + while ((pp->pio_usb_tx->irq & IRQ_TX_ALL_MASK) == 0) { + continue; + } + + if (has_transfer) { + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; + irq_clear(pp->device_rx_irq_num); + pio_usb_bus_start_receive(pp); + + // wait for ack + pio_usb_bus_wait_handshake(pp); + + pio_usb_bus_start_receive(pp); + irq_clear(pp->device_rx_irq_num); + + // + // time critical end + // + + if (ep->ep_num == 0x80 && new_devaddr > 0) { + rport->dev_addr = new_devaddr; + new_devaddr = 0; + update_ep0_crc5_lut(rport->dev_addr); + } + + rport->ints |= PIO_USB_INTS_ENDPOINT_CONTINUE_BITS; + rport->ep_continue |= (1 << ep_num); + } else { + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; + irq_clear(pp->device_rx_irq_num); + restart_usb_receiver(pp); + pio_usb_bus_start_receive(pp); + + // + // time critical end + // + } + } else if (token == USB_PID_OUT) { + int8_t ep_num = device_receive_ep_address(token, addr); + wait_receive_complete(pp); + restart_usb_receiver(pp); + if (ep_num < 0) { + return; + } + endpoint_t *ep = PIO_USB_ENDPOINT(ep_num << 1); + + gpio_clr_mask(1<<4); + uint8_t hanshake = ep->stalled + ? USB_PID_STALL + : (ep->has_transfer ? USB_PID_ACK : USB_PID_NAK); + int res = pio_usb_bus_receive_packet_and_handshake(pp, hanshake); + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); + restart_usb_receiver(pp); + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; + irq_clear(pp->device_rx_irq_num); + + if (ep->has_transfer) { + if (res >= 0) { + memcpy(ep->app_buf, pp->usb_rx_buffer + 2, res); + pio_usb_ll_transfer_continue(ep, res); + } + } + } else if (token == USB_PID_SETUP) { + int8_t ep_num = device_receive_ep_address(token, addr); + restart_usb_receiver(pp); + if (ep_num < 0) { + return; + } + int res = pio_usb_bus_receive_packet_and_handshake(pp, USB_PID_ACK); + pio_sm_clear_fifos(pp->pio_usb_rx, pp->sm_rx); + restart_usb_receiver(pp); + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; + irq_clear(pp->device_rx_irq_num); + + if (res >= 0) { + rport->setup_packet = pp->usb_rx_buffer + 2; + rport->ints |= PIO_USB_INTS_SETUP_REQ_BITS; + + // DATA1 for both data and status stage + PIO_USB_ENDPOINT(0)->has_transfer = PIO_USB_ENDPOINT(1)->has_transfer = false; + PIO_USB_ENDPOINT(0)->data_id = PIO_USB_ENDPOINT(1)->data_id = 1; + PIO_USB_ENDPOINT(0)->stalled = PIO_USB_ENDPOINT(1)->stalled = false; + } + } else if (token == USB_PID_SOF) { + // SOF interrupt + device_receive_ep_address(token, addr); + wait_receive_complete(pp); + restart_usb_receiver(pp); + } else { + device_receive_ep_address(token, addr); + wait_receive_complete(pp); + restart_usb_receiver(pp); + } +} + +usb_device_t *pio_usb_device_init(const pio_usb_configuration_t *c, + const usb_descriptor_buffers_t *buffers) { + pio_port_t *pp = PIO_USB_PIO_PORT(0); + root_port_t *rport = PIO_USB_ROOT_PORT(0); + usb_device_t *dev = &pio_usb_device[0]; + + pio_usb_bus_init(pp, c, rport); + gpio_disable_pulls(rport->pin_dp); // needs external pull-up + rport->mode = PIO_USB_MODE_DEVICE; + + memset(dev, 0, sizeof(*dev)); + for (int i = 0; i < PIO_USB_DEV_EP_CNT; i++) { + dev->endpoint_id[i] = 2 * (i + 1); // only index IN endpoint + } + + update_ep0_crc5_lut(rport->dev_addr); + + float const cpu_freq = (float)clock_get_hz(clk_sys); + + pio_calculate_clkdiv_from_float(cpu_freq / 48000000, + &pp->clk_div_fs_tx.div_int, + &pp->clk_div_fs_tx.div_frac); + pio_calculate_clkdiv_from_float(cpu_freq / 96000000, + &pp->clk_div_fs_rx.div_int, + &pp->clk_div_fs_rx.div_frac); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_rx, rport->pin_dp); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + SM_SET_CLKDIV_MAXSPEED(pp->pio_usb_rx, pp->sm_rx); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, true); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_eop, rport->pin_dm); + pio_sm_set_in_pins(pp->pio_usb_rx, pp->sm_eop, rport->pin_dp); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_eop, false); + SM_SET_CLKDIV(pp->pio_usb_rx, pp->sm_eop, pp->clk_div_fs_rx); + + descriptor_buffers = *buffers; + + pio_usb_bus_prepare_receive(pp); + + // configure PIOx_IRQ_0 to detect packet receive start + pio_set_irqn_source_enabled(pp->pio_usb_rx, 0, pis_interrupt0 + IRQ_RX_START, + true); + pp->device_rx_irq_num = (pp->pio_usb_rx == pio0) ? PIO0_IRQ_0 : PIO1_IRQ_0; + irq_set_exclusive_handler(pp->device_rx_irq_num, usb_device_packet_handler); + irq_set_enabled(pp->device_rx_irq_num, true); + + + // pre-encode handshake packets + uint8_t raw_packet[] = {USB_SYNC, USB_PID_NAK}; + pio_usb_ll_encode_tx_data(raw_packet, 2, nak_encoded); + raw_packet[1] = USB_PID_STALL; + pio_usb_ll_encode_tx_data(raw_packet, 2, stall_encoded); + + return dev; +} + +//--------------------------------------------------------------------+ +// Device Controller functions +//--------------------------------------------------------------------+ + +void pio_usb_device_set_address(uint8_t dev_addr) { + new_devaddr = dev_addr; +} + +bool __no_inline_not_in_flash_func(pio_usb_device_endpoint_open)( + uint8_t const *desc_endpoint) { + const endpoint_descriptor_t *d = (const endpoint_descriptor_t *)desc_endpoint; + endpoint_t *ep = pio_usb_device_get_endpoint_by_address(d->epaddr); + + pio_usb_ll_configure_endpoint(ep, desc_endpoint); + ep->root_idx = 0; + ep->dev_addr = 0; // not used + ep->need_pre = 0; + ep->is_tx = (d->epaddr & 0x80) ? true : false; // device: endpoint in is tx + + return true; +} + +bool pio_usb_device_transfer(uint8_t ep_address, uint8_t *buffer, + uint16_t buflen) { + endpoint_t *ep = pio_usb_device_get_endpoint_by_address(ep_address); + return pio_usb_ll_transfer_start(ep, buffer, buflen); +} + +//--------------------------------------------------------------------+ +// USB Device Stack +//--------------------------------------------------------------------+ +static int8_t ep0_desc_request_type = -1; +static uint16_t ep0_desc_request_len; +static uint8_t ep0_desc_request_idx; + +static void __no_inline_not_in_flash_func(prepare_ep0_data)(uint8_t *data, + uint8_t len) { + // 0: control out (rx), 1 : control in (tx) + endpoint_t *ep = &pio_usb_ep_pool[1]; + + pio_usb_ll_transfer_start(ep, data, len); + + if (len) { + // there is data, prepare for status as well + pio_usb_ll_transfer_start(&pio_usb_ep_pool[0], NULL, 0); + } +} + +static void __no_inline_not_in_flash_func(prepare_ep0_rx)(uint8_t *data, + uint8_t len) { + // 0: control out (rx), 1 : control in (tx) + endpoint_t *ep = &pio_usb_ep_pool[0]; + + pio_usb_ll_transfer_start(ep, data, len); + + if (len) { + // there is data, prepare for status as well + pio_usb_ll_transfer_start(&pio_usb_ep_pool[1], NULL, 0); + } +} + +void pio_usb_device_task(void) { + root_port_t *rport = PIO_USB_ROOT_PORT(0); + pio_port_t *pp = PIO_USB_PIO_PORT(0); + if (rport->ints) { + pio_usb_device_irq_handler(0); + } + + switch (ep0_desc_request_type) { + case DESC_TYPE_CONFIG: { + uint16_t req_len = ep0_desc_request_len; + uint16_t desc_len = + descriptor_buffers.config[2] | (descriptor_buffers.config[3] << 8); + req_len = req_len > desc_len ? desc_len : req_len; + prepare_ep0_data((uint8_t *)descriptor_buffers.config, req_len); + ep0_desc_request_type = -1; + } break; + case DESC_TYPE_STRING: { + const uint16_t *str = + (uint16_t *)&descriptor_buffers.string[ep0_desc_request_idx]; + prepare_ep0_data((uint8_t *)str, str[0] & 0xff); + ep0_desc_request_type = -1; + } break; + case DESC_TYPE_HID_REPORT:{ + prepare_ep0_data( + (uint8_t *)descriptor_buffers.hid_report[ep0_desc_request_idx], + ep0_desc_request_len); + ep0_desc_request_type = -1; + } + default: + break; + } + + uint32_t se0_time_us =0; + bool reset = false; + while (pio_usb_bus_get_line_state(rport) == PORT_PIN_SE0) { + busy_wait_us_32(1); + se0_time_us++; + + if (se0_time_us == 1000) { + memset(pio_usb_ep_pool, 0, sizeof(pio_usb_ep_pool)); + rport->dev_addr = 0; + update_ep0_crc5_lut(rport->dev_addr); + + // init endpoint control in/out + PIO_USB_ENDPOINT(0)->size = 64; + PIO_USB_ENDPOINT(0)->ep_num = 0; + PIO_USB_ENDPOINT(0)->is_tx = false; + + PIO_USB_ENDPOINT(1)->size = 64; + PIO_USB_ENDPOINT(1)->ep_num = 0x80; + PIO_USB_ENDPOINT(1)->is_tx = true; + + // TODO should be reset end, this is reset start only + rport->ep_complete = rport->ep_stalled = rport->ep_error = 0; + rport->ints |= PIO_USB_INTS_RESET_END_BITS; + reset = true; + } + } + if (reset) { + restart_usb_receiver(pp); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_eop, true); + pp->pio_usb_rx->irq = IRQ_RX_ALL_MASK; + } +} + +static void __no_inline_not_in_flash_func(configure_all_endpoints)(uint8_t const *desc) { + uint8_t const *desc_end = desc + (descriptor_buffers.config[2] | + (descriptor_buffers.config[3] << 8)); + while (desc < desc_end) { + if (desc[1] == DESC_TYPE_ENDPOINT) { + pio_usb_device_endpoint_open(desc); + } + desc += desc[0]; + } +} + +static int __no_inline_not_in_flash_func(process_device_setup_stage)(uint8_t *buffer) { + int res = -1; + const usb_setup_packet_t *packet = (usb_setup_packet_t *)buffer; + + if (packet->request_type == USB_REQ_DIR_IN) { + if (packet->request == 0x06) { + if (packet->value_msb == DESC_TYPE_DEVICE) { + prepare_ep0_data((uint8_t *)descriptor_buffers.device, 18); + res = 0; + } else if (packet->value_msb == DESC_TYPE_CONFIG) { + ep0_desc_request_len = (packet->length_lsb | (packet->length_msb << 8)); + ep0_desc_request_type = DESC_TYPE_CONFIG; + res = 0; + } else if (packet->value_msb == DESC_TYPE_STRING) { + if (descriptor_buffers.string != NULL) { + ep0_desc_request_idx = packet->value_lsb; + ep0_desc_request_type = DESC_TYPE_STRING; + res = 0; + } + } + } + } else if (packet->request_type == USB_REQ_DIR_OUT) { + if (packet->request == 0x05) { + // set address + new_devaddr = packet->value_lsb; + prepare_ep0_data(NULL, 0); + res = 0; + } else if (packet->request == 0x09) { + // set configuration + configure_all_endpoints(descriptor_buffers.config); + prepare_ep0_data(NULL, 0); + res = 0; + } + } else if (packet->request_type == (USB_REQ_DIR_IN | USB_REQ_REC_IFACE)) { + if (packet->request == 0x06 && packet->value_msb == DESC_TYPE_HID_REPORT) { + // get hid report desc + ep0_desc_request_len = (packet->length_lsb | (packet->length_msb << 8)); + ep0_desc_request_idx = packet->index_lsb; + ep0_desc_request_type = DESC_TYPE_HID_REPORT; + res = 0; + } + } else if (packet->request_type == (USB_REQ_TYP_CLASS | USB_REQ_REC_IFACE)) { + if (packet->request == 0x09) { + // set hid report + static __unused uint8_t received_hid_report[8]; // not used + prepare_ep0_rx(received_hid_report, 8); + res = 0; + } else if (packet->request == 0x0A) { + // set hid idle request + prepare_ep0_data(NULL, 0); + res = 0; + } else if (packet->request == 0x0B) { + // set hid protocol request + prepare_ep0_data(NULL, 0); + res = 0; + } + } else if (packet->request_type == (USB_REQ_REC_EP)) { + prepare_ep0_data(NULL, 0); + res = 0; + } + + return res; +} + +// IRQ Handler +static void __no_inline_not_in_flash_func(__pio_usb_device_irq_handler)(uint8_t root_idx) { + root_port_t *root = PIO_USB_ROOT_PORT(root_idx); + usb_device_t *dev = &pio_usb_device[0]; + + uint32_t const ints = root->ints; + + if (ints & PIO_USB_INTS_RESET_END_BITS) { + memset(dev, 0, sizeof(*dev)); + for (int i = 0; i < PIO_USB_DEV_EP_CNT; i++) { + dev->endpoint_id[i] = 2 * (i + 1); // only index IN endpoint + } + } + + if (ints & PIO_USB_INTS_SETUP_REQ_BITS) { + process_device_setup_stage(root->setup_packet); + dev->control_pipe.stage = STAGE_DATA; + } + + if (ints & PIO_USB_INTS_ENDPOINT_COMPLETE_BITS) { + const uint32_t ep_all = root->ep_complete; + + // control out + if (ep_all & 0x01) { + if (dev->control_pipe.stage == STAGE_STATUS) { + dev->control_pipe.stage = STAGE_COMPLETE; + } else if (dev->control_pipe.stage == STAGE_DATA) { + dev->control_pipe.stage = STAGE_STATUS; + prepare_ep0_data(NULL, 0); + } + } + + // control in + if (ep_all & 0x02) { + if (dev->control_pipe.stage == STAGE_STATUS) { + dev->control_pipe.stage = STAGE_COMPLETE; + } + } + + // clear all + root->ep_complete &= ~ep_all; + } + + if (ints & PIO_USB_INTS_ENDPOINT_CONTINUE_BITS) { + for (int b = 0; b < 16; b++) { + if (root->ep_continue & (1 << b)) { + endpoint_t *ep = PIO_USB_ENDPOINT((b << 1) | 0x01); + uint16_t const xact_len = pio_usb_ll_get_transaction_len(ep); + pio_usb_ll_transfer_continue(ep, xact_len); + root->ep_continue &= ~(1 << b); + } + } + } + + // clear all + root->ints &= ~ints; +} + +// weak alias to __pio_usb_device_irq_handler +void pio_usb_device_irq_handler(uint8_t root_id) __attribute__ ((weak, alias("__pio_usb_device_irq_handler"))); + +#pragma GCC pop_options diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_host.c b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_host.c new file mode 100644 index 00000000..831bce91 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_host.c @@ -0,0 +1,1370 @@ +/** + * Copyright (c) 2021 sekigon-gonnoc + * Ha Thach (thach@tinyusb.org) + */ + +#pragma GCC push_options +#pragma GCC optimize("-O3") + +#include +#include +#include +#include + +#include "hardware/sync.h" +#include "hardware/pio.h" +#include "hardware/gpio.h" + +#include "pio_usb.h" +#include "pio_usb_ll.h" +#include "usb_crc.h" +#include "usb_rx.pio.h" +#include "usb_tx.pio.h" + +static alarm_pool_t *_alarm_pool = NULL; +static repeating_timer_t sof_rt; +// The sof_count may be incremented and then read on different cores. +static volatile uint32_t sof_count = 0; +static bool timer_active; + +static volatile bool cancel_timer_flag; +static volatile bool start_timer_flag; +static __unused uint32_t int_stat; +static uint8_t sof_packet[4] = {USB_SYNC, USB_PID_SOF, 0x00, 0x10}; +static uint8_t sof_packet_encoded[4 * 2 * 7 / 6 + 2]; +static uint8_t sof_packet_encoded_len; + +static bool sof_timer(repeating_timer_t *_rt); + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +static void start_timer(alarm_pool_t *alarm_pool) { + if (timer_active) { + return; + } + + if (alarm_pool != NULL) { + alarm_pool_add_repeating_timer_us(alarm_pool, -1000, sof_timer, NULL, + &sof_rt); + } + + timer_active = true; +} + +static __unused void stop_timer(void) { + cancel_repeating_timer(&sof_rt); + timer_active = false; +} + +usb_device_t *pio_usb_host_init(const pio_usb_configuration_t *c) { + pio_port_t *pp = PIO_USB_PIO_PORT(0); + root_port_t *root = PIO_USB_ROOT_PORT(0); + + pio_usb_bus_init(pp, c, root); + root->mode = PIO_USB_MODE_HOST; + + float const cpu_freq = (float)clock_get_hz(clk_sys); + pio_calculate_clkdiv_from_float(cpu_freq / 48000000, + &pp->clk_div_fs_tx.div_int, + &pp->clk_div_fs_tx.div_frac); + pio_calculate_clkdiv_from_float(cpu_freq / 6000000, + &pp->clk_div_ls_tx.div_int, + &pp->clk_div_ls_tx.div_frac); + + pio_calculate_clkdiv_from_float(cpu_freq / 96000000, + &pp->clk_div_fs_rx.div_int, + &pp->clk_div_fs_rx.div_frac); + pio_calculate_clkdiv_from_float(cpu_freq / 12000000, + &pp->clk_div_ls_rx.div_int, + &pp->clk_div_ls_rx.div_frac); + + sof_packet_encoded_len = + pio_usb_ll_encode_tx_data(sof_packet, sizeof(sof_packet), sof_packet_encoded); + + if (!c->skip_alarm_pool) { + _alarm_pool = c->alarm_pool; + if (!_alarm_pool) { + _alarm_pool = alarm_pool_create(2, 1); + } + } + start_timer(_alarm_pool); + + return &pio_usb_device[0]; +} + +void pio_usb_host_stop(void) { + cancel_timer_flag = true; + while (cancel_timer_flag) { + continue; + } +} + +void pio_usb_host_restart(void) { + start_timer_flag = true; + while (start_timer_flag) { + continue; + } +} + +//--------------------------------------------------------------------+ +// Bus functions +//--------------------------------------------------------------------+ + +static void __no_inline_not_in_flash_func(override_pio_program)(PIO pio, const pio_program_t* program, uint offset) { + for (uint i = 0; i < program->length; ++i) { + uint16_t instr = program->instructions[i]; + pio->instr_mem[offset + i] = + pio_instr_bits_jmp != _pio_major_instr_bits(instr) ? instr + : instr + offset; + } +} + +static __always_inline void override_pio_rx_program(PIO pio, + const pio_program_t *program, + const pio_program_t *debug_program, + uint offset, int debug_pin) { + if (debug_pin < 0) { + override_pio_program(pio, program, offset); + } else { + override_pio_program(pio, debug_program, offset); + } +} + +static void +__no_inline_not_in_flash_func(configure_tx_program)(pio_port_t *pp, + root_port_t *port) { + if (port->pinout == PIO_USB_PINOUT_DPDM) { + pp->fs_tx_program = &usb_tx_dpdm_program; + pp->fs_tx_pre_program = &usb_tx_pre_dpdm_program; + pp->ls_tx_program = &usb_tx_dmdp_program; + } else { + pp->fs_tx_program = &usb_tx_dmdp_program; + pp->fs_tx_pre_program = &usb_tx_pre_dmdp_program; + pp->ls_tx_program = &usb_tx_dpdm_program; + } +} + +static void __no_inline_not_in_flash_func(configure_fullspeed_host)( + pio_port_t *pp, root_port_t *port) { + configure_tx_program(pp, port); + pio_sm_clear_fifos(pp->pio_usb_tx, pp->sm_tx); + override_pio_program(pp->pio_usb_tx, pp->fs_tx_program, pp->offset_tx); + SM_SET_CLKDIV(pp->pio_usb_tx, pp->sm_tx, pp->clk_div_fs_tx); + usb_tx_configure_pins(pp->pio_usb_tx, pp->sm_tx, port->pin_dp, port->pin_dm); + pio_sm_exec(pp->pio_usb_tx, pp->sm_tx, pp->tx_reset_instr); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_rx, port->pin_dp); + SM_SET_CLKDIV_MAXSPEED(pp->pio_usb_rx, pp->sm_rx); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_eop, port->pin_dm); + pio_sm_set_in_pins(pp->pio_usb_rx, pp->sm_eop, port->pin_dp); + SM_SET_CLKDIV(pp->pio_usb_rx, pp->sm_eop, pp->clk_div_fs_rx); +} + +static void __no_inline_not_in_flash_func(configure_lowspeed_host)( + pio_port_t *pp, root_port_t *port) { + configure_tx_program(pp, port); + pio_sm_clear_fifos(pp->pio_usb_tx, pp->sm_tx); + override_pio_program(pp->pio_usb_tx, pp->ls_tx_program, pp->offset_tx); + SM_SET_CLKDIV(pp->pio_usb_tx, pp->sm_tx, pp->clk_div_ls_tx); + usb_tx_configure_pins(pp->pio_usb_tx, pp->sm_tx, port->pin_dp, port->pin_dm); + pio_sm_exec(pp->pio_usb_tx, pp->sm_tx, pp->tx_reset_instr); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_rx, port->pin_dm); + SM_SET_CLKDIV_MAXSPEED(pp->pio_usb_rx, pp->sm_rx); + + pio_sm_set_jmp_pin(pp->pio_usb_rx, pp->sm_eop, port->pin_dp); + pio_sm_set_in_pins(pp->pio_usb_rx, pp->sm_eop, port->pin_dm); + SM_SET_CLKDIV(pp->pio_usb_rx, pp->sm_eop, pp->clk_div_ls_rx); +} + +static void __no_inline_not_in_flash_func(configure_root_port)( + pio_port_t *pp, root_port_t *root) { + if (root->is_fullspeed) { + configure_fullspeed_host(pp, root); + } else { + configure_lowspeed_host(pp, root); + } +} + +static void __no_inline_not_in_flash_func(restore_fs_bus)(const pio_port_t *pp) { + // change bus speed to full-speed + pio_sm_set_enabled(pp->pio_usb_tx, pp->sm_tx, false); + SM_SET_CLKDIV(pp->pio_usb_tx, pp->sm_tx, pp->clk_div_fs_tx); + pio_sm_set_enabled(pp->pio_usb_tx, pp->sm_tx, true); + + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + SM_SET_CLKDIV_MAXSPEED(pp->pio_usb_rx, pp->sm_rx); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, true); + + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_eop, false); + SM_SET_CLKDIV(pp->pio_usb_rx, pp->sm_eop, pp->clk_div_fs_rx); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_eop, true); +} + +// Time about 1us ourselves so it lives in RAM. +static void __not_in_flash_func(busy_wait_1_us)(void) { + uint32_t start = timer_hw->timerawl; + while (timer_hw->timerawl == start) { + tight_loop_contents(); + } +} + +static bool __no_inline_not_in_flash_func(connection_check)(root_port_t *port) { + if (pio_usb_bus_get_line_state(port) == PORT_PIN_SE0) { + busy_wait_1_us(); + + if (pio_usb_bus_get_line_state(port) == PORT_PIN_SE0) { + busy_wait_1_us(); + // device disconnect + port->connected = false; + port->suspended = true; + port->ints |= PIO_USB_INTS_DISCONNECT_BITS; + + // failed/retired all queuing transfer in this root + uint8_t root_idx = port - PIO_USB_ROOT_PORT(0); + for (int ep_idx = 0; ep_idx < PIO_USB_EP_POOL_CNT; ep_idx++) { + endpoint_t *ep = PIO_USB_ENDPOINT(ep_idx); + if ((ep->root_idx == root_idx) && ep->size && ep->has_transfer) { + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_ERROR_BITS); + } + } + + return false; + } + } + + return true; +} + +//--------------------------------------------------------------------+ +// SOF +//--------------------------------------------------------------------+ +static int usb_setup_transaction(pio_port_t *pp, endpoint_t *ep); +static int usb_in_transaction(pio_port_t *pp, endpoint_t *ep); +static int usb_out_transaction(pio_port_t *pp, endpoint_t *ep); + +void __not_in_flash_func(pio_usb_host_frame)(void) { + if (!timer_active) { + return; + } + + pio_port_t *pp = PIO_USB_PIO_PORT(0); + + // Send SOF + for (int root_idx = 0; root_idx < PIO_USB_ROOT_PORT_CNT; root_idx++) { + root_port_t *root = PIO_USB_ROOT_PORT(root_idx); + if (!(root->initialized && root->connected && !root->suspended && + connection_check(root))) { + continue; + } + configure_root_port(pp, root); + pio_usb_bus_usb_transfer(pp, sof_packet_encoded, sof_packet_encoded_len); + } + + // Carry out all queued endpoint transaction + for (int root_idx = 0; root_idx < PIO_USB_ROOT_PORT_CNT; root_idx++) { + root_port_t *root = PIO_USB_ROOT_PORT(root_idx); + if (!(root->initialized && root->connected && !root->suspended)) { + continue; + } + + configure_root_port(pp, root); + + for (int ep_pool_idx = 0; ep_pool_idx < PIO_USB_EP_POOL_CNT; + ep_pool_idx++) { + endpoint_t *ep = PIO_USB_ENDPOINT(ep_pool_idx); + if ((ep->root_idx == root_idx) && ep->size) { + bool const is_periodic = ((ep->attr & 0x03) == EP_ATTR_INTERRUPT); + + if (is_periodic && (ep->interval_counter > 0)) { + ep->interval_counter--; + continue; + } + + if (ep->has_transfer && !ep->transfer_aborted) { + ep->transfer_started = true; + + if (ep->need_pre) { + pp->need_pre = true; + } + + if (ep->ep_num == 0 && ep->data_id == USB_PID_SETUP) { + usb_setup_transaction(pp, ep); + } else { + if (ep->ep_num & EP_IN) { + usb_in_transaction(pp, ep); + } else { + usb_out_transaction(pp, ep); + } + + if (is_periodic) { + ep->interval_counter = ep->interval - 1; + } + } + + if (ep->need_pre) { + pp->need_pre = false; + restore_fs_bus(pp); + } + + ep->transfer_started = false; + } + } + } + } + + // check for new connection to root hub + for (int root_idx = 0; root_idx < PIO_USB_ROOT_PORT_CNT; root_idx++) { + root_port_t *root = PIO_USB_ROOT_PORT(root_idx); + if (root->initialized && !root->connected) { + port_pin_status_t const line_state = pio_usb_bus_get_line_state(root); + if (line_state == PORT_PIN_FS_IDLE || line_state == PORT_PIN_LS_IDLE) { + root->is_fullspeed = (line_state == PORT_PIN_FS_IDLE); + root->connected = true; + root->suspended = true; // need a bus reset before operating + root->ints |= PIO_USB_INTS_CONNECT_BITS; + } + } + } + + // Invoke IRQHandler if interrupt status is set + for (uint8_t root_idx = 0; root_idx < PIO_USB_ROOT_PORT_CNT; root_idx++) { + if (PIO_USB_ROOT_PORT(root_idx)->ints) { + pio_usb_host_irq_handler(root_idx); + } + } + + sof_count++; + + // SOF counter is 11-bit + uint16_t const sof_count_11b = sof_count & 0x7ff; + sof_packet[2] = sof_count_11b & 0xff; + sof_packet[3] = (calc_usb_crc5(sof_count_11b) << 3) | (sof_count_11b >> 8); + sof_packet_encoded_len = + pio_usb_ll_encode_tx_data(sof_packet, sizeof(sof_packet), sof_packet_encoded); +} + +static bool __no_inline_not_in_flash_func(sof_timer)(repeating_timer_t *_rt) { + (void)_rt; + + pio_usb_host_frame(); + + return true; +} + +//--------------------------------------------------------------------+ +// Host Controller functions +//--------------------------------------------------------------------+ + +uint32_t pio_usb_host_get_frame_number(void) { + return sof_count; +} + +void pio_usb_host_port_reset_start(uint8_t root_idx) { + root_port_t *root = PIO_USB_ROOT_PORT(root_idx); + + // bus is not operating while in reset + root->suspended = true; + + // Force line state to SE0 + gpio_set_outover(root->pin_dp, GPIO_OVERRIDE_LOW); + gpio_set_outover(root->pin_dm, GPIO_OVERRIDE_LOW); + gpio_set_oeover(root->pin_dp, GPIO_OVERRIDE_HIGH); + gpio_set_oeover(root->pin_dm, GPIO_OVERRIDE_HIGH); +} + +void pio_usb_host_port_reset_end(uint8_t root_idx) { + root_port_t *root = PIO_USB_ROOT_PORT(root_idx); + + // line state to input + gpio_set_oeover(root->pin_dp, GPIO_OVERRIDE_NORMAL); + gpio_set_oeover(root->pin_dm, GPIO_OVERRIDE_NORMAL); + gpio_set_outover(root->pin_dp, GPIO_OVERRIDE_NORMAL); + gpio_set_outover(root->pin_dm, GPIO_OVERRIDE_NORMAL); + busy_wait_us(100); // TODO check if this is neccessary + + // bus back to operating + root->suspended = false; +} + +void pio_usb_host_close_device(uint8_t root_idx, uint8_t device_address) { + for (int ep_pool_idx = 0; ep_pool_idx < PIO_USB_EP_POOL_CNT; ep_pool_idx++) { + endpoint_t *ep = PIO_USB_ENDPOINT(ep_pool_idx); + if ((ep->root_idx == root_idx) && (ep->dev_addr == device_address) && + ep->size) { + ep->size = 0; + ep->has_transfer = false; + } + } +} + +static inline __force_inline endpoint_t * _find_ep(uint8_t root_idx, + uint8_t device_address, uint8_t ep_address) { + for (int ep_pool_idx = 0; ep_pool_idx < PIO_USB_EP_POOL_CNT; ep_pool_idx++) { + endpoint_t *ep = PIO_USB_ENDPOINT(ep_pool_idx); + // note 0x00 and 0x80 are matched as control endpoint of opposite direction + if ((ep->root_idx == root_idx) && (ep->dev_addr == device_address) && + ep->size && + ((ep->ep_num == ep_address) || + (((ep_address & 0x7f) == 0) && ((ep->ep_num & 0x7f) == 0)))) { + return ep; + } + } + + return NULL; +} + +bool pio_usb_host_endpoint_open(uint8_t root_idx, uint8_t device_address, + uint8_t const *desc_endpoint, bool need_pre) { + const endpoint_descriptor_t *d = (const endpoint_descriptor_t *)desc_endpoint; + for (int ep_pool_idx = 0; ep_pool_idx < PIO_USB_EP_POOL_CNT; ep_pool_idx++) { + endpoint_t *ep = PIO_USB_ENDPOINT(ep_pool_idx); + // ep size is used as valid indicator + if (ep->size == 0) { + pio_usb_ll_configure_endpoint(ep, desc_endpoint); + ep->root_idx = root_idx; + ep->dev_addr = device_address; + ep->need_pre = need_pre; + ep->is_tx = (d->epaddr & 0x80) ? false : true; // host endpoint out is tx + return true; + } + } + + return false; +} + +bool pio_usb_host_send_setup(uint8_t root_idx, uint8_t device_address, + uint8_t const setup_packet[8]) { + endpoint_t *ep = _find_ep(root_idx, device_address, 0); + if (!ep) { + printf("cannot find ep 0x00\r\n"); + return false; + } + + ep->ep_num = 0; // setup is is OUT + ep->data_id = USB_PID_SETUP; + ep->is_tx = true; + + return pio_usb_ll_transfer_start(ep, (uint8_t *)setup_packet, 8); +} + +bool pio_usb_host_endpoint_transfer(uint8_t root_idx, uint8_t device_address, + uint8_t ep_address, uint8_t *buffer, + uint16_t buflen) { + endpoint_t *ep = _find_ep(root_idx, device_address, ep_address); + if (!ep) { + printf("no endpoint 0x%02X\r\n", ep_address); + return false; + } + + // Control endpoint, address may switch between 0x00 <-> 0x80 + // therefore we need to update ep_num and is_tx + if ((ep_address & 0x7f) == 0) { + ep->ep_num = ep_address; + ep->is_tx = ep_address == 0; + ep->data_id = 1; // data and status always start with DATA1 + } + + return pio_usb_ll_transfer_start(ep, buffer, buflen); +} + +bool pio_usb_host_endpoint_abort_transfer(uint8_t root_idx, uint8_t device_address, + uint8_t ep_address) { + endpoint_t *ep = _find_ep(root_idx, device_address, ep_address); + if (!ep) { + printf("no endpoint 0x%02X\r\n", ep_address); + return false; + } + + if (!ep->has_transfer) { + return false; // no transfer to abort + } + + // mark transfer as aborted + ep->transfer_aborted = true; + + // Race potential: SOF timer can be called before transfer_aborted is actually set + // and started the transfer. Wait 1 usb frame for transaction to complete. + // On the next SOF timer, transfer_aborted will be checked and skipped + while (ep->has_transfer && ep->transfer_started) { + busy_wait_ms(1); + } + + // check if transfer is still active (could be completed) + bool const still_active = ep->has_transfer; + if (still_active) { + ep->has_transfer = false; + } + ep->transfer_aborted = false; + + return still_active; // still active means transfer is successfully aborted +} + +//--------------------------------------------------------------------+ +// Transaction helper +//--------------------------------------------------------------------+ + +static int __no_inline_not_in_flash_func(usb_in_transaction)(pio_port_t *pp, + endpoint_t *ep) { + int res = 0; + uint8_t expect_pid = (ep->data_id == 1) ? USB_PID_DATA1 : USB_PID_DATA0; + + pio_usb_bus_prepare_receive(pp); + pio_usb_bus_send_token(pp, USB_PID_IN, ep->dev_addr, ep->ep_num); + pio_usb_bus_start_receive(pp); + + int receive_len = pio_usb_bus_receive_packet_and_handshake(pp, USB_PID_ACK); + uint8_t const receive_pid = pp->usb_rx_buffer[1]; + + if (receive_len >= 0) { + if (receive_pid == expect_pid) { + memcpy(ep->app_buf, &pp->usb_rx_buffer[2], receive_len); + pio_usb_ll_transfer_continue(ep, receive_len); + } else { + // DATA0/1 mismatched, 0 for re-try next frame + } + } else if (receive_pid == USB_PID_NAK) { + // NAK try again next frame + } else if (receive_pid == USB_PID_STALL) { + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_STALLED_BITS); + } else { + res = -1; + if ((pp->pio_usb_rx->irq & IRQ_RX_COMP_MASK) == 0) { + res = -2; + } + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_ERROR_BITS); + } + + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + pp->usb_rx_buffer[0] = 0; + pp->usb_rx_buffer[1] = 0; + + return res; +} + +static int __no_inline_not_in_flash_func(usb_out_transaction)(pio_port_t *pp, + endpoint_t *ep) { + int res = 0; + + uint16_t const xact_len = pio_usb_ll_get_transaction_len(ep); + + pio_usb_bus_prepare_receive(pp); + pio_usb_bus_send_token(pp, USB_PID_OUT, ep->dev_addr, ep->ep_num); + + pio_usb_bus_usb_transfer(pp, ep->buffer, ep->encoded_data_len); + pio_usb_bus_start_receive(pp); + + pio_usb_bus_wait_handshake(pp); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + + uint8_t const receive_token = pp->usb_rx_buffer[1]; + + if (receive_token == USB_PID_ACK) { + pio_usb_ll_transfer_continue(ep, xact_len); + } else if (receive_token == USB_PID_NAK) { + // NAK try again next frame + } else if (receive_token == USB_PID_STALL) { + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_STALLED_BITS); + } else { + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_ERROR_BITS); + } + + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + pp->usb_rx_buffer[0] = 0; + pp->usb_rx_buffer[1] = 0; + + return res; +} + +static int __no_inline_not_in_flash_func(usb_setup_transaction)( + pio_port_t *pp, endpoint_t *ep) { + + int res = 0; + + // Setup token + pio_usb_bus_prepare_receive(pp); + + pio_usb_bus_send_token(pp, USB_PID_SETUP, ep->dev_addr, 0); + + // Data + ep->data_id = 0; // set to DATA0 + pio_usb_bus_usb_transfer(pp, ep->buffer, ep->encoded_data_len); + + // Handshake + pio_usb_bus_start_receive(pp); + pio_usb_bus_wait_handshake(pp); + pio_sm_set_enabled(pp->pio_usb_rx, pp->sm_rx, false); + + ep->actual_len = 8; + + if (pp->usb_rx_buffer[0] == USB_SYNC && pp->usb_rx_buffer[1] == USB_PID_ACK) { + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_COMPLETE_BITS); + } else { + res = -1; + pio_usb_ll_transfer_complete(ep, PIO_USB_INTS_ENDPOINT_ERROR_BITS); + } + + pp->usb_rx_buffer[1] = 0; // reset buffer + + return res; +} + +//--------------------------------------------------------------------+ +// USB Host Stack +//--------------------------------------------------------------------+ +static void on_device_connect(pio_port_t *pp, root_port_t *root, + int device_idx) { + bool fullspeed_flag = false; + + if (pio_usb_bus_get_line_state(root) == PORT_PIN_FS_IDLE) { + fullspeed_flag = true; + } else if (pio_usb_bus_get_line_state(root) == PORT_PIN_LS_IDLE) { + fullspeed_flag = false; + } + + pio_sm_set_pins_with_mask(pp->pio_usb_tx, pp->sm_tx, 0, + (1 << root->pin_dp) | (1 << root->pin_dm)); + pio_sm_set_pindirs_with_mask(pp->pio_usb_tx, pp->sm_tx, + (1 << root->pin_dp) | (1 << root->pin_dm), + (1 << root->pin_dp) | (1 << root->pin_dm)); + + busy_wait_ms(100); + + pio_sm_set_pindirs_with_mask(pp->pio_usb_tx, pp->sm_tx, 0, + (1 << root->pin_dp) | (1 << root->pin_dm)); + + busy_wait_us(100); + + root->suspended = false; + + if (fullspeed_flag && pio_usb_bus_get_line_state(root) == PORT_PIN_FS_IDLE) { + root->root_device = &pio_usb_device[device_idx]; + if (!root->root_device->connected) { + configure_fullspeed_host(pp, root); + root->root_device->is_fullspeed = true; + root->root_device->is_root = true; + root->root_device->connected = true; + root->root_device->root = root; + root->root_device->event = EVENT_CONNECT; + } + } else if (!fullspeed_flag && pio_usb_bus_get_line_state(root) == PORT_PIN_LS_IDLE) { + root->root_device = &pio_usb_device[device_idx]; + if (!root->root_device->connected) { + configure_lowspeed_host(pp, root); + root->root_device->is_fullspeed = false; + root->root_device->is_root = true; + root->root_device->connected = true; + root->root_device->root = root; + root->root_device->event = EVENT_CONNECT; + } + } + + endpoint_descriptor_t ep0_desc = { + sizeof(endpoint_descriptor_t), DESC_TYPE_ENDPOINT, 0x00, 0x00, { 0x08, 0x00 }, 0x00 + }; + pio_usb_host_endpoint_open(root - pio_usb_root_port, 0x00, + (uint8_t const *)&ep0_desc, false); +} + +static int __no_inline_not_in_flash_func(control_out_protocol)( + usb_device_t *device, uint8_t *setup_data, uint16_t setup_length, + uint8_t *out_data, uint16_t out_length) { + int res = 0; + + control_pipe_t *pipe = &device->control_pipe; + + if (pipe->operation == CONTROL_NONE) { + pipe->setup_packet.tx_address = setup_data; + pipe->setup_packet.tx_length = setup_length; + pipe->out_data_packet.tx_address = out_data; + pipe->out_data_packet.tx_length = out_length; + pipe->operation = CONTROL_OUT; + + pio_usb_host_send_setup(device->root - pio_usb_root_port, device->address, setup_data); + } else { + return -1; + } + + const uint64_t timeout = 5000 * 1000; // 5s + uint64_t start_time = time_us_64(); + while (pipe->operation == CONTROL_OUT && + time_us_64() - start_time < timeout) { + if (!device->connected) { + pipe->operation = CONTROL_NONE; + return -1; + } + } + + if (time_us_64() - start_time >= timeout) { + printf("control out[timeout]\n"); + res = -2; + } else if (pipe->operation == CONTROL_ERROR) { + printf("control out[error]\n"); + res = -1; + } else if (pipe->operation == CONTROL_COMPLETE) { + printf("control out[complete]\n"); + res = 0; + } + pipe->operation = CONTROL_NONE; + + return res; +} + +static int __no_inline_not_in_flash_func(control_in_protocol)( + usb_device_t *device, uint8_t *tx_data, uint16_t tx_length, + uint8_t *rx_buffer, uint16_t request_length) { + int res = 0; + + control_pipe_t *pipe = &device->control_pipe; + + if (pipe->operation == CONTROL_NONE) { + pipe->setup_packet.tx_address = tx_data; + pipe->setup_packet.tx_length = tx_length; + pipe->rx_buffer = rx_buffer; + pipe->request_length = request_length; + pipe->operation = CONTROL_IN; + + pio_usb_host_send_setup(device->root - pio_usb_root_port, device->address, tx_data); + } else { + return -1; + } + + const uint64_t timeout = 5000 * 1000; // 5s + uint64_t start_time = time_us_64(); + while (pipe->operation == CONTROL_IN && + time_us_64() - start_time < timeout) { + if (!device->connected) { + pipe->operation = CONTROL_NONE; + return -1; + } + } + + if (time_us_64() - start_time >= timeout) { + printf("control in[timeout]\n"); + res = -2; + } else if (pipe->operation == CONTROL_ERROR) { + printf("control in[error]\n"); + res = -1; + } else if (pipe->operation == CONTROL_COMPLETE) { + printf("control in[complete]\n"); + res = 0; + } + pipe->operation = CONTROL_NONE; + + return res; +} + +static int set_hub_feature(usb_device_t *device, uint8_t port, uint8_t value) { + usb_setup_packet_t req = SET_HUB_FEATURE_REQUEST; + req.index_lsb = port + 1; + req.value_lsb = value; + return control_out_protocol(device, (uint8_t *)&req, sizeof(req), NULL, 0); +} + +static int clear_hub_feature(usb_device_t *device, uint8_t port, + uint8_t value) { + usb_setup_packet_t req = CLEAR_HUB_FEATURE_REQUEST; + req.index_lsb = port + 1; + req.value_lsb = value; + return control_out_protocol(device, (uint8_t *)&req, sizeof(req), NULL, 0); +} + +static int get_hub_port_status(usb_device_t *device, uint8_t port, + hub_port_status_t *status) { + usb_setup_packet_t req = GET_HUB_PORT_STATUS_REQUEST; + req.index_lsb = port + 1; + return control_in_protocol(device, (uint8_t *)&req, sizeof(req), (uint8_t*)status, + sizeof(*status)); +} + +static int initialize_hub(usb_device_t *device) { + uint8_t rx_buffer[16]; + int res = 0; + printf("USB Hub detected\n"); + usb_setup_packet_t get_hub_desc_request = GET_HUB_DESCRPTOR_REQUEST; + control_in_protocol(device, (uint8_t *)&get_hub_desc_request, + sizeof(get_hub_desc_request), rx_buffer, 8); + const hub_descriptor_t *desc = (hub_descriptor_t *)rx_buffer; + uint8_t port_num = desc->port_num; + + printf("\tTurn on port powers\n"); + for (int idx = 0; idx < port_num; idx++) { + res = set_hub_feature(device, idx, HUB_SET_PORT_POWER); + if (res != 0) { + printf("\tFailed to turn on ports\n"); + break; + } + } + + busy_wait_ms(500); + + return res; +} + +static int get_string_descriptor(usb_device_t *device, uint8_t idx, + uint8_t *rx_buffer, uint8_t *str_buffer) { + int res = -1; + usb_setup_packet_t req = GET_DEVICE_DESCRIPTOR_REQ_DEFAULT; + req.value_msb = DESC_TYPE_STRING; + req.value_lsb = idx; + req.length_lsb = 1; + req.length_msb = 0; + res = control_in_protocol(device, (uint8_t *)&req, sizeof(req), rx_buffer, 1); + if (res != 0) { + return res; + } + + uint8_t len = rx_buffer[0]; + req.length_lsb = len; + req.length_msb = 0; + res = + control_in_protocol(device, (uint8_t *)&req, sizeof(req), rx_buffer, len); + if (res != 0) { + return res; + } + + uint16_t *wchar_buffer = (uint16_t *)(uintptr_t) rx_buffer; + for (int i = 0; i < (len - 2) / 2; i++) { + str_buffer[i] = wchar_buffer[i + 1]; + } + str_buffer[(len - 2) / 2] = '\0'; + + return res; +} + +static int enumerate_device(usb_device_t *device, uint8_t address) { + int res = 0; + uint8_t rx_buffer[512]; + + usb_setup_packet_t get_device_descriptor_request = + GET_DEVICE_DESCRIPTOR_REQ_DEFAULT; + res = control_in_protocol(device, (uint8_t *)&get_device_descriptor_request, + sizeof(get_device_descriptor_request), rx_buffer, 18); + if (res != 0) { + pio_usb_host_close_device(device->root - pio_usb_root_port, 0); + return res; + } + + const device_descriptor_t *desc = + (device_descriptor_t *)device->control_pipe.rx_buffer; + device->vid = desc->vid[0] | (desc->vid[1] << 8); + device->pid = desc->pid[0] | (desc->pid[1] << 8); + device->device_class = desc->device_class; + uint8_t idx_manufacture = desc->manufacture; + uint8_t idx_product = desc->product; + uint8_t idx_serial = desc->serial; + + printf("Enumerating %04x:%04x, class:%d, address:%d\n", device->vid, + device->pid, device->device_class, address); + + usb_setup_packet_t set_address_request = SET_ADDRESS_REQ_DEFAULT; + set_address_request.value_lsb = address; + set_address_request.value_msb = 0; + res = control_out_protocol(device, (uint8_t *)&set_address_request, + sizeof(set_address_request), NULL, 0); + pio_usb_host_close_device(device->root - pio_usb_root_port, 0); + if (res != 0) { + return res; + } + device->address = address; + + endpoint_descriptor_t ep0_desc = { + sizeof(endpoint_descriptor_t), DESC_TYPE_ENDPOINT, 0x00, 0x00, { desc->max_packet_size, 0x00 }, 0x00 + }; + pio_usb_host_endpoint_open(device->root - pio_usb_root_port, address, + (uint8_t const *)&ep0_desc, + !device->is_root && !device->is_fullspeed); + + uint8_t str[64]; + if (idx_manufacture != 0) { + res = get_string_descriptor(device, idx_manufacture, rx_buffer, str); + if (res == 0) { + printf("Manufacture:%s\n", str); + } else { + printf("Failed to get string descriptor (Manufacture)\n"); + } + stdio_flush(); + } + + if (idx_product != 0) { + res = get_string_descriptor(device, idx_product, rx_buffer, str); + if (res == 0) { + printf("Product:%s\n", str); + } else { + printf("Failed to get string descriptor (Product)\n"); + } + stdio_flush(); + } + + if (idx_serial != 0) { + res = get_string_descriptor(device, idx_serial, rx_buffer, str); + if (res == 0) { + printf("Serial:%s\n", str); + } else { + printf("Failed to get string descriptor (Serial)\n"); + } + stdio_flush(); + } + + usb_setup_packet_t get_configuration_descriptor_request = + GET_CONFIGURATION_DESCRIPTOR_REQ_DEFAULT; + get_configuration_descriptor_request.length_lsb = 9; + get_configuration_descriptor_request.length_msb = 0; + res = control_in_protocol( + device, (uint8_t *)&get_configuration_descriptor_request, + sizeof(get_configuration_descriptor_request), rx_buffer, 9); + if (res != 0) { + return res; + } + + get_configuration_descriptor_request.length_lsb = + ((configuration_descriptor_t *)(device->control_pipe.rx_buffer)) + ->total_length_lsb; + get_configuration_descriptor_request.length_msb = + ((configuration_descriptor_t *)(device->control_pipe.rx_buffer)) + ->total_length_msb; + uint16_t request_length = + get_configuration_descriptor_request.length_lsb | + (get_configuration_descriptor_request.length_msb << 8); + res = control_in_protocol( + device, (uint8_t *)&get_configuration_descriptor_request, + sizeof(get_configuration_descriptor_request), rx_buffer, request_length); + + if (res != 0) { + return res; + } + uint8_t configuration_descrptor_data[512]; + int16_t configuration_descrptor_length = + request_length > 512 ? 512 : request_length; + memcpy(configuration_descrptor_data, + (const void *)device->control_pipe.rx_buffer, + configuration_descrptor_length); + + usb_setup_packet_t set_usb_configuration_request = + SET_CONFIGURATION_REQ_DEFAULT; + set_usb_configuration_request.value_lsb = + ((configuration_descriptor_t *)(device->control_pipe.rx_buffer)) + ->configuration_value; + res = control_out_protocol(device, (uint8_t *)&set_usb_configuration_request, + sizeof(set_usb_configuration_request), NULL, 0); + + if (res != 0) { + return res; + } + volatile uint8_t ep_id_idx = 0; + volatile uint8_t interface = 0; + volatile uint8_t class = 0; + uint8_t *descriptor = configuration_descrptor_data; + while (configuration_descrptor_length > 0) { + switch (descriptor[1]) { + case DESC_TYPE_INTERFACE: { + const interface_descriptor_t *d = + (const interface_descriptor_t *)descriptor; + printf( + "inum:%d, altsetting:%d, numep:%d, iclass:%d, isubclass:%d, " + "iprotcol:%d, iface:%d\n", + d->inum, d->altsetting, d->numep, d->iclass, d->isubclass, + d->iprotocol, d->iface); + interface = d->inum; + class = d->iclass; + } break; + case DESC_TYPE_ENDPOINT: { + const endpoint_descriptor_t *d = + (const endpoint_descriptor_t *)descriptor; + printf("\t\t\tepaddr:0x%02x, attr:%d, size:%d, interval:%d\n", + d->epaddr, d->attr, d->max_size[0] | (d->max_size[1] << 8), + d->interval); + + if ((class == CLASS_HID || class == CLASS_HUB) && + d->attr == EP_ATTR_INTERRUPT) { + volatile endpoint_t *ep = NULL; + for (int ep_pool_idx = 0; ep_pool_idx < PIO_USB_EP_POOL_CNT; + ep_pool_idx++) { + if (pio_usb_ep_pool[ep_pool_idx].size == 0) { + ep = &pio_usb_ep_pool[ep_pool_idx]; + device->endpoint_id[ep_id_idx] = ep_pool_idx + 1; + ep_id_idx++; + break; + } + } + + if (ep != NULL) { + ep->interval = d->interval; + ep->interval_counter = 0; + ep->size = d->max_size[0] | (d->max_size[1] << 8); + ep->attr = d->attr | EP_ATTR_ENUMERATING; + ep->ep_num = d->epaddr; + + ep->root_idx = device->root - pio_usb_root_port; + ep->dev_addr = device->address; + ep->need_pre = !device->is_root && !device->is_fullspeed; + ep->is_tx = (d->epaddr & 0x80) ? false : true; + } else { + printf("No empty EP\n"); + } + } + } break; + case DESC_TYPE_HID: { + const hid_descriptor_t *d = (const hid_descriptor_t *)descriptor; + printf( + "\tbcdHID:%x.%x, country:%d, desc num:%d, desc_type:%d, " + "desc_size:%d\n", + d->bcd_hid[1], d->bcd_hid[0], d->contry_code, d->num_desc, + d->desc_type, d->desc_len[0] | (d->desc_len[1] << 8)); + + usb_setup_packet_t set_hid_idle_request = SET_HID_IDLE_REQ_DEFAULT; + set_hid_idle_request.value_lsb = interface; + set_hid_idle_request.value_msb = 0; + control_out_protocol(device, (uint8_t *)&set_hid_idle_request, + sizeof(set_hid_idle_request), NULL, 0); + + usb_setup_packet_t get_hid_report_descrpitor_request = + GET_HID_REPORT_DESCRIPTOR_DEFAULT; + get_hid_report_descrpitor_request.index_lsb = interface; + get_hid_report_descrpitor_request.index_msb = 0; + get_hid_report_descrpitor_request.length_lsb = d->desc_len[0]; + get_hid_report_descrpitor_request.length_msb = d->desc_len[1]; + uint16_t desc_len = d->desc_len[0] | (d->desc_len[1] << 8); + control_in_protocol( + device, (uint8_t *)&get_hid_report_descrpitor_request, + sizeof(get_hid_report_descrpitor_request), rx_buffer, desc_len); + printf("\t\tReport descriptor:"); + for (int i = 0; i < desc_len; i++) { + printf("%02x ", device->control_pipe.rx_buffer[i]); + } + printf("\n"); + stdio_flush(); + + } break; + default: + break; + } + + configuration_descrptor_length -= descriptor[0]; + descriptor += descriptor[0]; + } + + for (int epidx = 0; epidx < PIO_USB_DEV_EP_CNT; epidx++) { + endpoint_t *ep = pio_usb_get_endpoint(device, epidx); + if (ep == NULL) { + break; + } + ep->attr &= ~EP_ATTR_ENUMERATING; + + // prepare transfer + if (ep->ep_num & EP_IN) { + pio_usb_ll_transfer_start(ep, ep->buffer, ep->size); + } + } + + return res; +} + +static void device_disconnect(usb_device_t *device) { + printf("Disconnect device %d\n", device->address); + for (int port = 0; port < PIO_USB_HUB_PORT_CNT; port++) { + if (device->child_devices[port] != 0) { + device_disconnect(&pio_usb_device[device->child_devices[port]]); + } + } + + for (int ep_idx = 0; ep_idx < PIO_USB_DEV_EP_CNT; ep_idx++) { + endpoint_t *ep = pio_usb_get_endpoint(device, ep_idx); + if (ep == NULL) { + break; + } + memset(ep, 0, sizeof(*ep)); + } + + if (device->address == 0 && device->root != NULL) { + device->root->addr0_exists = false; + } + + memset(device, 0, sizeof(*device)); +} + +static int device_pool_vacant(void) { + for (int idx = 0; idx < PIO_USB_DEVICE_CNT; idx++) { + if (!pio_usb_device[idx].connected) { + return idx; + } + } + + return -1; +} + +static int assign_new_device_to_port(usb_device_t *hub_device, uint8_t port, bool is_ls) { + int idx = device_pool_vacant(); + if (idx >= 0) { + hub_device->child_devices[port] = idx; + pio_usb_device[idx].parent_device = hub_device; + pio_usb_device[idx].parent_port = port; + pio_usb_device[idx].root = hub_device->root; + pio_usb_device[idx].connected = true; + pio_usb_device[idx].is_fullspeed = !is_ls; + pio_usb_device[idx].event = EVENT_CONNECT; + printf("Assign device %d to %d-%d\n", idx, hub_device->address, port); + + endpoint_descriptor_t ep0_desc = { + sizeof(endpoint_descriptor_t), DESC_TYPE_ENDPOINT, 0x00, 0x00, { 0x08, 0x00 }, 0x00 + }; + pio_usb_host_endpoint_open(hub_device->root - pio_usb_root_port, 0x00, + (uint8_t const *)&ep0_desc, is_ls); + + return 0; + } + + printf("Failed to assign device\n"); + + return -1; +} + +static void __no_inline_not_in_flash_func(process_hub_event)( + usb_device_t *device) { + volatile endpoint_t *ep = pio_usb_get_endpoint(device, 0); + uint8_t bitmap = ep->buffer[0]; + for (int bit = 1; bit < 8; bit++) { + if (!(bitmap & (1 << bit))) { + continue; + } + uint8_t port = bit - 1; + hub_port_status_t status; + int res = get_hub_port_status(device, port, &status); + if (res != 0) { + printf("Failed to get port%d-%d status\n", device->address, port); + continue; + } + printf("port%d-%d status:%d %d\n", device->address, port, + status.port_change, status.port_status); + + if (status.port_change & HUB_CHANGE_PORT_CONNECTION) { + if (status.port_status & HUB_STAT_PORT_CONNECTION) { + printf("new device on port %d, reset port\n", port); + if (device->child_devices[port] != 0) { + printf("device is already assigned. disconnect previous\n"); + device_disconnect(&pio_usb_device[device->child_devices[port]]); + } + + if (device->root->addr0_exists) { + printf("Address 0 already exists\n"); + continue; + } + + if (device_pool_vacant() >= 0) { + set_hub_feature(device, port, HUB_SET_PORT_RESET); + device->root->addr0_exists = true; + } else { + printf("No vacant in device pool\n"); + } + } else { + printf("device removed from port %d\n", port); + if (device->child_devices[port] != 0) { + device_disconnect(&pio_usb_device[device->child_devices[port]]); + } + } + clear_hub_feature(device, port, HUB_CLR_PORT_CONNECTION); + } else if (status.port_change & HUB_CHANGE_PORT_RESET) { + printf("reset port %d complete\n", port); + res = clear_hub_feature(device, port, HUB_CLR_PORT_RESET); + if (res == 0) { + assign_new_device_to_port(device, port, + status.port_status & HUB_STAT_PORT_LOWSPEED); + } + } else if (status.port_change & HUB_CHANGE_PORT_ENABLE) { + clear_hub_feature(device, port, HUB_CLR_PORT_ENABLE); + } + } + + device->event = EVENT_NONE; +} + +void __no_inline_not_in_flash_func(pio_usb_host_task)(void) { + for (int root_idx = 0; root_idx < PIO_USB_ROOT_PORT_CNT; root_idx++) { + if (pio_usb_root_port[root_idx].event == EVENT_CONNECT) { + printf("Root %d connected\n", root_idx); + int dev_idx = device_pool_vacant(); + if (dev_idx >= 0) { + on_device_connect(&pio_port[0], &pio_usb_root_port[root_idx], dev_idx); + pio_usb_root_port[root_idx].addr0_exists = true; + } + pio_usb_root_port[root_idx].event = EVENT_NONE; + } else if (pio_usb_root_port[root_idx].event == EVENT_DISCONNECT) { + printf("Root %d disconnected\n", root_idx); + pio_usb_host_close_device( + root_idx, pio_usb_root_port[root_idx].root_device->address); + pio_usb_root_port[root_idx].root_device->connected = false; + pio_usb_root_port[root_idx].root_device->event = EVENT_DISCONNECT; + pio_usb_root_port[root_idx].root_device = NULL; + pio_usb_root_port[root_idx].event = EVENT_NONE; + } + } + + for (int idx = 0; idx < PIO_USB_DEVICE_CNT; idx++) { + usb_device_t *device = &pio_usb_device[idx]; + + if (device->event == EVENT_CONNECT) { + device->event = EVENT_NONE; + printf("Device %d Connected\n", idx); + int res = enumerate_device(device, idx + 1); + if (res == 0) { + device->enumerated = true; + device->root->addr0_exists = false; + if (device->device_class == CLASS_HUB) { + res = initialize_hub(device); + } + } + + if (res != 0) { + printf("Enumeration failed(%d)\n", res); + // retry + if (device->is_root) { + device->root->event = EVENT_DISCONNECT; + } else { + set_hub_feature(device->parent_device, device->parent_port, + HUB_SET_PORT_RESET); + device_disconnect(device); + } + } + } else if (device->event == EVENT_DISCONNECT) { + device->event = EVENT_NONE; + printf("Disconnect\n"); + device_disconnect(device); + } else if (device->event == EVENT_HUB_PORT_CHANGE) { + process_hub_event(device); + } + } + + if (cancel_timer_flag) { + int_stat = save_and_disable_interrupts(); + stop_timer(); + if (pio_usb_root_port->root_device != NULL) { + device_disconnect(pio_usb_root_port->root_device); + } + cancel_timer_flag = false; + } + + if (start_timer_flag) { + start_timer(_alarm_pool); + restore_interrupts(int_stat); + start_timer_flag = false; + } +} + +static void __no_inline_not_in_flash_func(handle_endpoint_irq)( + root_port_t *root, uint32_t flag, volatile uint32_t *ep_reg) { + (void)root; + const uint32_t ep_all = *ep_reg; + + for (uint8_t ep_idx = 0; ep_idx < PIO_USB_EP_POOL_CNT; ep_idx++) { + if (ep_all & (1u << ep_idx)) { + endpoint_t *ep = PIO_USB_ENDPOINT(ep_idx); + usb_device_t *device = NULL; + + // find device this endpoint belongs to + for (int idx = 0; idx < PIO_USB_DEVICE_CNT; idx++) { + usb_device_t *dev = &pio_usb_device[idx]; + if (dev->connected && (ep->dev_addr == dev->address)) { + device = dev; + break; + } + } + + if (device) { + // control endpoint is either 0x00 or 0x80 + if ((ep->ep_num & 0x7f) == 0) { + control_pipe_t *pipe = &device->control_pipe; + + if (flag != PIO_USB_INTS_ENDPOINT_COMPLETE_BITS) { + pipe->stage = STAGE_SETUP; + pipe->operation = CONTROL_ERROR; + } else { + ep->data_id = 1; // both data and status have DATA1 + if (pipe->stage == STAGE_SETUP) { + if (pipe->operation == CONTROL_IN) { + pipe->stage = STAGE_IN; + ep->ep_num = 0x80; + ep->is_tx = false; + pio_usb_ll_transfer_start(ep, + (uint8_t *)(uintptr_t)pipe->rx_buffer, + pipe->request_length); + } else if (pipe->operation == CONTROL_OUT) { + if (pipe->out_data_packet.tx_address != NULL) { + pipe->stage = STAGE_OUT; + ep->ep_num = 0x00; + ep->is_tx = true; + pio_usb_ll_transfer_start(ep, + pipe->out_data_packet.tx_address, + pipe->out_data_packet.tx_length); + } else { + pipe->stage = STAGE_STATUS; + ep->ep_num = 0x80; + ep->is_tx = false; + pio_usb_ll_transfer_start(ep, NULL, 0); + } + } + } else if (pipe->stage == STAGE_IN) { + pipe->stage = STAGE_STATUS; + ep->ep_num = 0x00; + ep->is_tx = true; + pio_usb_ll_transfer_start(ep, NULL, 0); + } else if (pipe->stage == STAGE_OUT) { + pipe->stage = STAGE_STATUS; + ep->ep_num = 0x80; + ep->is_tx = false; + pio_usb_ll_transfer_start(ep, NULL, 0); + } else if (pipe->stage == STAGE_STATUS) { + pipe->stage = STAGE_SETUP; + pipe->operation = CONTROL_COMPLETE; + } + } + } else if (device->device_class == CLASS_HUB && (ep->ep_num & EP_IN)) { + // hub interrupt endpoint + device->event = EVENT_HUB_PORT_CHANGE; + } + } + } + } + + // clear all + (*ep_reg) &= ~ep_all; +} + +// IRQ Handler +static void __no_inline_not_in_flash_func(__pio_usb_host_irq_handler)(uint8_t root_id) { + root_port_t *root = PIO_USB_ROOT_PORT(root_id); + uint32_t const ints = root->ints; + + if (ints & PIO_USB_INTS_CONNECT_BITS) { + root->event = EVENT_CONNECT; + } + + if (ints & PIO_USB_INTS_DISCONNECT_BITS) { + root->event = EVENT_DISCONNECT; + } + + if (ints & PIO_USB_INTS_ENDPOINT_COMPLETE_BITS) { + handle_endpoint_irq(root, PIO_USB_INTS_ENDPOINT_COMPLETE_BITS, + &root->ep_complete); + } + + if (ints & PIO_USB_INTS_ENDPOINT_STALLED_BITS) { + handle_endpoint_irq(root, PIO_USB_INTS_ENDPOINT_STALLED_BITS, + &root->ep_stalled); + } + + if (ints & PIO_USB_INTS_ENDPOINT_ERROR_BITS) { + handle_endpoint_irq(root, PIO_USB_INTS_ENDPOINT_ERROR_BITS, + &root->ep_error); + } + + // clear all + root->ints &= ~ints; +} + +// weak alias to __pio_usb_host_irq_handler +void pio_usb_host_irq_handler(uint8_t root_id) __attribute__ ((weak, alias("__pio_usb_host_irq_handler"))); + +#pragma GCC pop_options diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_ll.h b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_ll.h new file mode 100644 index 00000000..3b4ac6d6 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/pio_usb_ll.h @@ -0,0 +1,211 @@ +/** + * Copyright (c) 2021 sekigon-gonnoc + * Ha Thach (thach@tinyusb.org) + */ + +#pragma once + +#include "hardware/pio.h" +#include "pio_usb_configuration.h" +#include "usb_definitions.h" +#include + +enum { + PIO_USB_INTS_CONNECT_POS = 0, + PIO_USB_INTS_DISCONNECT_POS, + PIO_USB_INTS_RESET_END_POS, + PIO_USB_INTS_SETUP_REQ_POS, + PIO_USB_INTS_SOF_POS, + + PIO_USB_INTS_ENDPOINT_COMPLETE_POS, + PIO_USB_INTS_ENDPOINT_ERROR_POS, + PIO_USB_INTS_ENDPOINT_STALLED_POS, + PIO_USB_INTS_ENDPOINT_CONTINUE_POS, +}; + +#define PIO_USB_INTS_CONNECT_BITS (1u << PIO_USB_INTS_CONNECT_POS) +#define PIO_USB_INTS_DISCONNECT_BITS (1u << PIO_USB_INTS_DISCONNECT_POS) +#define PIO_USB_INTS_RESET_END_BITS (1u << PIO_USB_INTS_RESET_END_POS) +#define PIO_USB_INTS_SETUP_REQ_BITS (1u << PIO_USB_INTS_SETUP_REQ_POS) + +#define PIO_USB_INTS_SOF_BITS (1u << PIO_USB_INTS_SOF_POS) + +#define PIO_USB_INTS_ENDPOINT_COMPLETE_BITS \ + (1u << PIO_USB_INTS_ENDPOINT_COMPLETE_POS) +#define PIO_USB_INTS_ENDPOINT_ERROR_BITS (1u << PIO_USB_INTS_ENDPOINT_ERROR_POS) +#define PIO_USB_INTS_ENDPOINT_STALLED_BITS \ + (1u << PIO_USB_INTS_ENDPOINT_STALLED_POS) +#define PIO_USB_INTS_ENDPOINT_CONTINUE_BITS \ + (1u << PIO_USB_INTS_ENDPOINT_CONTINUE_POS) + +typedef enum { + PORT_PIN_SE0 = 0b00, + PORT_PIN_FS_IDLE = 0b01, + PORT_PIN_LS_IDLE = 0b10, + PORT_PIN_SE1 = 0b11, +} port_pin_status_t; + +typedef struct { + uint16_t div_int; + uint8_t div_frac; +} pio_clk_div_t; + +typedef struct { + PIO pio_usb_tx; // could not set to volatile + uint sm_tx; + uint offset_tx; + uint tx_ch; + + PIO pio_usb_rx; // could not set to volatile + uint sm_rx; + uint offset_rx; + uint sm_eop; + uint offset_eop; + uint tx_reset_instr; + uint tx_start_instr; + uint rx_reset_instr; + uint rx_reset_instr2; + uint device_rx_irq_num; + + int8_t debug_pin_rx; + int8_t debug_pin_eop; + + const pio_program_t *fs_tx_program; + const pio_program_t *fs_tx_pre_program; + const pio_program_t *ls_tx_program; + + pio_clk_div_t clk_div_fs_tx; + pio_clk_div_t clk_div_fs_rx; + pio_clk_div_t clk_div_ls_tx; + pio_clk_div_t clk_div_ls_rx; + + bool need_pre; + + uint8_t usb_rx_buffer[128]; +} pio_port_t; + +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ + +enum { + PIO_USB_MODE_INVALID = 0, + PIO_USB_MODE_DEVICE, + PIO_USB_MODE_HOST, +}; + +extern usb_device_t pio_usb_device[PIO_USB_DEVICE_CNT]; + +extern root_port_t pio_usb_root_port[PIO_USB_ROOT_PORT_CNT]; +#define PIO_USB_ROOT_PORT(_idx) (pio_usb_root_port + (_idx)) + +extern endpoint_t pio_usb_ep_pool[PIO_USB_EP_POOL_CNT]; +#define PIO_USB_ENDPOINT(_idx) (pio_usb_ep_pool + (_idx)) + +extern pio_port_t pio_port[1]; +#define PIO_USB_PIO_PORT(_idx) (pio_port + (_idx)) + +//--------------------------------------------------------------------+ +// Bus functions +//--------------------------------------------------------------------+ + +#define IRQ_TX_EOP_MASK (1 << IRQ_TX_EOP) +#define IRQ_TX_ALL_MASK (IRQ_TX_EOP_MASK) +#define IRQ_RX_COMP_MASK (1 << IRQ_RX_EOP) +#define IRQ_RX_ALL_MASK \ + ((1 << IRQ_RX_EOP) | (1 << IRQ_RX_BS_ERR) | (1 << IRQ_RX_START) | \ + (1 << DECODER_TRIGGER)) + +#define SM_SET_CLKDIV(pio, sm, div) \ + pio_sm_set_clkdiv_int_frac(pio, sm, div.div_int, div.div_frac) +#define SM_SET_CLKDIV_MAXSPEED(pio, sm) \ + pio_sm_set_clkdiv_int_frac(pio, sm, 1, 0) + +void pio_usb_bus_init(pio_port_t *pp, const pio_usb_configuration_t *c, + root_port_t *root); + +void pio_usb_bus_start_receive(const pio_port_t *pp); +void pio_usb_bus_prepare_receive(const pio_port_t *pp); +int pio_usb_bus_receive_packet_and_handshake(pio_port_t *pp, uint8_t handshake); +void pio_usb_bus_usb_transfer(const pio_port_t *pp, uint8_t *data, + uint16_t len); + +uint8_t pio_usb_bus_wait_handshake(pio_port_t *pp); +void pio_usb_bus_send_handshake(const pio_port_t *pp, uint8_t pid); +void pio_usb_bus_send_token(const pio_port_t *pp, uint8_t token, uint8_t addr, + uint8_t ep_num); + +static __always_inline port_pin_status_t +pio_usb_bus_get_line_state(root_port_t *root) { + uint8_t dp = gpio_get(root->pin_dp) ? 0 : 1; + uint8_t dm = gpio_get(root->pin_dm) ? 0 : 1; + + return (dm << 1) | dp; +} + +//--------------------------------------------------------------------+ +// Low Level functions +//--------------------------------------------------------------------+ + +void pio_usb_ll_configure_endpoint(endpoint_t *ep, + uint8_t const *desc_endpoint); +bool pio_usb_ll_transfer_start(endpoint_t *ep, uint8_t *buffer, + uint16_t buflen); +bool pio_usb_ll_transfer_continue(endpoint_t *ep, uint16_t xferred_bytes); +void pio_usb_ll_transfer_complete(endpoint_t *ep, uint32_t flag); + +static inline __force_inline uint16_t +pio_usb_ll_get_transaction_len(endpoint_t *ep) { + uint16_t remaining = ep->total_len - ep->actual_len; + return (remaining < ep->size) ? remaining : ep->size; +} + +enum { + PIO_USB_TX_ENCODED_DATA_SE0 = 0, + PIO_USB_TX_ENCODED_DATA_K = 1, + PIO_USB_TX_ENCODED_DATA_COMP = 2, + PIO_USB_TX_ENCODED_DATA_J = 3, +}; +uint8_t pio_usb_ll_encode_tx_data(uint8_t const *buffer, uint8_t buffer_len, + uint8_t *encoded_data); + +//-------------------------------------------------------------------- +// Host Controller functions +//-------------------------------------------------------------------- + +// Host IRQ Handler +void pio_usb_host_irq_handler(uint8_t root_idx); + +void pio_usb_host_port_reset_start(uint8_t root_idx); +void pio_usb_host_port_reset_end(uint8_t root_idx); + +void pio_usb_host_close_device(uint8_t root_idx, uint8_t device_address); + +bool pio_usb_host_endpoint_open(uint8_t root_idx, uint8_t device_address, + uint8_t const *desc_endpoint, bool need_pre); +bool pio_usb_host_send_setup(uint8_t root_idx, uint8_t device_address, + uint8_t const setup_packet[8]); +bool pio_usb_host_endpoint_transfer(uint8_t root_idx, uint8_t device_address, + uint8_t ep_address, uint8_t *buffer, + uint16_t buflen); +bool pio_usb_host_endpoint_abort_transfer(uint8_t root_idx, uint8_t device_address, + uint8_t ep_address); + +//-------------------------------------------------------------------- +// Device Controller functions +//-------------------------------------------------------------------- + +// Device IRQ Handler +void pio_usb_device_irq_handler(uint8_t root_idx); + +void pio_usb_device_set_address(uint8_t dev_addr); +bool pio_usb_device_endpoint_open(uint8_t const *desc_endpoint); +bool pio_usb_device_transfer(uint8_t ep_address, uint8_t *buffer, + uint16_t buflen); + +static inline __force_inline endpoint_t * +pio_usb_device_get_endpoint_by_address(uint8_t ep_address) { + // index = 2*num + dir e.g out1, in1, out2, in2 + uint8_t const ep_idx = ((ep_address & 0x7f) << 1) | (ep_address >> 7); + return PIO_USB_ENDPOINT(ep_idx); +} diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_crc.c b/rescue/firmware/lib/Pico-PIO-USB/src/usb_crc.c new file mode 100644 index 00000000..1d58d17f --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_crc.c @@ -0,0 +1,63 @@ + +#include "usb_crc.h" + +const uint8_t __not_in_flash("crc5_tbl") crc5_tbl[32] = { + 0x00, 0x0b, 0x16, 0x1d, 0x05, 0x0e, 0x13, 0x18, 0x0a, 0x01, + 0x1c, 0x17, 0x0f, 0x04, 0x19, 0x12, 0x14, 0x1f, 0x02, 0x09, + 0x11, 0x1a, 0x07, 0x0c, 0x1e, 0x15, 0x08, 0x03, 0x1b, 0x10, + 0x0d, 0x06, +}; +uint8_t __not_in_flash_func(calc_usb_crc5)(uint16_t data) { + data = data ^ 0x1f; + + const uint8_t lsb = (data >> 1) & 0x1f; + const uint8_t msb = (data >> 6) & 0x1f; + + uint8_t crc = (data & 1) ? 0x14 : 0x00; + crc = crc5_tbl[(lsb ^ crc)]; + crc = crc5_tbl[(msb ^ crc)]; + + return crc ^ 0x1f; +} + +// Place to RAM +const uint16_t __not_in_flash("crc_tbl") crc16_tbl[256] = { + 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, + 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, + 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, + 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, + 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, + 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, + 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, + 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, + 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, + 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, + 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, + 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, + 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, + 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, + 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, + 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, + 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, + 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, + 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, + 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, + 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, + 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, + 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, + 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, + 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, + 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, + 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, + 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, + 0x4100, 0x81c1, 0x8081, 0x4040}; + +uint16_t calc_usb_crc16(const uint8_t *data, uint16_t len) { + uint16_t crc = 0xffff; + + for (int idx = 0; idx < len; idx++) { + crc = (crc >> 8) ^ crc16_tbl[(crc ^ data[idx]) & 0xff]; + } + + return crc ^ 0xffff; +} \ No newline at end of file diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_crc.h b/rescue/firmware/lib/Pico-PIO-USB/src/usb_crc.h new file mode 100644 index 00000000..3c6831e3 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_crc.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include "pico/stdlib.h" + +// Calc CRC5-USB of 11bit data +uint8_t calc_usb_crc5(uint16_t data); +// Calc CRC16-USB of array +uint16_t calc_usb_crc16(const uint8_t *data, uint16_t len); + +extern const uint16_t crc16_tbl[256]; +static inline uint16_t __time_critical_func(update_usb_crc16)(uint16_t crc, uint8_t data) { + crc = (crc >> 8) ^ crc16_tbl[(crc ^ data) & 0xff]; + return crc; +} \ No newline at end of file diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_definitions.h b/rescue/firmware/lib/Pico-PIO-USB/src/usb_definitions.h new file mode 100644 index 00000000..029c0dbb --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_definitions.h @@ -0,0 +1,346 @@ + +#pragma once + +#include + +#include "pio_usb_configuration.h" + +typedef enum { + CONTROL_NONE, + CONTROL_IN, + CONTROL_OUT, + CONTROL_COMPLETE, + CONTROL_ERROR, +} control_transfer_operation_t; + +typedef enum { + EP_IN = 0x80, + EP_OUT = 0x00, +} ep_type_t; + +typedef enum { + STAGE_SETUP, + STAGE_DATA, + STAGE_IN, + STAGE_OUT, + STAGE_STATUS, + STAGE_COMPLETE, + STAGE_ERROR +} setup_transfer_stage_t; + +typedef enum { + STAGE_IDLE, + STAGE_DEVICE, + STAGE_CONFIG, + STAGE_CONFIG2, + STAGE_INTERFACE, + STAGE_ENDPOINT +} usb_enumeration_stage_t; + +typedef struct { + uint8_t *tx_address; + uint8_t tx_length; +} packet_info_t; + +typedef struct { + volatile uint8_t data_in_num; + volatile uint16_t buffer_idx; + volatile uint8_t *rx_buffer; + volatile packet_info_t setup_packet; + volatile packet_info_t out_data_packet; + volatile int16_t request_length; + volatile control_transfer_operation_t operation; + volatile setup_transfer_stage_t stage; +} control_pipe_t; + +typedef struct { + volatile uint8_t root_idx; + volatile uint8_t dev_addr; + bool need_pre; + bool is_tx; // Host out or Device in + + volatile uint8_t ep_num; + volatile bool new_data_flag; + volatile uint16_t size; + + volatile uint8_t attr; + volatile uint8_t interval; + volatile uint8_t interval_counter; + volatile uint8_t data_id; // data0 or data1 + + volatile bool stalled; + volatile bool has_transfer; + volatile bool transfer_started; + volatile bool transfer_aborted; + + uint8_t buffer[(64 + 4) * 2 * 7 / 6 + 2]; + uint8_t encoded_data_len; + uint8_t *app_buf; + uint16_t total_len; + uint16_t actual_len; +} endpoint_t; + +typedef enum { + EVENT_NONE, + EVENT_CONNECT, + EVENT_DISCONNECT, + EVENT_HUB_PORT_CHANGE, +} usb_device_event_t; + +typedef struct struct_usb_device_t usb_device_t; +typedef struct struct_root_port_t { + volatile bool initialized; + volatile bool addr0_exists; + volatile uint8_t pin_dp; + volatile uint8_t pin_dm; + volatile usb_device_event_t event; + usb_device_t *root_device; + PIO_USB_PINOUT pinout; + + volatile bool is_fullspeed; + volatile bool connected; + volatile bool suspended; + uint8_t mode; + + // register interface + volatile uint32_t ints; // interrupt status + volatile uint32_t ep_complete; + volatile uint32_t ep_error; + volatile uint32_t ep_stalled; + volatile uint32_t ep_continue; + + // device only + uint8_t dev_addr; + uint8_t *setup_packet; +} root_port_t; + +struct struct_usb_device_t { + volatile bool connected; + volatile bool enumerated; + volatile usb_device_event_t event; + volatile uint8_t address; + volatile uint16_t vid; + volatile uint16_t pid; + volatile uint8_t device_class; + volatile bool is_fullspeed; + volatile bool is_root; + control_pipe_t control_pipe; + uint8_t endpoint_id[PIO_USB_DEV_EP_CNT]; + uint8_t child_devices[PIO_USB_HUB_PORT_CNT]; + struct struct_usb_device_t *parent_device; + uint8_t parent_port; + root_port_t *root; +}; + +enum { + USB_SYNC = 0x80, + USB_PID_OUT = 0xe1, + USB_PID_IN = 0x69, + USB_PID_SOF = 0xa5, + USB_PID_SETUP = 0x2d, + USB_PID_DATA0 = 0xc3, + USB_PID_DATA1 = 0x4b, + USB_PID_ACK = 0xd2, + USB_PID_NAK = 0x5a, + USB_PID_STALL = 0x1e, + USB_PID_PRE = 0x3c, + USB_CRC16_PLACE = 0, +}; + +enum { + DESC_TYPE_DEVICE = 0x01, + DESC_TYPE_CONFIG = 0x02, + DESC_TYPE_STRING = 0x03, + DESC_TYPE_INTERFACE = 0x04, + DESC_TYPE_ENDPOINT = 0x05, + DESC_TYPE_HID = 0x21, + DESC_TYPE_HID_REPORT = 0x22, +}; + +enum { + CLASS_HID = 0x03, + CLASS_HUB = 0x09, +}; + +enum { + EP_ATTR_CONTROL = 0x00, + EP_ATTR_ISOCHRONOUS = 0x01, + EP_ATTR_BULK = 0x02, + EP_ATTR_INTERRUPT = 0x03, + EP_ATTR_ENUMERATING = 0x80 +}; + +typedef struct { + // uint8_t sync; + // uint8_t pid; + uint8_t request_type; + uint8_t request; + uint8_t value_lsb; + uint8_t value_msb; + uint8_t index_lsb; + uint8_t index_msb; + uint8_t length_lsb; + uint8_t length_msb; + // uint8_t crc16[2]; +} usb_setup_packet_t; + +typedef struct { + uint8_t length; + uint8_t type; + uint8_t bcd_usb[2]; + uint8_t device_class; + uint8_t subclass; + uint8_t protocol; + uint8_t max_packet_size; + uint8_t vid[2]; + uint8_t pid[2]; + uint8_t bcd_device[2]; + uint8_t manufacture; + uint8_t product; + uint8_t serial; + uint8_t num_configu; +} device_descriptor_t; + +typedef struct { + uint8_t length; + uint8_t type; + uint8_t string[62]; +} __attribute__((aligned(2))) string_descriptor_t; + +typedef struct { + uint8_t length; + uint8_t type; + uint8_t inum; + uint8_t altsetting; + uint8_t numep; + uint8_t iclass; + uint8_t isubclass; + uint8_t iprotocol; + uint8_t iface; +} interface_descriptor_t; + +typedef struct { + uint8_t length; + uint8_t type; + uint8_t epaddr; + uint8_t attr; + uint8_t max_size[2]; + uint8_t interval; +} endpoint_descriptor_t; + +typedef struct { + uint8_t length; + uint8_t type; + uint8_t bcd_hid[2]; + uint8_t contry_code; + uint8_t num_desc; + uint8_t desc_type; + uint8_t desc_len[2]; +} hid_descriptor_t; + +typedef struct configuration_descriptor_tag { + uint8_t length; + uint8_t type; + uint8_t total_length_lsb; + uint8_t total_length_msb; + uint8_t num_interfaces; + uint8_t configuration_value; + uint8_t configuration; + uint8_t attributes; + uint8_t max_power; +} configuration_descriptor_t; + +typedef struct { + uint8_t lenght; + uint8_t type; + uint8_t port_num; + uint8_t chara_lsb; + uint8_t chara_msb; + uint8_t pow_on_time; + uint8_t current; + uint8_t removable; +} hub_descriptor_t; + +typedef struct { + uint16_t port_status; + uint16_t port_change; +} hub_port_status_t; + +enum { + HUB_SET_PORT_RESET = 4, + HUB_SET_PORT_POWER = 8, + HUB_CLR_PORT_CONNECTION = 16, + HUB_CLR_PORT_ENABLE = 17, + HUB_CLR_PORT_SUSPEND = 18, + HUB_CLR_PORT_RESET = 20, +}; + +enum { + HUB_STAT_PORT_CONNECTION = (1 << 0), + HUB_STAT_PORT_ENABLE = (1 << 1), + HUB_STAT_PORT_SUSPEND = (1 << 2), + HUB_STAT_PORT_OC = (1 << 3), + HUB_STAT_PORT_RESET = (1 << 4), + HUB_STAT_PORT_POWER = (1 << 8), + HUB_STAT_PORT_LOWSPEED = (1 << 9), +}; + +enum { + HUB_CHANGE_PORT_CONNECTION = (1 << 0), + HUB_CHANGE_PORT_ENABLE = (1 << 1), + HUB_CHANGE_PORT_SUSPEND = (1 << 2), + HUB_CHANGE_PORT_OC = (1 << 3), + HUB_CHANGE_PORT_RESET = (1 << 4), +}; + +enum { + USB_REQ_DIR_IN = 0x80, + USB_REQ_DIR_OUT = 0x00, + USB_REQ_TYP_STANDARD = 0x00, + USB_REQ_TYP_CLASS = 0x20, + USB_REQ_TYP_VENDOR = 0x40, + USB_REQ_REC_DEVICE = 0x00, + USB_REQ_REC_IFACE = 0x01, + USB_REQ_REC_EP = 0x02, + USB_REQ_REC_OTHER = 0x03, +}; + +#define GET_DEVICE_DESCRIPTOR_REQ_DEFAULT \ + { USB_REQ_DIR_IN, 0x06, 0, 0x01, 0, 0, 0x12, 0 } +#define GET_CONFIGURATION_DESCRIPTOR_REQ_DEFAULT \ + { USB_REQ_DIR_IN, 0x06, 0, 0x02, 0, 0, 0x09, 0 } +#define SET_CONFIGURATION_REQ_DEFAULT \ + { USB_REQ_DIR_OUT, 0x09, 0, 0, 0, 0, 0, 0 } +#define SET_ADDRESS_REQ_DEFAULT \ + { USB_REQ_DIR_OUT, 0x5, 0x02, 0, 0, 0, 0, 0 } +#define SET_HID_IDLE_REQ_DEFAULT \ + { USB_REQ_TYP_CLASS | USB_REQ_REC_IFACE, 0x0A, 0, 0, 0, 0, 0, 0 } +#define GET_HID_REPORT_DESCRIPTOR_DEFAULT \ + { USB_REQ_DIR_IN | USB_REQ_REC_IFACE, 0x06, 0, 0x22, 0, 0, 0xff, 0 } +#define GET_HUB_DESCRPTOR_REQUEST \ + { \ + USB_REQ_DIR_IN | USB_REQ_TYP_CLASS | USB_REQ_REC_DEVICE, 0x06, 0, 0x29, 0, \ + 0, 8, 0 \ + } +#define GET_HUB_PORT_STATUS_REQUEST \ + { \ + USB_REQ_DIR_IN | USB_REQ_TYP_CLASS | USB_REQ_REC_OTHER, 0, 0, 0, 0, 0, 4, \ + 0 \ + } +#define SET_HUB_FEATURE_REQUEST \ + { \ + USB_REQ_DIR_OUT | USB_REQ_TYP_CLASS | USB_REQ_REC_OTHER, 0x03, 0, 0, 0, 0, \ + 0, 0 \ + } +#define CLEAR_HUB_FEATURE_REQUEST \ + { \ + USB_REQ_DIR_OUT | USB_REQ_TYP_CLASS | USB_REQ_REC_OTHER, 0x01, 0, 0, 0, 0, \ + 0, 0 \ + } + +typedef struct { + const uint8_t *device; + const uint8_t *config; + const uint8_t **hid_report; + const string_descriptor_t *string; +} usb_descriptor_buffers_t; diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_rx.pio b/rescue/firmware/lib/Pico-PIO-USB/src/usb_rx.pio new file mode 100644 index 00000000..76e6fbe4 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_rx.pio @@ -0,0 +1,235 @@ + +; Copyright (c) 2021-2024 sekigon-gonnoc + +.define public IRQ_RX_BS_ERR 1 ; bit stuffinc error +.define public IRQ_RX_EOP 2 ; eop detect flag +.define public IRQ_RX_START 3 ; packet start flag +.define public DECODER_TRIGGER 4 + +.define BIT_REPEAT_COUNT 6 ; bit repeat counter + +.define db0 0 +.define db1 1 + +; USB signal edge and eop detector +; 17 instruction +; FS(12M) LS(1.5M) +; Run at 96MHz 12MHz +; jmp_pin d- d+ +; in_pin d+ d- +; both d+/d- pin should be input invert overrideed +.program usb_edge_detector +eop: + irq wait IRQ_RX_EOP +start: + jmp pin start ; Wait fall edge + irq IRQ_RX_START [1] + +.wrap_target +pin_still_low: + irq DECODER_TRIGGER [1] ; Trigger NRZI decoder + +; Resync on rising edge +pin_low: + jmp pin pin_went_high +pin_went_low: + jmp pin pin_went_high + jmp pin pin_went_high + jmp pin pin_went_high + jmp pin pin_went_high + jmp pin pin_went_high +.wrap + +pin_still_high: + mov x, isr [2] + jmp x-- eop ; Jump to eop if jmp_pin and in_pin are high because both inputs are inverted +; Jump to here on rising edge +pin_went_high: + mov isr, null + in pins, 1 ; Capture the pin to check eop. + irq DECODER_TRIGGER ; Trigger NRZI decoder + jmp pin pin_still_high + jmp pin_went_low ; To adjust interval of decoder trigger, jump to pin_went_low (not pin_low) + +.program usb_edge_detector_debug +.side_set 1 +eop: + irq wait IRQ_RX_EOP side db0 +start: + jmp pin start side db1 ; Wait fall edge + irq IRQ_RX_START [1] side db0 + +.wrap_target +pin_still_low: + irq DECODER_TRIGGER [1] side db0 ; Trigger NRZI decoder + +; Resync on rising edge +pin_low: + jmp pin pin_went_high side db1 +pin_went_low: + jmp pin pin_went_high side db1 + jmp pin pin_went_high side db1 + jmp pin pin_went_high side db1 + jmp pin pin_went_high side db1 + jmp pin pin_went_high side db1 +.wrap + +pin_still_high: + mov x, isr [2] side db1 + jmp x-- eop side db1 ; Jump to eop if jmp_pin and in_pin are high because both inputs are inverted +; Jump to here on rising edge +pin_went_high: + mov isr, null side db1 + in pins, 1 side db0 ; Capture the pin to check eop. + irq DECODER_TRIGGER side db0 ; Trigger NRZI decoder + jmp pin pin_still_high side db0 + jmp pin_went_low side db1 ; To adjust interval of decoder trigger, jump to pin_went_low (not pin_low) + +; USB NRZI data decoder +; 15 instruction +; FS(12M) LS(1.5M) +; Run at as fast as possible +; jmp_pin d+ d- +; both d+/d- pin should be input invert overrideed +; Fill OSR by 1 and set 0 to x before runnning this program +.program usb_nrzi_decoder +start: + ; set x, 0 +.wrap_target +set_y: + set y, BIT_REPEAT_COUNT +irq_wait: + wait 1 irq DECODER_TRIGGER ; wait signal from edge detector + jmp !y flip ; ignore stuff bit, without error check + jmp PIN pin_high +pin_low: + jmp !x K1 +K2: + ; x==1 +J1: + ; x==0 + in null, 1 +flip: + mov x, ~x +.wrap + +pin_high: + jmp !x J1 +J2: + ; x==1 +K1: + ; x==0 + in osr, 1 + jmp y-- irq_wait ; y is always not 0 at here + +.program usb_nrzi_decoder_debug +.side_set 1 opt +start: + ; set x, 0 side db0 +.wrap_target +set_y: + set y, BIT_REPEAT_COUNT +irq_wait: + wait 1 irq DECODER_TRIGGER ; wait signal from edge detector + jmp !y flip ; ignore stuff bit, without error check + jmp PIN pin_high +pin_low: + jmp !x K1 side db0 +K2: + ; x==1 +J1: + ; x==0 + in null, 1 +flip: + mov x, ~x +.wrap + +pin_high: + jmp !x J1 side db1 +K1: + ; x==0 +J2: + ; x==1 + in osr, 1 + jmp y-- irq_wait ; y is always not 0 at here + +% c-sdk { +#include "hardware/clocks.h" + +#if PICO_SDK_VERSION_MAJOR < 2 +static __always_inline void pio_sm_set_jmp_pin(PIO pio, uint sm, uint jmp_pin) { + pio->sm[sm].execctrl = + (pio->sm[sm].execctrl & ~PIO_SM0_EXECCTRL_JMP_PIN_BITS) | + (jmp_pin << PIO_SM0_EXECCTRL_JMP_PIN_LSB); +} +#endif + +static inline void usb_rx_fs_program_init(PIO pio, uint sm, uint offset, uint pin_dp, uint pin_dm, int pin_debug) { + if (pin_dp < pin_dm) { + pio_sm_set_consecutive_pindirs(pio, sm, pin_dp, 2, false); + } else { + pio_sm_set_consecutive_pindirs(pio, sm, pin_dm, 2, false); + } + gpio_pull_down(pin_dp); + gpio_pull_down(pin_dm); + gpio_set_inover(pin_dp, GPIO_OVERRIDE_INVERT); + gpio_set_inover(pin_dm, GPIO_OVERRIDE_INVERT); + + pio_sm_config c; + + if (pin_debug < 0) { + c = usb_nrzi_decoder_program_get_default_config(offset); + } else { + c = usb_nrzi_decoder_debug_program_get_default_config(offset); + + pio_sm_set_pins_with_mask(pio, sm, 0, 1 << pin_debug); + pio_sm_set_pindirs_with_mask(pio, sm, 1 << pin_debug, 1 << pin_debug); + pio_gpio_init(pio, pin_debug); + sm_config_set_sideset_pins(&c, pin_debug); + } + + sm_config_set_in_pins(&c, pin_dp); // for WAIT, IN + sm_config_set_jmp_pin(&c, pin_dp); // for JMP + + // Shift to right, autopull enabled, 8bit + sm_config_set_in_shift(&c, true, true, 8); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); + + pio_sm_init(pio, sm, offset, &c); + pio_sm_exec(pio, sm, pio_encode_mov_not(pio_osr, pio_null)); + pio_sm_set_enabled(pio, sm, false); +} + +static inline void eop_detect_fs_program_init(PIO pio, uint sm, uint offset, + uint pin_dp, uint pin_dm, bool is_fs, int pin_debug) { + pio_sm_config c; + + if (pin_debug < 0) { + c = usb_edge_detector_program_get_default_config(offset); + } else { + c = usb_edge_detector_debug_program_get_default_config(offset); + pio_sm_set_pins_with_mask(pio, sm, 0, 1 << pin_debug); + pio_sm_set_pindirs_with_mask(pio, sm, 1 << pin_debug, 1 << pin_debug); + pio_gpio_init(pio, pin_debug); + sm_config_set_sideset_pins(&c, pin_debug); + } + + sm_config_set_in_pins(&c, pin_dp); // for WAIT, IN + sm_config_set_jmp_pin(&c, pin_dm); // for JMP + + sm_config_set_in_shift(&c, false, false, 8); + + float div; + if (is_fs) { + div = (float)clock_get_hz(clk_sys) / (96000000); + } else { + div = (float)clock_get_hz(clk_sys) / (12000000); + } + + sm_config_set_clkdiv(&c, div); + + pio_sm_init(pio, sm, offset, &c); + pio_sm_set_enabled(pio, sm, true); +} + +%} \ No newline at end of file diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_rx.pio.h b/rescue/firmware/lib/Pico-PIO-USB/src/usb_rx.pio.h new file mode 100644 index 00000000..4beaa35b --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_rx.pio.h @@ -0,0 +1,239 @@ +// -------------------------------------------------- // +// This file is autogenerated by pioasm; do not edit! // +// -------------------------------------------------- // + +#pragma once + +#if !PICO_NO_HARDWARE +#include "hardware/pio.h" +#endif + +#define IRQ_RX_BS_ERR 1 +#define IRQ_RX_EOP 2 +#define IRQ_RX_START 3 +#define DECODER_TRIGGER 4 + +// ----------------- // +// usb_edge_detector // +// ----------------- // + +#define usb_edge_detector_wrap_target 3 +#define usb_edge_detector_wrap 9 + +static const uint16_t usb_edge_detector_program_instructions[] = { + 0xc022, // 0: irq wait 2 + 0x00c1, // 1: jmp pin, 1 + 0xc103, // 2: irq nowait 3 [1] + // .wrap_target + 0xc104, // 3: irq nowait 4 [1] + 0x00cc, // 4: jmp pin, 12 + 0x00cc, // 5: jmp pin, 12 + 0x00cc, // 6: jmp pin, 12 + 0x00cc, // 7: jmp pin, 12 + 0x00cc, // 8: jmp pin, 12 + 0x00cc, // 9: jmp pin, 12 + // .wrap + 0xa226, // 10: mov x, isr [2] + 0x0040, // 11: jmp x--, 0 + 0xa0c3, // 12: mov isr, null + 0x4001, // 13: in pins, 1 + 0xc004, // 14: irq nowait 4 + 0x00ca, // 15: jmp pin, 10 + 0x0005, // 16: jmp 5 +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program usb_edge_detector_program = { + .instructions = usb_edge_detector_program_instructions, + .length = 17, + .origin = -1, +}; + +static inline pio_sm_config usb_edge_detector_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_edge_detector_wrap_target, offset + usb_edge_detector_wrap); + return c; +} +#endif + +// ----------------------- // +// usb_edge_detector_debug // +// ----------------------- // + +#define usb_edge_detector_debug_wrap_target 3 +#define usb_edge_detector_debug_wrap 9 + +static const uint16_t usb_edge_detector_debug_program_instructions[] = { + 0xc022, // 0: irq wait 2 side 0 + 0x10c1, // 1: jmp pin, 1 side 1 + 0xc103, // 2: irq nowait 3 side 0 [1] + // .wrap_target + 0xc104, // 3: irq nowait 4 side 0 [1] + 0x10cc, // 4: jmp pin, 12 side 1 + 0x10cc, // 5: jmp pin, 12 side 1 + 0x10cc, // 6: jmp pin, 12 side 1 + 0x10cc, // 7: jmp pin, 12 side 1 + 0x10cc, // 8: jmp pin, 12 side 1 + 0x10cc, // 9: jmp pin, 12 side 1 + // .wrap + 0xb226, // 10: mov x, isr side 1 [2] + 0x1040, // 11: jmp x--, 0 side 1 + 0xb0c3, // 12: mov isr, null side 1 + 0x4001, // 13: in pins, 1 side 0 + 0xc004, // 14: irq nowait 4 side 0 + 0x00ca, // 15: jmp pin, 10 side 0 + 0x1005, // 16: jmp 5 side 1 +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program usb_edge_detector_debug_program = { + .instructions = usb_edge_detector_debug_program_instructions, + .length = 17, + .origin = -1, +}; + +static inline pio_sm_config usb_edge_detector_debug_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_edge_detector_debug_wrap_target, offset + usb_edge_detector_debug_wrap); + sm_config_set_sideset(&c, 1, false, false); + return c; +} +#endif + +// ---------------- // +// usb_nrzi_decoder // +// ---------------- // + +#define usb_nrzi_decoder_wrap_target 0 +#define usb_nrzi_decoder_wrap 6 + +static const uint16_t usb_nrzi_decoder_program_instructions[] = { + // .wrap_target + 0xe046, // 0: set y, 6 + 0x20c4, // 1: wait 1 irq, 4 + 0x0066, // 2: jmp !y, 6 + 0x00c7, // 3: jmp pin, 7 + 0x0028, // 4: jmp !x, 8 + 0x4061, // 5: in null, 1 + 0xa029, // 6: mov x, !x + // .wrap + 0x0025, // 7: jmp !x, 5 + 0x40e1, // 8: in osr, 1 + 0x0081, // 9: jmp y--, 1 +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program usb_nrzi_decoder_program = { + .instructions = usb_nrzi_decoder_program_instructions, + .length = 10, + .origin = -1, +}; + +static inline pio_sm_config usb_nrzi_decoder_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_nrzi_decoder_wrap_target, offset + usb_nrzi_decoder_wrap); + return c; +} +#endif + +// ---------------------- // +// usb_nrzi_decoder_debug // +// ---------------------- // + +#define usb_nrzi_decoder_debug_wrap_target 0 +#define usb_nrzi_decoder_debug_wrap 6 + +static const uint16_t usb_nrzi_decoder_debug_program_instructions[] = { + // .wrap_target + 0xe046, // 0: set y, 6 + 0x20c4, // 1: wait 1 irq, 4 + 0x0066, // 2: jmp !y, 6 + 0x00c7, // 3: jmp pin, 7 + 0x1028, // 4: jmp !x, 8 side 0 + 0x4061, // 5: in null, 1 + 0xa029, // 6: mov x, !x + // .wrap + 0x1825, // 7: jmp !x, 5 side 1 + 0x40e1, // 8: in osr, 1 + 0x0081, // 9: jmp y--, 1 +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program usb_nrzi_decoder_debug_program = { + .instructions = usb_nrzi_decoder_debug_program_instructions, + .length = 10, + .origin = -1, +}; + +static inline pio_sm_config usb_nrzi_decoder_debug_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_nrzi_decoder_debug_wrap_target, offset + usb_nrzi_decoder_debug_wrap); + sm_config_set_sideset(&c, 2, true, false); + return c; +} + +#include "hardware/clocks.h" +#if PICO_SDK_VERSION_MAJOR < 2 +static __always_inline void pio_sm_set_jmp_pin(PIO pio, uint sm, uint jmp_pin) { + pio->sm[sm].execctrl = + (pio->sm[sm].execctrl & ~PIO_SM0_EXECCTRL_JMP_PIN_BITS) | + (jmp_pin << PIO_SM0_EXECCTRL_JMP_PIN_LSB); +} +#endif +static inline void usb_rx_fs_program_init(PIO pio, uint sm, uint offset, uint pin_dp, uint pin_dm, int pin_debug) { + if (pin_dp < pin_dm) { + pio_sm_set_consecutive_pindirs(pio, sm, pin_dp, 2, false); + } else { + pio_sm_set_consecutive_pindirs(pio, sm, pin_dm, 2, false); + } + gpio_pull_down(pin_dp); + gpio_pull_down(pin_dm); + gpio_set_inover(pin_dp, GPIO_OVERRIDE_INVERT); + gpio_set_inover(pin_dm, GPIO_OVERRIDE_INVERT); + pio_sm_config c; + if (pin_debug < 0) { + c = usb_nrzi_decoder_program_get_default_config(offset); + } else { + c = usb_nrzi_decoder_debug_program_get_default_config(offset); + pio_sm_set_pins_with_mask(pio, sm, 0, 1 << pin_debug); + pio_sm_set_pindirs_with_mask(pio, sm, 1 << pin_debug, 1 << pin_debug); + pio_gpio_init(pio, pin_debug); + sm_config_set_sideset_pins(&c, pin_debug); + } + sm_config_set_in_pins(&c, pin_dp); // for WAIT, IN + sm_config_set_jmp_pin(&c, pin_dp); // for JMP + // Shift to right, autopull enabled, 8bit + sm_config_set_in_shift(&c, true, true, 8); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); + pio_sm_init(pio, sm, offset, &c); + pio_sm_exec(pio, sm, pio_encode_mov_not(pio_osr, pio_null)); + pio_sm_set_enabled(pio, sm, false); +} +static inline void eop_detect_fs_program_init(PIO pio, uint sm, uint offset, + uint pin_dp, uint pin_dm, bool is_fs, int pin_debug) { + pio_sm_config c; + if (pin_debug < 0) { + c = usb_edge_detector_program_get_default_config(offset); + } else { + c = usb_edge_detector_debug_program_get_default_config(offset); + pio_sm_set_pins_with_mask(pio, sm, 0, 1 << pin_debug); + pio_sm_set_pindirs_with_mask(pio, sm, 1 << pin_debug, 1 << pin_debug); + pio_gpio_init(pio, pin_debug); + sm_config_set_sideset_pins(&c, pin_debug); + } + sm_config_set_in_pins(&c, pin_dp); // for WAIT, IN + sm_config_set_jmp_pin(&c, pin_dm); // for JMP + sm_config_set_in_shift(&c, false, false, 8); + float div; + if (is_fs) { + div = (float)clock_get_hz(clk_sys) / (96000000); + } else { + div = (float)clock_get_hz(clk_sys) / (12000000); + } + sm_config_set_clkdiv(&c, div); + pio_sm_init(pio, sm, offset, &c); + pio_sm_set_enabled(pio, sm, true); +} + +#endif + diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_tx.pio b/rescue/firmware/lib/Pico-PIO-USB/src/usb_tx.pio new file mode 100644 index 00000000..dffb7b92 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_tx.pio @@ -0,0 +1,159 @@ +; Copyright (c) 2021-2024 sekigon-gonnoc + +.define public IRQ_TX_EOP 0 ; EOP start flag bit + +; USB NRZI transmitter +; Run at 48 MHz for full-spped (x4) +; Run at 6 MHz for low-spped (x4) +; autopull enabled +; Should be placed at address 0 +.program usb_tx_dpdm +.side_set 2 + +; J for fs, K for ls +.define FJ_LK 0b01 +; K for fs, J for ls +.define FK_LJ 0b10 +.define SE0 0b00 + +irq IRQ_TX_EOP side SE0 [7] +reset: +.wrap_target +out pc, 2 side FJ_LK [3] +set pindirs, 0b00 side FJ_LK [3] +out pc, 2 side FK_LJ [3] +start: +set pindirs, 0b11 side FJ_LK +.wrap + +; USB transmitter for PRE packet (No EOP) +; Run at 48 MHz for full-spped +; autopull enabled +.program usb_tx_pre_dpdm +.side_set 2 + +; J for fs, K for ls +.define FJ_LK 0b01 +; K for fs, J for ls +.define FK_LJ 0b10 +.define SE0 0b00 + +irq IRQ_TX_EOP side FJ_LK [7] +reset: +.wrap_target +out pc, 2 side FJ_LK [3] +set pindirs, 0b00 side FJ_LK [3] +out pc, 2 side FK_LJ [3] +start: +set pindirs, 0b11 side FJ_LK +.wrap + +; USB NRZI transmitter +; Run at 48 MHz for full-spped +; Run at 6 MHz for low-spped +; autopull enabled +.program usb_tx_dmdp +.side_set 2 + +.define FK_LJ 0b01 +.define FJ_LK 0b10 +.define SE0 0b00 + +irq IRQ_TX_EOP side SE0 [7] +reset: +.wrap_target +out pc, 2 side FJ_LK [3] +set pindirs, 0b00 side FJ_LK [3] +out pc, 2 side FK_LJ [3] +start: +set pindirs, 0b11 side FJ_LK +.wrap + +; USB transmitter for PRE packet (No EOP) +; Run at 48 MHz for full-spped +; autopull enabled +.program usb_tx_pre_dmdp +.side_set 2 + +.define FK_LJ 0b01 +.define FJ_LK 0b10 +.define SE0 0b00 + +irq IRQ_TX_EOP side FJ_LK [7] +reset: +.wrap_target +out pc, 2 side FJ_LK [3] +set pindirs, 0b00 side FJ_LK [3] +out pc, 2 side FK_LJ [3] +start: +set pindirs, 0b11 side FJ_LK +.wrap + +% c-sdk { +#include "hardware/clocks.h" + + static void __no_inline_not_in_flash_func(usb_tx_configure_pins)(PIO pio, uint sm, uint pin_dp, uint pin_dm) { + if (pin_dp < pin_dm) { + pio_sm_set_out_pins(pio, sm, pin_dp, 2); + pio_sm_set_set_pins(pio, sm, pin_dp, 2); + pio_sm_set_sideset_pins(pio, sm, pin_dp); + } else { + pio_sm_set_out_pins(pio, sm, pin_dm, 2); + pio_sm_set_set_pins(pio, sm, pin_dm, 2); + pio_sm_set_sideset_pins(pio, sm, pin_dm); + } + } + + static inline void usb_tx_fs_program_init(PIO pio, uint sm, uint offset, + uint pin_dp, uint pin_dm) { + pio_sm_set_pins_with_mask(pio, sm, (1 << pin_dp), ((1 << pin_dp) | (1 << pin_dm))); + + gpio_pull_down(pin_dp); + gpio_pull_down(pin_dm); + pio_gpio_init(pio, pin_dp); + pio_gpio_init(pio, pin_dm); + + pio_sm_config c = usb_tx_dpdm_program_get_default_config(offset); + + // shifts to left, autopull, 8bit + sm_config_set_out_shift(&c, false, true, 8); + + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + + // run at 48MHz + // clk_sys should be multiply of 12MHz + float div = (float)clock_get_hz(clk_sys) / (48000000UL); + sm_config_set_clkdiv(&c, div); + + pio_sm_init(pio, sm, offset + 1, &c); + usb_tx_configure_pins(pio, sm, pin_dp, pin_dm); + pio_sm_set_enabled(pio, sm, true); + } + + static inline void usb_tx_ls_program_init(PIO pio, uint sm, uint offset, + uint pin_dp, uint pin_dm) { + pio_sm_set_pins_with_mask(pio, sm, (1 << pin_dm), ((1 << pin_dp) | (1 << pin_dm))); + + gpio_pull_down(pin_dp); + gpio_pull_down(pin_dm); + pio_gpio_init(pio, pin_dp); + pio_gpio_init(pio, pin_dm); + + pio_sm_config c = usb_tx_dmdp_program_get_default_config(offset); + + // shifts to left, autopull, 8bit + sm_config_set_out_shift(&c, false, true, 8); + + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + + // run at 6MHz + // clk_sys should be multiply of 12MHz + float div = (float)clock_get_hz(clk_sys) / (6000000UL); + sm_config_set_clkdiv(&c, div); + + pio_sm_init(pio, sm, offset + 1, &c); + usb_tx_configure_pins(pio, sm, pin_dp, pin_dm); + pio_sm_set_enabled(pio, sm, true); + } + +%} \ No newline at end of file diff --git a/rescue/firmware/lib/Pico-PIO-USB/src/usb_tx.pio.h b/rescue/firmware/lib/Pico-PIO-USB/src/usb_tx.pio.h new file mode 100644 index 00000000..0e938c83 --- /dev/null +++ b/rescue/firmware/lib/Pico-PIO-USB/src/usb_tx.pio.h @@ -0,0 +1,192 @@ +// -------------------------------------------------- // +// This file is autogenerated by pioasm; do not edit! // +// -------------------------------------------------- // + +#pragma once + +#if !PICO_NO_HARDWARE +#include "hardware/pio.h" +#endif + +#define IRQ_TX_EOP 0 + +// ----------- // +// usb_tx_dpdm // +// ----------- // + +#define usb_tx_dpdm_wrap_target 1 +#define usb_tx_dpdm_wrap 4 + +static const uint16_t __not_in_flash("tx_program") usb_tx_dpdm_program_instructions[] = { + 0xc700, // 0: irq nowait 0 side 0 [7] + // .wrap_target + 0x6ba2, // 1: out pc, 2 side 1 [3] + 0xeb80, // 2: set pindirs, 0 side 1 [3] + 0x73a2, // 3: out pc, 2 side 2 [3] + 0xe883, // 4: set pindirs, 3 side 1 + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program __not_in_flash("tx_program") usb_tx_dpdm_program = { + .instructions = usb_tx_dpdm_program_instructions, + .length = 5, + .origin = -1, +}; + +static inline pio_sm_config usb_tx_dpdm_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_tx_dpdm_wrap_target, offset + usb_tx_dpdm_wrap); + sm_config_set_sideset(&c, 2, false, false); + return c; +} +#endif + +// --------------- // +// usb_tx_pre_dpdm // +// --------------- // + +#define usb_tx_pre_dpdm_wrap_target 1 +#define usb_tx_pre_dpdm_wrap 4 + +static const uint16_t __not_in_flash("tx_program") usb_tx_pre_dpdm_program_instructions[] = { + 0xcf00, // 0: irq nowait 0 side 1 [7] + // .wrap_target + 0x6ba2, // 1: out pc, 2 side 1 [3] + 0xeb80, // 2: set pindirs, 0 side 1 [3] + 0x73a2, // 3: out pc, 2 side 2 [3] + 0xe883, // 4: set pindirs, 3 side 1 + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program __not_in_flash("tx_program") usb_tx_pre_dpdm_program = { + .instructions = usb_tx_pre_dpdm_program_instructions, + .length = 5, + .origin = -1, +}; + +static inline pio_sm_config usb_tx_pre_dpdm_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_tx_pre_dpdm_wrap_target, offset + usb_tx_pre_dpdm_wrap); + sm_config_set_sideset(&c, 2, false, false); + return c; +} +#endif + +// ----------- // +// usb_tx_dmdp // +// ----------- // + +#define usb_tx_dmdp_wrap_target 1 +#define usb_tx_dmdp_wrap 4 + +static const uint16_t __not_in_flash("tx_program") usb_tx_dmdp_program_instructions[] = { + 0xc700, // 0: irq nowait 0 side 0 [7] + // .wrap_target + 0x73a2, // 1: out pc, 2 side 2 [3] + 0xf380, // 2: set pindirs, 0 side 2 [3] + 0x6ba2, // 3: out pc, 2 side 1 [3] + 0xf083, // 4: set pindirs, 3 side 2 + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program __not_in_flash("tx_program") usb_tx_dmdp_program = { + .instructions = usb_tx_dmdp_program_instructions, + .length = 5, + .origin = -1, +}; + +static inline pio_sm_config usb_tx_dmdp_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_tx_dmdp_wrap_target, offset + usb_tx_dmdp_wrap); + sm_config_set_sideset(&c, 2, false, false); + return c; +} +#endif + +// --------------- // +// usb_tx_pre_dmdp // +// --------------- // + +#define usb_tx_pre_dmdp_wrap_target 1 +#define usb_tx_pre_dmdp_wrap 4 + +static const uint16_t __not_in_flash("tx_program") usb_tx_pre_dmdp_program_instructions[] = { + 0xd700, // 0: irq nowait 0 side 2 [7] + // .wrap_target + 0x73a2, // 1: out pc, 2 side 2 [3] + 0xf380, // 2: set pindirs, 0 side 2 [3] + 0x6ba2, // 3: out pc, 2 side 1 [3] + 0xf083, // 4: set pindirs, 3 side 2 + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program __not_in_flash("tx_program") usb_tx_pre_dmdp_program = { + .instructions = usb_tx_pre_dmdp_program_instructions, + .length = 5, + .origin = -1, +}; + +static inline pio_sm_config usb_tx_pre_dmdp_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + usb_tx_pre_dmdp_wrap_target, offset + usb_tx_pre_dmdp_wrap); + sm_config_set_sideset(&c, 2, false, false); + return c; +} + +#include "hardware/clocks.h" + static void __no_inline_not_in_flash_func(usb_tx_configure_pins)(PIO pio, uint sm, uint pin_dp, uint pin_dm) { + if (pin_dp < pin_dm) { + pio_sm_set_out_pins(pio, sm, pin_dp, 2); + pio_sm_set_set_pins(pio, sm, pin_dp, 2); + pio_sm_set_sideset_pins(pio, sm, pin_dp); + } else { + pio_sm_set_out_pins(pio, sm, pin_dm, 2); + pio_sm_set_set_pins(pio, sm, pin_dm, 2); + pio_sm_set_sideset_pins(pio, sm, pin_dm); + } + } + static inline void usb_tx_fs_program_init(PIO pio, uint sm, uint offset, + uint pin_dp, uint pin_dm) { + pio_sm_set_pins_with_mask(pio, sm, (1 << pin_dp), ((1 << pin_dp) | (1 << pin_dm))); + gpio_pull_down(pin_dp); + gpio_pull_down(pin_dm); + pio_gpio_init(pio, pin_dp); + pio_gpio_init(pio, pin_dm); + pio_sm_config c = usb_tx_dpdm_program_get_default_config(offset); + // shifts to left, autopull, 8bit + sm_config_set_out_shift(&c, false, true, 8); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + // run at 48MHz + // clk_sys should be multiply of 12MHz + float div = (float)clock_get_hz(clk_sys) / (48000000UL); + sm_config_set_clkdiv(&c, div); + pio_sm_init(pio, sm, offset + 1, &c); + usb_tx_configure_pins(pio, sm, pin_dp, pin_dm); + pio_sm_set_enabled(pio, sm, true); + } + static inline void usb_tx_ls_program_init(PIO pio, uint sm, uint offset, + uint pin_dp, uint pin_dm) { + pio_sm_set_pins_with_mask(pio, sm, (1 << pin_dm), ((1 << pin_dp) | (1 << pin_dm))); + gpio_pull_down(pin_dp); + gpio_pull_down(pin_dm); + pio_gpio_init(pio, pin_dp); + pio_gpio_init(pio, pin_dm); + pio_sm_config c = usb_tx_dmdp_program_get_default_config(offset); + // shifts to left, autopull, 8bit + sm_config_set_out_shift(&c, false, true, 8); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + // run at 6MHz + // clk_sys should be multiply of 12MHz + float div = (float)clock_get_hz(clk_sys) / (6000000UL); + sm_config_set_clkdiv(&c, div); + pio_sm_init(pio, sm, offset + 1, &c); + usb_tx_configure_pins(pio, sm, pin_dp, pin_dm); + pio_sm_set_enabled(pio, sm, true); + } + +#endif + diff --git a/rescue/firmware/lib/pico-pio-usb-bulk-multi-xact.patch b/rescue/firmware/lib/pico-pio-usb-bulk-multi-xact.patch new file mode 100644 index 00000000..40fd3a77 --- /dev/null +++ b/rescue/firmware/lib/pico-pio-usb-bulk-multi-xact.patch @@ -0,0 +1,49 @@ +diff -ru a/src/pio_usb_host.c b/src/pio_usb_host.c +--- a/src/pio_usb_host.c ++++ b/src/pio_usb_host.c +@@ -246,11 +246,19 @@ + static int usb_in_transaction(pio_port_t *pp, endpoint_t *ep); + static int usb_out_transaction(pio_port_t *pp, endpoint_t *ep); + ++#ifndef PIO_USB_BULK_FRAME_BUDGET_US ++// FM-1 Transporter: keep running bulk transactions within a frame until this ++// much of the 1 ms frame has elapsed (upstream does one packet per frame). ++#define PIO_USB_BULK_FRAME_BUDGET_US 700 ++#endif ++ + void __not_in_flash_func(pio_usb_host_frame)(void) { + if (!timer_active) { + return; + } + ++ uint32_t const frame_start_us = time_us_32(); ++ + pio_port_t *pp = PIO_USB_PIO_PORT(0); + + // Send SOF +@@ -294,10 +302,21 @@ + if (ep->ep_num == 0 && ep->data_id == USB_PID_SETUP) { + usb_setup_transaction(pp, ep); + } else { +- if (ep->ep_num & EP_IN) { +- usb_in_transaction(pp, ep); +- } else { +- usb_out_transaction(pp, ep); ++ bool const is_bulk = ((ep->attr & 0x03) == EP_ATTR_BULK); ++ for (;;) { ++ if (ep->ep_num & EP_IN) { ++ usb_in_transaction(pp, ep); ++ } else { ++ usb_out_transaction(pp, ep); ++ } ++ // Bulk only: keep going, NAKs included, while the frame has ++ // time left. Devices such as the JieLi loader NAK briefly while ++ // refilling their FIFO; a hardware host retries at once too. ++ // Completion, STALL and errors clear has_transfer. ++ if (!is_bulk || !ep->has_transfer || ep->transfer_aborted || ++ time_us_32() - frame_start_us > PIO_USB_BULK_FRAME_BUDGET_US) { ++ break; ++ } + } + + if (is_periodic) { diff --git a/rescue/firmware/lib/pico-pio-usb-debugprobe.patch b/rescue/firmware/lib/pico-pio-usb-debugprobe.patch new file mode 100644 index 00000000..4318bba6 --- /dev/null +++ b/rescue/firmware/lib/pico-pio-usb-debugprobe.patch @@ -0,0 +1,232 @@ +diff --git a/src/pio_usb.c b/src/pio_usb.c +index e84b6fa..abab9a3 100644 +--- a/src/pio_usb.c ++++ b/src/pio_usb.c +@@ -290,7 +290,7 @@ static void apply_config(pio_port_t *pp, const pio_usb_configuration_t *c, + port->pin_dp = c->pin_dp; + + if (c->pinout == PIO_USB_PINOUT_DPDM) { +- port->pin_dm = c->pin_dp + 1; ++ port->pin_dm = c->pin_dp + 2; + pp->fs_tx_program = &usb_tx_dpdm_program; + pp->fs_tx_pre_program = &usb_tx_pre_dpdm_program; + pp->ls_tx_program = &usb_tx_dmdp_program; +@@ -559,7 +559,7 @@ int pio_usb_host_add_port(uint8_t pin_dp, PIO_USB_PINOUT pinout) { + root->pin_dp = pin_dp; + + if (pinout == PIO_USB_PINOUT_DPDM) { +- root->pin_dm = pin_dp + 1; ++ root->pin_dm = pin_dp + 2; + } else { + root->pin_dm = pin_dp - 1; + } +diff --git a/src/pio_usb_host.c b/src/pio_usb_host.c +index 831bce9..aab3e10 100644 +--- a/src/pio_usb_host.c ++++ b/src/pio_usb_host.c +@@ -66,10 +66,10 @@ usb_device_t *pio_usb_host_init(const pio_usb_configuration_t *c) { + root->mode = PIO_USB_MODE_HOST; + + float const cpu_freq = (float)clock_get_hz(clk_sys); +- pio_calculate_clkdiv_from_float(cpu_freq / 48000000, ++ pio_calculate_clkdiv_from_float(cpu_freq / 24000000, + &pp->clk_div_fs_tx.div_int, + &pp->clk_div_fs_tx.div_frac); +- pio_calculate_clkdiv_from_float(cpu_freq / 6000000, ++ pio_calculate_clkdiv_from_float(cpu_freq / 3000000, + &pp->clk_div_ls_tx.div_int, + &pp->clk_div_ls_tx.div_frac); + +diff --git a/src/usb_rx.pio b/src/usb_rx.pio +index 76e6fbe..432ec7f 100644 +--- a/src/usb_rx.pio ++++ b/src/usb_rx.pio +@@ -166,7 +166,7 @@ static __always_inline void pio_sm_set_jmp_pin(PIO pio, uint sm, uint jmp_pin) { + + static inline void usb_rx_fs_program_init(PIO pio, uint sm, uint offset, uint pin_dp, uint pin_dm, int pin_debug) { + if (pin_dp < pin_dm) { +- pio_sm_set_consecutive_pindirs(pio, sm, pin_dp, 2, false); ++ pio_sm_set_consecutive_pindirs(pio, sm, pin_dp, 3, false); + } else { + pio_sm_set_consecutive_pindirs(pio, sm, pin_dm, 2, false); + } +diff --git a/src/usb_tx.pio b/src/usb_tx.pio +index dffb7b9..2182246 100644 +--- a/src/usb_tx.pio ++++ b/src/usb_tx.pio +@@ -3,90 +3,92 @@ + .define public IRQ_TX_EOP 0 ; EOP start flag bit + + ; USB NRZI transmitter +-; Run at 48 MHz for full-spped (x4) +-; Run at 6 MHz for low-spped (x4) ++; Run at 24 MHz for full-spped (x2) ++; Run at 3 MHz for low-spped (x2) ++; Raspberry Pi Debug Probe: three side-set pins, D+ at the base, D- two above ++; (the pin between is never enabled), and half the clock so the delays fit + ; autopull enabled + ; Should be placed at address 0 + .program usb_tx_dpdm +-.side_set 2 ++.side_set 3 + + ; J for fs, K for ls +-.define FJ_LK 0b01 ++.define FJ_LK 0b001 + ; K for fs, J for ls +-.define FK_LJ 0b10 +-.define SE0 0b00 ++.define FK_LJ 0b100 ++.define SE0 0b000 + +-irq IRQ_TX_EOP side SE0 [7] ++irq IRQ_TX_EOP side SE0 [3] + reset: + .wrap_target +-out pc, 2 side FJ_LK [3] +-set pindirs, 0b00 side FJ_LK [3] +-out pc, 2 side FK_LJ [3] ++out pc, 2 side FJ_LK [1] ++set pindirs, 0b000 side FJ_LK [1] ++out pc, 2 side FK_LJ [1] + start: +-set pindirs, 0b11 side FJ_LK ++set pindirs, 0b101 side FJ_LK + .wrap + + ; USB transmitter for PRE packet (No EOP) +-; Run at 48 MHz for full-spped ++; Run at 24 MHz for full-spped + ; autopull enabled + .program usb_tx_pre_dpdm +-.side_set 2 ++.side_set 3 + + ; J for fs, K for ls +-.define FJ_LK 0b01 ++.define FJ_LK 0b001 + ; K for fs, J for ls +-.define FK_LJ 0b10 +-.define SE0 0b00 ++.define FK_LJ 0b100 ++.define SE0 0b000 + +-irq IRQ_TX_EOP side FJ_LK [7] ++irq IRQ_TX_EOP side FJ_LK [3] + reset: + .wrap_target +-out pc, 2 side FJ_LK [3] +-set pindirs, 0b00 side FJ_LK [3] +-out pc, 2 side FK_LJ [3] ++out pc, 2 side FJ_LK [1] ++set pindirs, 0b000 side FJ_LK [1] ++out pc, 2 side FK_LJ [1] + start: +-set pindirs, 0b11 side FJ_LK ++set pindirs, 0b101 side FJ_LK + .wrap + + ; USB NRZI transmitter +-; Run at 48 MHz for full-spped +-; Run at 6 MHz for low-spped ++; Run at 24 MHz for full-spped ++; Run at 3 MHz for low-spped + ; autopull enabled + .program usb_tx_dmdp +-.side_set 2 ++.side_set 3 + +-.define FK_LJ 0b01 +-.define FJ_LK 0b10 +-.define SE0 0b00 ++.define FK_LJ 0b001 ++.define FJ_LK 0b100 ++.define SE0 0b000 + +-irq IRQ_TX_EOP side SE0 [7] ++irq IRQ_TX_EOP side SE0 [3] + reset: + .wrap_target +-out pc, 2 side FJ_LK [3] +-set pindirs, 0b00 side FJ_LK [3] +-out pc, 2 side FK_LJ [3] ++out pc, 2 side FJ_LK [1] ++set pindirs, 0b000 side FJ_LK [1] ++out pc, 2 side FK_LJ [1] + start: +-set pindirs, 0b11 side FJ_LK ++set pindirs, 0b101 side FJ_LK + .wrap + + ; USB transmitter for PRE packet (No EOP) +-; Run at 48 MHz for full-spped ++; Run at 24 MHz for full-spped + ; autopull enabled + .program usb_tx_pre_dmdp +-.side_set 2 ++.side_set 3 + +-.define FK_LJ 0b01 +-.define FJ_LK 0b10 +-.define SE0 0b00 ++.define FK_LJ 0b001 ++.define FJ_LK 0b100 ++.define SE0 0b000 + +-irq IRQ_TX_EOP side FJ_LK [7] ++irq IRQ_TX_EOP side FJ_LK [3] + reset: + .wrap_target +-out pc, 2 side FJ_LK [3] +-set pindirs, 0b00 side FJ_LK [3] +-out pc, 2 side FK_LJ [3] ++out pc, 2 side FJ_LK [1] ++set pindirs, 0b000 side FJ_LK [1] ++out pc, 2 side FK_LJ [1] + start: +-set pindirs, 0b11 side FJ_LK ++set pindirs, 0b101 side FJ_LK + .wrap + + % c-sdk { +@@ -94,12 +96,12 @@ set pindirs, 0b11 side FJ_LK + + static void __no_inline_not_in_flash_func(usb_tx_configure_pins)(PIO pio, uint sm, uint pin_dp, uint pin_dm) { + if (pin_dp < pin_dm) { +- pio_sm_set_out_pins(pio, sm, pin_dp, 2); +- pio_sm_set_set_pins(pio, sm, pin_dp, 2); ++ pio_sm_set_out_pins(pio, sm, pin_dp, 3); ++ pio_sm_set_set_pins(pio, sm, pin_dp, 3); + pio_sm_set_sideset_pins(pio, sm, pin_dp); + } else { +- pio_sm_set_out_pins(pio, sm, pin_dm, 2); +- pio_sm_set_set_pins(pio, sm, pin_dm, 2); ++ pio_sm_set_out_pins(pio, sm, pin_dm, 3); ++ pio_sm_set_set_pins(pio, sm, pin_dm, 3); + pio_sm_set_sideset_pins(pio, sm, pin_dm); + } + } +@@ -120,9 +122,9 @@ set pindirs, 0b11 side FJ_LK + + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + +- // run at 48MHz ++ // run at 24MHz + // clk_sys should be multiply of 12MHz +- float div = (float)clock_get_hz(clk_sys) / (48000000UL); ++ float div = (float)clock_get_hz(clk_sys) / (24000000UL); + sm_config_set_clkdiv(&c, div); + + pio_sm_init(pio, sm, offset + 1, &c); +@@ -146,9 +148,9 @@ set pindirs, 0b11 side FJ_LK + + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + +- // run at 6MHz ++ // run at 3MHz + // clk_sys should be multiply of 12MHz +- float div = (float)clock_get_hz(clk_sys) / (6000000UL); ++ float div = (float)clock_get_hz(clk_sys) / (3000000UL); + sm_config_set_clkdiv(&c, div); + + pio_sm_init(pio, sm, offset + 1, &c); diff --git a/rescue/firmware/pico_sdk_import.cmake b/rescue/firmware/pico_sdk_import.cmake new file mode 100644 index 00000000..9c84e016 --- /dev/null +++ b/rescue/firmware/pico_sdk_import.cmake @@ -0,0 +1,16 @@ +# This file can be copied from the Raspberry Pi Pico SDK: +# external/pico_sdk_import.cmake +# +# Or configure with: +# cmake -S . -B build -DPICO_SDK_PATH=/path/to/pico-sdk +# +# Keeping this placeholder avoids silently vendoring a stale SDK import helper. +if (DEFINED ENV{PICO_SDK_PATH} AND NOT PICO_SDK_PATH) + set(PICO_SDK_PATH $ENV{PICO_SDK_PATH}) +endif() + +if (NOT PICO_SDK_PATH) + message(FATAL_ERROR "Set PICO_SDK_PATH to your pico-sdk checkout") +endif() + +include(${PICO_SDK_PATH}/external/pico_sdk_import.cmake) diff --git a/rescue/firmware/pio/usb_key.pio b/rescue/firmware/pio/usb_key.pio new file mode 100644 index 00000000..33be4eb9 --- /dev/null +++ b/rescue/firmware/pio/usb_key.pio @@ -0,0 +1,46 @@ +; FM-1 Transporter - JieLi USB_KEY and ROM calibration pulse generator. + +.program usb_key_pp +.side_set 1 +.wrap_target + pull block side 0 + set pins, 0 side 0 + set pindirs, 3 side 0 + set x, 14 side 0 +bitloop: + out pins, 1 side 0 [7] + nop side 1 [10] + jmp x-- bitloop side 1 + out pins, 1 side 0 [7] + nop side 1 [9] + set pindirs, 0 side 0 +.wrap + +; The same with D- two pins above D+ (Raspberry Pi Debug Probe: GP4, GP6). +; The pin between stays an input. +.program usb_key_pp_gap +.side_set 1 +.wrap_target + pull block side 0 + set pins, 0 side 0 + set pindirs, 5 side 0 + set x, 14 side 0 +bitloop: + out pins, 1 side 0 [7] + nop side 1 [10] + jmp x-- bitloop side 1 + out pins, 1 side 0 [7] + nop side 1 [9] + set pindirs, 0 side 0 +.wrap + +.program sof_pulse +.wrap_target + set pindirs, 1 [3] + set pindirs, 0 + set x, 30 +delay: + nop [30] + jmp x-- delay + nop [1] +.wrap diff --git a/rescue/firmware/pio/ws2812.pio b/rescue/firmware/pio/ws2812.pio new file mode 100644 index 00000000..b8bf1ab3 --- /dev/null +++ b/rescue/firmware/pio/ws2812.pio @@ -0,0 +1,19 @@ +; WS2812 driver, from pico-examples (BSD-3-Clause, Raspberry Pi Ltd). +; Used for the RP2040-Zero's status LED on GP16. + +.program ws2812 +.side_set 1 + +.define public T1 3 +.define public T2 3 +.define public T3 4 + +.wrap_target +bitloop: + out x, 1 side 0 [T3 - 1] + jmp !x do_zero side 1 [T1 - 1] +do_one: + jmp bitloop side 1 [T2 - 1] +do_zero: + nop side 0 [T2 - 1] +.wrap diff --git a/rescue/firmware/src/autorescue.c b/rescue/firmware/src/autorescue.c new file mode 100644 index 00000000..dac7597b --- /dev/null +++ b/rescue/firmware/src/autorescue.c @@ -0,0 +1,280 @@ +// FM-1 Rescue: stand-alone restore of the FM-1 firmware region from the +// payload in the RP2040 flash. See autorescue.h. + +#include "autorescue.h" + +#include +#include + +#include "pico/stdlib.h" + +#include "jieli_uboot.h" +#include "log.h" +#include "payload.h" +#include "pio_host.h" +#include "recovery.h" + +#define FLASH_ID_ALT 0xB36014 // 1 MiB part of the 2026 units with the logo on the front +#define WRITE_TRIES 3 +#define SOFTKEY_DELAY_MS 1500 // after a V15 mount, let the probe finish first +#define FOREIGN_AFTER_MS 15000 // mounted, neither UBOOT nor V15, for this long + +typedef enum { + E_NONE, + E_LINK, // lost the FM-1 before anything was written + E_CHIP, // not an FM-1 (chip key / flash ID) + E_WRITE, // a sector could not be written: the region is incomplete + E_VERIFY, // the final read does not match +} ar_err_t; + +typedef enum { PH_IDLE, PH_CHECK, PH_WRITE, PH_VERIFY } ar_phase_t; + +// Written by core 1, read by core 0 for the `rescue` status line. +static volatile ar_state_t state = AR_BOOT; // until ar_init has looked at the payload +static volatile ar_err_t err; +static volatile ar_phase_t phase; +static volatile uint32_t err_addr; +static volatile uint32_t n_written, n_same, cur_sector; +static volatile bool foreign; +static bool any_written; + +static uint8_t __attribute__((aligned(4))) sec[JL_SECTOR_SIZE]; + +bool ar_enabled(void) { + return state != AR_OFF && state != AR_BOOT; +} + +ar_state_t ar_state(void) { + return state; +} + +void ar_status_line(char *s, unsigned n) { + static const char *const names[] = {"off", "boot", "wait", "run", "done", "error", "bad-payload"}; + static const char *const errs[] = {"none", "link", "chip", "write", "verify"}; + static const char *const phases[] = {"idle", "check", "write", "verify"}; + ar_state_t st = state; + snprintf(s, n, "state=%s%s phase=%s sector=%lu/%lu written=%lu same=%lu err=%s addr=%06lX", + names[st], (st == AR_WAIT && foreign) ? " foreign=1" : "", phases[phase], + (unsigned long)cur_sector, (unsigned long)(PL_IMAGE_LEN / JL_SECTOR_SIZE), + (unsigned long)n_written, (unsigned long)n_same, errs[err], + (unsigned long)err_addr); +} + +const char *ar_describe(void) { // core 1 only + static char s[128]; + ar_status_line(s, sizeof(s)); + return s; +} + +void ar_init(void) { + switch (payload_check()) { + case PL_NONE: + state = AR_OFF; + return; + case PL_BAD: + state = AR_BAD_PAYLOAD; + dlog("RESCUE: the payload is damaged; nothing will be written. Rebuild the .uf2."); + return; + case PL_VALID: + break; + } + state = AR_WAIT; + dlog("RESCUE: stand-alone mode. Switch the FM-1 ON now (it must be OFF before)."); +} + +static void fail(ar_err_t e, uint32_t addr) { + err = e; + err_addr = addr; + state = AR_ERROR; + rgb(true, false, false); + static const char *const why[] = { + "", "lost the FM-1 before writing anything", + "this is not an FM-1 (chip key / flash ID)", + "a sector could not be written - the firmware region is INCOMPLETE; repeat the rescue", + "the final read-back does not match - repeat the rescue", + }; + dlog("RESCUE: ERROR at %06lX: %s", (unsigned long)addr, why[e]); + dlog("RESCUE: %s", ar_describe()); +} + +static bool read_sector(uint32_t addr) { + uint16_t chunk = jl_read_chunk(); + for (uint32_t off = 0; off < JL_SECTOR_SIZE; off += chunk) { + uint16_t n = (JL_SECTOR_SIZE - off) < chunk ? (uint16_t)(JL_SECTOR_SIZE - off) : chunk; + if (!jl_flash_read(addr + off, n, &sec[off])) return false; + } + return true; +} + +// One pass over the region: write every sector that differs. Returns false +// (after fail()) on an error. +static bool write_pass(const uint8_t *image, uint32_t base, uint32_t len) { + n_written = n_same = 0; + phase = PH_WRITE; + for (uint32_t off = 0; off < len; off += JL_SECTOR_SIZE) { + uint32_t addr = base + off; + cur_sector = off / JL_SECTOR_SIZE + 1; + const uint8_t *want = image + off; + rgb(false, false, (off / JL_SECTOR_SIZE) & 1); + if (!read_sector(addr)) { + fail(any_written ? E_WRITE : E_LINK, addr); + return false; + } + if (memcmp(sec, want, JL_SECTOR_SIZE) == 0) { + n_same++; + continue; + } + bool ok = false; + for (int t = 0; t < WRITE_TRIES && !ok; t++) { + any_written = true; + ok = jl_flash_write_sector(addr, want); + if (!ok) { + dlog("RESCUE: sector %06lX attempt %d failed", (unsigned long)addr, t + 1); + if (!fm1_host_uboot_ready()) break; + } + } + if (!ok) { + fail(E_WRITE, addr); + return false; + } + n_written++; + if (n_written % 16 == 1) { + dlog("RESCUE: wrote %06lX (%lu written, %lu already right)", (unsigned long)addr, + (unsigned long)n_written, (unsigned long)n_same); + } + } + return true; +} + +static bool verify_pass(const uint8_t *image, uint32_t base, uint32_t len) { + phase = PH_VERIFY; + for (uint32_t off = 0; off < len; off += JL_SECTOR_SIZE) { + cur_sector = off / JL_SECTOR_SIZE + 1; + rgb(false, (off / JL_SECTOR_SIZE) & 1, true); + if (!read_sector(base + off) || memcmp(sec, image + off, JL_SECTOR_SIZE) != 0) { + dlog("RESCUE: verify mismatch or read error at %06lX", (unsigned long)(base + off)); + return false; + } + } + return true; +} + +static void run(void) { + const pl_header_t *h = payload_header(); + const uint8_t *image = payload_image(); + uint64_t t0 = time_us_64(); + state = AR_RUN; + phase = PH_CHECK; + cur_sector = 0; + rgb(false, false, true); + dlog("RESCUE: FM-1 in boot mode - restoring %s", h->label); + + if (!jl_have_loader() && !jl_loader_load(0, payload_loader(), JL_LOADER_SIZE)) { + fail(E_LINK, 0); + return; + } + jl_info_t info; + if (!jl_info(&info)) { + fail(E_LINK, 0); + return; + } + dlog("RESCUE: chip key %04X, type %u, flash id %06lX", info.chip_key, info.dev_type, + (unsigned long)info.flash_id); + if (info.chip_key != JL_CHIP_KEY || + (info.flash_id != JL_FLASH_ID && info.flash_id != FLASH_ID_ALT)) { + fail(E_CHIP, 0); + return; + } + + // The boot head is never written; log what it is, for the record. + uint32_t head_crc = 0; + for (uint32_t a = 0; a < JL_WRITE_MIN; a += JL_SECTOR_SIZE) { + if (!read_sector(a)) { + fail(E_LINK, a); + return; + } + head_crc = pl_crc32(sec, JL_SECTOR_SIZE, head_crc); + } + dlog("RESCUE: boot head 0x0000..0x3FFF crc32 %08lX (not written)", (unsigned long)head_crc); + + for (int pass = 0; pass < 2; pass++) { + if (!write_pass(image, h->image_addr, h->image_len)) return; + dlog("RESCUE: pass %d: %lu sectors written, %lu already right", pass + 1, + (unsigned long)n_written, (unsigned long)n_same); + if (n_written == 0 || verify_pass(image, h->image_addr, h->image_len)) { + state = AR_DONE; + phase = PH_IDLE; + rgb(false, true, false); + dlog("RESCUE: DONE in %.1f s. Switch the FM-1 OFF, remove the wires, switch it ON.", + (time_us_64() - t0) / 1e6); + return; + } + if (!fm1_host_uboot_ready()) break; + } + fail(E_VERIFY, 0); +} + +void ar_task(void) { + static uint64_t mount_seen_us; + static bool was_mounted, softkey_sent; + uint64_t now = time_us_64(); + bool blink_slow = (now / 400000) & 1; + bool blink_fast = (now / 120000) & 1; + + switch (state) { + case AR_OFF: + case AR_BOOT: + return; + case AR_BAD_PAYLOAD: +#if FM1T_LED_MONO + rgb(blink_fast, false, false); // one LED: the same as an error +#else + rgb(blink_slow, false, !blink_slow); +#endif + return; + case AR_DONE: + rgb(false, true, false); + return; + case AR_ERROR: + rgb(blink_fast, false, false); + return; + case AR_RUN: + return; + case AR_WAIT: + break; + } + + bool mounted = fm1_pio_host_mounted(); + if (mounted && !was_mounted) { + mount_seen_us = now; + softkey_sent = false; + foreign = false; + } + was_mounted = mounted; + + if (fm1_host_uboot_ready()) { + run(); + return; + } + if (mounted && fm1_host_v15_mounted() && !softkey_sent && + now - mount_seen_us > SOFTKEY_DELAY_MS * 1000ull) { + softkey_sent = true; + dlog("RESCUE: stock V15 is running - sending the soft key to enter boot mode"); + fm1_host_softkey(); + } + if (mounted && !fm1_host_v15_mounted() && !foreign && + now - mount_seen_us > FOREIGN_AFTER_MS * 1000ull) { + foreign = true; + dlog("RESCUE: a device is attached but it is neither UBOOT nor stock V15. Switch the " + "FM-1 OFF, unplug and re-plug this board, then switch the FM-1 ON."); + } + if (mounted && foreign) { +#if FM1T_LED_MONO + rgb((now / 100000) % 10 == 0, false, false); // one LED: a short flash every second +#else + rgb(true, false, true); +#endif + } else { + rgb(blink_slow, blink_slow, false); + } +} diff --git a/rescue/firmware/src/autorescue.h b/rescue/firmware/src/autorescue.h new file mode 100644 index 00000000..b9e251d3 --- /dev/null +++ b/rescue/firmware/src/autorescue.h @@ -0,0 +1,58 @@ +#pragma once + +// Stand-alone rescue: with a valid payload (payload.h) in the RP2040's flash, +// the board restores the FM-1 on its own, with no computer program: +// +// 1. USB_KEY at power-on (recovery.c), or the V15 soft key if the FM-1 is +// already running stock V15, puts the FM-1 in its mask-ROM UBOOT. +// 2. The embedded wl82loader is uploaded, the chip key (0x980F) and flash +// ID (0x856014 / 0xB36014) are checked. +// 3. Every 4 KiB sector of 0x4000..0x92FFF that differs from the payload is +// erased, written and read back (jl_flash_write_sector). Nothing below +// 0x4000 or from 0x93000 up is ever written (settings, sounds, songs and +// the boot head stay as they are). +// 4. A final read of the whole region is compared with the payload. +// +// LED (one colour or pattern per state; core 1 only): +// yellow, blinking waiting for the FM-1: switch it on +// yellow, steady the FM-1 answered, entering boot mode +// blue, flickering reading / writing +// green, steady done: switch the FM-1 off and on again +// red, fast blinking error (see the console log); nothing below 0x4000 +// was touched; repeat the procedure +// purple, steady the FM-1 runs a firmware that has no soft key: +// switch it off, re-plug the board, switch it on +// red/blue alternating the payload is damaged: rebuild the .uf2 +// +// One-LED boards (Raspberry Pi Pico, FM1T_LED_MONO): slow blink = waiting, +// flicker = working, steady = done, fast blink = error or damaged payload, +// a short flash every second = another firmware is running on the FM-1. + +#include + +typedef enum { + AR_OFF, // no payload: plain Transporter + AR_BOOT, // the payload is not checked yet (the first moments after power-on) + AR_WAIT, // waiting for UBOOT + AR_RUN, + AR_DONE, + AR_ERROR, + AR_BAD_PAYLOAD, +} ar_state_t; + +// core 1, before recovery: checks the payload. +void ar_init(void); + +// core 1, from the host loop. +void ar_task(void); + +bool ar_enabled(void); +ar_state_t ar_state(void); +const char *ar_describe(void); // core 1 + +// One status line (no newline) for the data port's `rescue` request; safe on +// core 0 while core 1 works: +// state=[ foreign=1] phase= sector=/143 written= same= err= addr= +void ar_status_line(char *s, unsigned n); diff --git a/rescue/firmware/src/jieli_uboot.c b/rescue/firmware/src/jieli_uboot.c new file mode 100644 index 00000000..8f0997bc --- /dev/null +++ b/rescue/firmware/src/jieli_uboot.c @@ -0,0 +1,336 @@ +// JieLi WL82 UBOOT1.00 / LoaderV2 protocol, read-only subset. +// Ported from jl-uboot-tool (jltech/uboot.py, cipher.py, crc.py) and the +// fm-1-research-lab flow in tools/fm1_uboot_restore.py. + +#include "jieli_uboot.h" + +#include + +#include "pico/stdlib.h" + +#include "log.h" +#include "pio_host.h" + +#define LOADER_ADDR 0x1C02000u +#define LOADER_ARG 0x0001 + +// ROM UBOOT1.00 +#define CMD_WRITE_MEMORY 0xFB06 +#define CMD_READ_MEMORY 0xFD07 +#define CMD_JUMP 0xFB08 +// LoaderV2 +#define CMD_ERASE_SECTOR 0xFB01 +#define CMD_WRITE_FLASH 0xFB04 +#define CMD_READ_FLASH 0xFD05 +#define CMD_READ_KEY 0xFC09 +#define CMD_GET_ONLINE_DEVICE 0xFC0A +#define CMD_GET_USB_BUFF_SIZE 0xFC14 +#define CMD_RUN_APP 0xFC0C + +#define KEEPALIVE_MS 1000 // the loader resets the chip after ~3 s without a command + +static uint8_t loader_buf[JL_LOADER_SIZE]; // uploaded by the host (fm1t.py) +static uint32_t loader_len; +static bool loader_running; +static uint16_t read_chunk = JL_IO_SIZE; +static uint64_t last_cmd_us; + +static uint8_t __attribute__((aligned(4))) resp[16]; +static uint8_t __attribute__((aligned(4))) block[JL_IO_SIZE]; + +void jl_reset(void) { + loader_running = false; + read_chunk = JL_IO_SIZE; +} + +bool jl_have_loader(void) { + return loader_len == JL_LOADER_SIZE; +} + +bool jl_loader_load(uint32_t off, const uint8_t *data, uint32_t len) { + if (off == 0) loader_len = 0; + if (off != loader_len || len > JL_LOADER_SIZE - off) return false; + memcpy(&loader_buf[off], data, len); + loader_len += len; + return true; +} + +// CRC-16/XMODEM (poly 0x1021, no reflection), with caller-supplied init. +uint16_t jl_crc16(const uint8_t *data, uint32_t len, uint16_t crc) { + for (uint32_t i = 0; i < len; i++) { + crc ^= (uint16_t)data[i] << 8; + for (int b = 0; b < 8; b++) { + crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1); + } + } + return crc; +} + +// jl_crc_cipher with key 0xFFFFFFFF. The magic is a fixed 16-byte GB2312 +// string from the JieLi tools. +static void jl_crc_cipher(uint8_t *buf, uint32_t len) { + static const uint8_t magic[16] = { + 0xC3, 0xCF, 0xC0, 0xE8, 0xCE, 0xD2, 0xB0, 0xAE, + 0xC4, 0xE3, 0xA3, 0xAC, 0xD3, 0xF1, 0xC1, 0xD6, + }; + static const uint8_t key_hi[2] = {0xFF, 0xFF}; + uint16_t crc = jl_crc16(key_hi, 2, 0xFFFF); + for (uint32_t i = 0; i < len; i++) { + crc = jl_crc16(&magic[i % 16], 1, crc); + buf[i] ^= (uint8_t)crc; + } +} + +static void put_be32(uint8_t *p, uint32_t v) { + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +// CDB = cmd (u16 BE) + args, padded with 0xFF to 16 bytes. +static void make_cdb(uint8_t cdb[16], uint16_t cmd, const uint8_t *args, uint8_t nargs) { + memset(cdb, 0xFF, 16); + cdb[0] = (uint8_t)(cmd >> 8); + cdb[1] = (uint8_t)cmd; + memcpy(&cdb[2], args, nargs); +} + +// cmd_exec: 16-byte data-IN, resp[0:2] echoes the command. +static bool cmd_exec(uint16_t cmd, const uint8_t *args, uint8_t nargs) { + uint8_t cdb[16]; + uint32_t got = 0; + make_cdb(cdb, cmd, args, nargs); + last_cmd_us = time_us_64(); + if (!fm1_host_bot(cdb, 16, true, resp, sizeof(resp), &got)) { + dlog("JL: cmd %04X failed", cmd); + return false; + } + uint16_t echo = (uint16_t)(resp[0] << 8 | resp[1]); + if (echo != cmd) { + dlog("JL: cmd %04X answered as %04X", cmd, echo); + return false; + } + return true; +} + +bool jl_ensure_loader(void) { + if (loader_running) return true; + if (!fm1_host_uboot_ready()) { + dlog("JL: no UBOOT mounted"); + return false; + } + if (!jl_have_loader()) { + dlog("JL: wl82loader not uploaded (fm1t.py --loader)"); + return false; + } + dlog("JL: uploading wl82loader (%u bytes) to %08lX", (unsigned)JL_LOADER_SIZE, + (unsigned long)LOADER_ADDR); + + // The blob is shipped already ciphered: send it raw, 512 bytes at a time. + for (uint32_t off = 0; off < JL_LOADER_SIZE; off += JL_IO_SIZE) { + uint16_t n = (uint16_t)((JL_LOADER_SIZE - off) < JL_IO_SIZE + ? (JL_LOADER_SIZE - off) : JL_IO_SIZE); + memcpy(block, &loader_buf[off], n); + + uint8_t args[9]; + put_be32(args, LOADER_ADDR + off); + args[4] = (uint8_t)(n >> 8); + args[5] = (uint8_t)n; + args[6] = 0x00; + uint16_t crc = jl_crc16(block, n, 0); + args[7] = (uint8_t)crc; // LE + args[8] = (uint8_t)(crc >> 8); + + uint8_t cdb[16]; + make_cdb(cdb, CMD_WRITE_MEMORY, args, sizeof(args)); + if (!fm1_host_bot(cdb, 16, false, block, n, NULL)) { + dlog("JL: loader block at +%lu failed", (unsigned long)off); + return false; + } + } + + uint8_t args[6]; + put_be32(args, LOADER_ADDR); + args[4] = (uint8_t)(LOADER_ARG >> 8); + args[5] = (uint8_t)LOADER_ARG; + if (!cmd_exec(CMD_JUMP, args, sizeof(args))) { + dlog("JL: jump to loader failed"); + return false; + } + + loader_running = true; + last_cmd_us = time_us_64(); + dlog("JL: loader running"); + + // Read-only query; falls back to 512-byte reads if unsupported. + if (cmd_exec(CMD_GET_USB_BUFF_SIZE, NULL, 0)) { + uint32_t size = (uint32_t)resp[2] << 24 | (uint32_t)resp[3] << 16 | + (uint32_t)resp[4] << 8 | resp[5]; + uint32_t chunk = size > JL_READ_MAX ? JL_READ_MAX : size; + chunk -= chunk % JL_IO_SIZE; + if (chunk >= JL_IO_SIZE) read_chunk = (uint16_t)chunk; + dlog("JL: loader USB buffer %lu bytes, reading %u at a time", (unsigned long)size, + read_chunk); + } + return true; +} + +uint16_t jl_read_chunk(void) { + return read_chunk; +} + +bool jl_info(jl_info_t *info) { + if (!jl_ensure_loader()) return false; + + uint8_t args[4]; + put_be32(args, 0x00AC6900); + if (!cmd_exec(CMD_READ_KEY, args, sizeof(args))) return false; + // payload = resp[2:]; key = cipher(reverse(payload[4:6])) as u16 LE + uint8_t k[2] = {resp[2 + 5], resp[2 + 4]}; + jl_crc_cipher(k, 2); + info->chip_key = (uint16_t)(k[0] | k[1] << 8); + + if (!cmd_exec(CMD_GET_ONLINE_DEVICE, NULL, 0)) return false; + const uint8_t *p = &resp[2]; + info->dev_type = p[0]; + info->flash_id = (uint32_t)p[2] | (uint32_t)p[3] << 8 | (uint32_t)p[4] << 16 | + (uint32_t)p[5] << 24; + return true; +} + +bool jl_flash_read(uint32_t addr, uint16_t len, uint8_t *buf) { + if (len > JL_READ_MAX) return false; + if (!jl_ensure_loader()) return false; + + uint8_t args[6]; + put_be32(args, addr); + args[4] = (uint8_t)(len >> 8); + args[5] = (uint8_t)len; + + uint8_t cdb[16]; + uint32_t got = 0; + make_cdb(cdb, CMD_READ_FLASH, args, sizeof(args)); + last_cmd_us = time_us_64(); + if (!fm1_host_bot(cdb, 16, true, buf, len, &got) || got != len) { + dlog("JL: flash read %06lX+%u failed (got %lu)", (unsigned long)addr, len, + (unsigned long)got); + return false; + } + return true; +} + +bool jl_flash_write_sector(uint32_t addr, const uint8_t *data) { + if (addr < JL_WRITE_MIN || addr >= JL_WRITE_END || (addr % JL_SECTOR_SIZE)) { + dlog("JL: write to %06lX refused (allowed: %06X-%06X, 4 KiB aligned)", + (unsigned long)addr, JL_WRITE_MIN, JL_WRITE_END); + return false; + } + if (!jl_ensure_loader()) return false; + + uint8_t args[9]; + put_be32(args, addr); + if (!cmd_exec(CMD_ERASE_SECTOR, args, 4)) { + dlog("JL: erase %06lX failed", (unsigned long)addr); + return false; + } + + for (uint32_t off = 0; off < JL_SECTOR_SIZE; off += JL_IO_SIZE) { + memcpy(block, &data[off], JL_IO_SIZE); + put_be32(args, addr + off); + args[4] = (uint8_t)(JL_IO_SIZE >> 8); + args[5] = (uint8_t)JL_IO_SIZE; + args[6] = 0x00; + uint16_t crc = jl_crc16(block, JL_IO_SIZE, 0); + args[7] = (uint8_t)crc; // LE + args[8] = (uint8_t)(crc >> 8); + + uint8_t cdb[16]; + make_cdb(cdb, CMD_WRITE_FLASH, args, sizeof(args)); + last_cmd_us = time_us_64(); + if (!fm1_host_bot(cdb, 16, false, block, JL_IO_SIZE, NULL)) { + dlog("JL: write %06lX failed", (unsigned long)(addr + off)); + return false; + } + } + + for (uint32_t off = 0; off < JL_SECTOR_SIZE; off += JL_IO_SIZE) { + if (!jl_flash_read(addr + off, JL_IO_SIZE, block)) return false; + if (memcmp(block, &data[off], JL_IO_SIZE) != 0) { + dlog("JL: verify %06lX failed", (unsigned long)(addr + off)); + return false; + } + } + return true; +} + +bool jl_run_app(void) { + if (!loader_running) return false; + uint8_t args[4]; + put_be32(args, 1); + dlog("JL: RUN_APP - the FM-1 leaves UBOOT and boots its firmware"); + // The chip may reset before it answers; either way the loader is gone. + cmd_exec(CMD_RUN_APP, args, sizeof(args)); + loader_running = false; + return true; +} + +void jl_keepalive(void) { + if (!loader_running || !fm1_host_uboot_ready()) return; + if (time_us_64() - last_cmd_us < KEEPALIVE_MS * 1000ull) return; + if (!cmd_exec(CMD_GET_ONLINE_DEVICE, NULL, 0)) dlog("JL: keepalive failed"); +} + +//--------------------------------------------------------------------+ +// RAM-run (ROM UBOOT1.00 stage only; requested by fm-1-research-lab) +//--------------------------------------------------------------------+ +// WL82 UBOOT1.00 runs every memory write/read through jl_crc_cipher, per +// transfer. These refuse to run once the loader is up: it lives at +// LOADER_ADDR, the same address RAM-run images use, and would be clobbered. + +bool jl_loader_running(void) { + return loader_running; +} + +bool jl_rom_mem_write(uint32_t addr, const uint8_t *data, uint16_t len) { + if (loader_running || !len || len > JL_IO_SIZE) return false; + memcpy(block, data, len); + jl_crc_cipher(block, len); + uint8_t args[9]; + put_be32(args, addr); + args[4] = (uint8_t)(len >> 8); + args[5] = (uint8_t)len; + args[6] = 0x00; + uint16_t crc = jl_crc16(block, len, 0); + args[7] = (uint8_t)crc; // LE + args[8] = (uint8_t)(crc >> 8); + uint8_t cdb[16]; + make_cdb(cdb, CMD_WRITE_MEMORY, args, sizeof(args)); + last_cmd_us = time_us_64(); + return fm1_host_bot(cdb, 16, false, block, len, NULL); +} + +bool jl_rom_mem_read(uint32_t addr, uint16_t len, uint8_t *out) { + if (loader_running || !len || len > JL_IO_SIZE) return false; + uint8_t args[6]; + put_be32(args, addr); + args[4] = (uint8_t)(len >> 8); + args[5] = (uint8_t)len; + uint8_t cdb[16]; + make_cdb(cdb, CMD_READ_MEMORY, args, sizeof(args)); + uint32_t got = 0; + last_cmd_us = time_us_64(); + if (!fm1_host_bot(cdb, 16, true, block, len, &got) || got != len) return false; + jl_crc_cipher(block, len); + memcpy(out, block, len); + return true; +} + +bool jl_rom_jump(uint32_t addr, uint16_t arg) { + if (loader_running) return false; + uint8_t args[6]; + put_be32(args, addr); + args[4] = (uint8_t)(arg >> 8); + args[5] = (uint8_t)arg; + return cmd_exec(CMD_JUMP, args, sizeof(args)); +} diff --git a/rescue/firmware/src/jieli_uboot.h b/rescue/firmware/src/jieli_uboot.h new file mode 100644 index 00000000..e6370b8d --- /dev/null +++ b/rescue/firmware/src/jieli_uboot.h @@ -0,0 +1,76 @@ +#pragma once + +#include +#include + +// JieLi WL82 UBOOT1.00 + wl82loader (LoaderV2), read-only subset. +// See docs/PROTOCOL.md. Core 1 only. +// +// Writes are limited to whole 4 KiB sectors inside the application area +// [JL_WRITE_MIN, JL_WRITE_END). Header/SPL/isd_config below 0x4000 and the +// device data from 0x93000 up are refused here, whatever the host asks. +// Deliberately absent: block/chip erase, chip-key write. RAM writes exist only +// for the loader upload and the ROM-stage RAM-run calls below (RAM, never flash). + +#define JL_CHIP_KEY 0x980F +#define JL_FLASH_ID 0x856014 +#define JL_FLASH_SIZE (1024u * 1024u) +#define JL_IO_SIZE 512 // loader upload and flash write chunk +#define JL_READ_MAX 4096 // largest READ_FLASH we issue (see jl_read_chunk) +#define JL_SECTOR_SIZE 0x1000 +#define JL_WRITE_MIN 0x4000 +#define JL_WRITE_END 0x93000 + +typedef struct { + uint16_t chip_key; + uint8_t dev_type; + uint32_t flash_id; +} jl_info_t; + +// Forget loader state (call on every new mount). +void jl_reset(void); + +#define JL_LOADER_SIZE 24064 // wl82loader.bin + +// True once the host has uploaded the whole loader. +bool jl_have_loader(void); + +// Stores a loader chunk; chunks must arrive in order, starting at off 0. +bool jl_loader_load(uint32_t off, const uint8_t *data, uint32_t len); + +// Uploads wl82loader to RAM and jumps to it, once per mount. +bool jl_ensure_loader(void); + +bool jl_info(jl_info_t *info); + +// READ_FLASH size to use: the loader's USB buffer size (GET_USB_BUFF_SIZE), +// clamped to [JL_IO_SIZE, JL_READ_MAX] in 512-byte steps. Each Bulk-Only +// command costs at least three 1 ms frames on the PIO host (CBW, data, CSW), +// so larger reads are what make dumps faster. +uint16_t jl_read_chunk(void); + +// Reads len (<= JL_READ_MAX) bytes of SPI flash at addr into buf. +// buf must be word-aligned RAM. +bool jl_flash_read(uint32_t addr, uint16_t len, uint8_t *buf); + +// Erases one 4 KiB sector, writes it and reads it back. Returns false (and +// touches nothing) if addr is outside the writable area or misaligned. +bool jl_flash_write_sector(uint32_t addr, const uint8_t *data); + +// LoaderV2 RUN_APP: leave UBOOT and boot the installed firmware. No write. +bool jl_run_app(void); + +// Sends a harmless GET_ONLINE_DEVICE if the loader has been idle for 1 s. +// The loader resets the chip after ~3 s without a command. +void jl_keepalive(void); + +uint16_t jl_crc16(const uint8_t *data, uint32_t len, uint16_t crc); + +// RAM-run, ROM UBOOT1.00 stage only (refused once the loader runs). Memory +// data is ciphered/deciphered here; len <= JL_IO_SIZE. jl_rom_jump calls the +// code like a function and fails if it does not return within the host's +// transfer timeout (the ROM resets the chip after ~2 s anyway). +bool jl_loader_running(void); +bool jl_rom_mem_write(uint32_t addr, const uint8_t *data, uint16_t len); +bool jl_rom_mem_read(uint32_t addr, uint16_t len, uint8_t *out); +bool jl_rom_jump(uint32_t addr, uint16_t arg); diff --git a/rescue/firmware/src/log.c b/rescue/firmware/src/log.c new file mode 100644 index 00000000..7a297d30 --- /dev/null +++ b/rescue/firmware/src/log.c @@ -0,0 +1,88 @@ +#include "log.h" + +#include +#include + +#include "pico/stdlib.h" +#include "pico/stdio/driver.h" +#include "hardware/sync.h" +#include "tusb.h" + +#define LOG_BUF_SIZE 8192 // power of two + +static char buf[LOG_BUF_SIZE]; +static volatile uint32_t head; // written by producers (under the stdio mutex) +static volatile uint32_t tail; // written by core 0 only +static volatile uint32_t dropped; +static uint64_t t0; + +static void log_out_chars(const char *s, int len) { + uint32_t h = head; + for (int i = 0; i < len; i++) { + if (h - tail >= LOG_BUF_SIZE) { + dropped++; + continue; + } + buf[h & (LOG_BUF_SIZE - 1)] = s[i]; + h++; + } + __dmb(); + head = h; +} + +static stdio_driver_t log_driver = { + .out_chars = log_out_chars, +#if PICO_STDIO_ENABLE_CRLF_SUPPORT + .crlf_enabled = PICO_STDIO_DEFAULT_CRLF, +#endif +}; + +void log_init(void) { + t0 = time_us_64(); + stdio_set_driver_enabled(&log_driver, true); +} + +uint32_t log_dropped(void) { + return dropped; +} + +void log_drain(void) { + if (!tud_cdc_n_connected(0)) { + // Keep the newest output; nobody is listening yet. + uint32_t h = head; + if (h - tail > LOG_BUF_SIZE / 2) tail = h - LOG_BUF_SIZE / 2; + return; + } + + for (;;) { + uint32_t h = head; + __dmb(); + uint32_t t = tail; + if (h == t) break; + + uint32_t avail = tud_cdc_n_write_available(0); + if (!avail) break; + + uint32_t idx = t & (LOG_BUF_SIZE - 1); + uint32_t n = h - t; + if (n > LOG_BUF_SIZE - idx) n = LOG_BUF_SIZE - idx; + if (n > avail) n = avail; + + n = tud_cdc_n_write(0, &buf[idx], n); + tail = t + n; + } + + tud_cdc_n_write_flush(0); +} + +void dlog(const char *fmt, ...) { + // Format the whole line first so lines from the two cores never interleave. + char line[256]; + int n = snprintf(line, sizeof(line), "[%9llu us] ", + (unsigned long long)(time_us_64() - t0)); + va_list ap; + va_start(ap, fmt); + vsnprintf(line + n, sizeof(line) - (size_t)n, fmt, ap); + va_end(ap); + puts(line); +} diff --git a/rescue/firmware/src/log.h b/rescue/firmware/src/log.h new file mode 100644 index 00000000..6046d7ec --- /dev/null +++ b/rescue/firmware/src/log.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +// stdout goes into a lock-free ring buffer so the timing-sensitive recovery +// and host code on core 1 never waits on USB. Core 0 drains it to the CDC +// port with log_drain(). + +void log_init(void); +void log_drain(void); +uint32_t log_dropped(void); + +// Time-stamped log line, relative to log_init(). +void dlog(const char *fmt, ...) __attribute__((format(printf, 1, 2))); diff --git a/rescue/firmware/src/main.c b/rescue/firmware/src/main.c new file mode 100644 index 00000000..9c182727 --- /dev/null +++ b/rescue/firmware/src/main.c @@ -0,0 +1,139 @@ +// FM-1 Transporter - USB_KEY recovery + PIO USB host for the JieLi UBOOT +// Seeed XIAO RP2040: GP0/D6 -> FM-1 D+, GP1/D7 -> FM-1 D-, GND -> GND. +// FM-1 VBUS is not connected in the current battery-powered prototype. +// +// core 0: native USB device (Mac-facing CDC console) and log output +// core 1: USB_KEY recovery on PIO0 -> handoff -> Pico-PIO-USB host on PIO1 +// +// GP0/GP1 have exactly one owner at a time, and both owners live on core 1: +// recovery hands the bus to the host in one call sequence, with the ROM +// pulses running until the moment the host takes the pins. + +#include + +#include "pico/stdlib.h" +#include "pico/multicore.h" +#include "hardware/clocks.h" +#include "hardware/watchdog.h" +#include "tusb.h" + +#include "autorescue.h" +#include "log.h" +#include "pio_host.h" +#include "recovery.h" +#include "transporter_proto.h" + +#define CONSOLE_WAIT_MS 10000 +#define ATTACHED_PULSE_MS 6000 // as in the runs where V15 enumerated +#define REKEY_MAGIC 0x4B455931 // "KEY1" in watchdog scratch 0: force USB_KEY + +// Reboots the transporter straight into USB_KEY mode even if D+ is pulled up, +// for a unit stuck with its USB up. The FM-1 then needs one power cycle. +void fm1_rekey(void) { + watchdog_hw->scratch[0] = REKEY_MAGIC; + watchdog_reboot(0, 0, 50); +} + +static volatile bool console_ready; + +static void core1_main(void) { + // The payload first: until then the data port reports "boot", never "off" (which the Android app + // takes as "no payload, reprogram this board" - it did, in a loop, during the console wait). + ar_init(); + for (int i = 0; i < CONSOLE_WAIT_MS / 100 && !console_ready; i++) { + sleep_ms(100); + } + sleep_ms(200); + + printf("\nFM-1 Transporter\n"); +#if FM1T_BOARD_DEBUGPROBE + printf("Debug Probe: D+=GP4 (UART TX, orange) D-=GP6 (UART RX, yellow), PIO host on PIO1\n"); +#else + printf("XIAO RP2040: D+=GP0/D6 D-=GP1/D7, PIO host on PIO1\n"); +#endif + printf("If the FM-1 runs stock V15, leave it on: fm1t enters UBOOT via the soft key.\n"); + printf("Otherwise switch it OFF, and ON again once the key is running.\n"); + + recovery_init(); +#if FM1T_HOST_ONLY + // Host bring-up without the key path: attach any full-speed device, or an + // FM-1 already in UBOOT (e.g. via the V15 USB-MIDI soft key). + dlog("HOST-ONLY build: skipping USB_KEY recovery"); +#else + bool force_key = watchdog_hw->scratch[0] == REKEY_MAGIC; + watchdog_hw->scratch[0] = 0; + if (force_key) { + // A loader or UBOOT may still hold D+ for a moment after we stop + // talking to it; keying into that would mistake it for a fresh ROM. + dlog("REKEY: waiting for D+ to drop (loader watchdog / power-off)"); + bool dropped = recovery_wait_detached(15000); + dlog("REKEY: %s; USB_KEY forced now", + dropped ? "D+ dropped" : "D+ still high after 15 s - power-cycle the FM-1"); + recovery_run(); + } else if (recovery_target_attached()) { + dlog("D+ already pulled up (FM-1 app or a waiting UBOOT) - skipping USB_KEY"); + recovery_pulses_only(ATTACHED_PULSE_MS); + } else { + recovery_run(); + } +#endif + + // The ROM is holding D+ up and our pulses are still running. Swap owners + // with the smallest possible gap. + uint64_t t_release = time_us_64(); + recovery_release_bus(); + fm1_pio_host_start(); + uint64_t t_host = time_us_64(); + + rgb(true, true, true); + dlog("HANDOFF: pulses stopped, PIO host started in %llu us", + (unsigned long long)(t_host - t_release)); + + for (;;) { + fm1_pio_host_task(); + } +} + +// Console (CDC 0): one-letter diagnostic commands, each on its own line. +// Anything longer is answered with the help text by fm1_pio_host_command(). +static void console_rx(const char *buf, uint32_t n) { + static char line[8]; + static uint32_t len; + for (uint32_t i = 0; i < n; i++) { + char c = buf[i]; + if (c == '\r' || c == '\n') { + if (len) fm1_pio_host_command(len == 1 ? line[0] : '?'); + len = 0; + } else if (len < sizeof(line)) { + line[len++] = c; + } + } +} + +void tud_cdc_rx_cb(uint8_t itf) { + char buf[64]; + uint32_t n = tud_cdc_n_read(itf, buf, sizeof(buf)); + if (itf == 0) { + console_rx(buf, n); + } else { + fm1_proto_rx(buf, n); + } +} + +int main(void) { + // Pico-PIO-USB needs clk_sys to be a multiple of 12 MHz. The recovery + // PIO dividers are derived from clk_sys, so they follow automatically. + set_sys_clock_khz(120000, true); + + log_init(); + tud_init(0); + + multicore_launch_core1(core1_main); + + for (;;) { + tud_task(); + console_ready = tud_cdc_n_connected(0); + log_drain(); + fm1_proto_drain(); + } +} diff --git a/rescue/firmware/src/payload.c b/rescue/firmware/src/payload.c new file mode 100644 index 00000000..cc0d2b71 --- /dev/null +++ b/rescue/firmware/src/payload.c @@ -0,0 +1,76 @@ +#include "payload.h" + +#include + +#include "hardware/flash.h" +#include "pico/stdlib.h" + +#include "jieli_uboot.h" +#include "log.h" + +#define PL_BASE ((const uint8_t *)(XIP_BASE + PL_FLASH_OFFSET)) + +static uint32_t crc_table[256]; + +uint32_t pl_crc32(const uint8_t *data, uint32_t len, uint32_t crc) { + if (!crc_table[1]) { + for (uint32_t i = 0; i < 256; i++) { + uint32_t c = i; + for (int k = 0; k < 8; k++) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : c >> 1; + crc_table[i] = c; + } + } + crc = ~crc; + for (uint32_t i = 0; i < len; i++) crc = crc_table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8); + return ~crc; +} + +const pl_header_t *payload_header(void) { + return (const pl_header_t *)PL_BASE; +} + +const uint8_t *payload_loader(void) { + return PL_BASE + payload_header()->loader_off; +} + +const uint8_t *payload_image(void) { + return PL_BASE + payload_header()->image_off; +} + +pl_status_t payload_check(void) { + const pl_header_t *h = payload_header(); + if (memcmp(h->magic, PL_MAGIC, sizeof(h->magic)) != 0) { + dlog("RESCUE: no payload at +0x%06X - plain Transporter mode", PL_FLASH_OFFSET); + return PL_NONE; + } + if (pl_crc32((const uint8_t *)h, 252, 0) != h->hdr_crc32) { + dlog("RESCUE: payload header CRC mismatch"); + return PL_BAD; + } + if (h->version != PL_VERSION || h->hdr_size != sizeof(pl_header_t) || + h->loader_off != PL_LOADER_OFF || h->loader_len != JL_LOADER_SIZE || + h->image_off != PL_IMAGE_OFF || h->image_addr != PL_IMAGE_ADDR || + h->image_len != PL_IMAGE_LEN || h->label[sizeof(h->label) - 1] != 0) { + dlog("RESCUE: payload layout not supported (v%lu)", (unsigned long)h->version); + return PL_BAD; + } + if (pl_crc32(payload_loader(), h->loader_len, 0) != h->loader_crc32) { + dlog("RESCUE: loader CRC mismatch"); + return PL_BAD; + } + if (pl_crc32(payload_image(), h->image_len, 0) != h->image_crc32) { + dlog("RESCUE: firmware image CRC mismatch"); + return PL_BAD; + } + char sha[17]; + for (int i = 0; i < 8; i++) { + static const char hx[] = "0123456789abcdef"; + sha[2 * i] = hx[h->image_sha256[i] >> 4]; + sha[2 * i + 1] = hx[h->image_sha256[i] & 15]; + } + sha[16] = 0; + dlog("RESCUE: payload OK: %s, 0x%lX bytes for 0x%05lX, sha256 %s..., crc32 %08lX", + h->label, (unsigned long)h->image_len, (unsigned long)h->image_addr, sha, + (unsigned long)h->image_crc32); + return PL_VALID; +} diff --git a/rescue/firmware/src/payload.h b/rescue/firmware/src/payload.h new file mode 100644 index 00000000..3689d832 --- /dev/null +++ b/rescue/firmware/src/payload.h @@ -0,0 +1,58 @@ +#pragma once + +// FM-1 Rescue payload: the firmware to restore and JieLi's loader, stored in +// the RP2040's own flash at PL_FLASH_OFFSET by the rescue builder +// (rescue/fm1-rescue.html), in the same UF2 as this firmware. +// +// Layout (offsets from the start of the payload): +// 0x0000 pl_header_t (256 bytes, little-endian) +// 0x1000 wl82loader.bin (24064 bytes) +// 0x8000 the FM-1 flash region 0x4000..0x92FFF (0x8F000 bytes) +// +// With no valid payload the board is a plain FM-1 Transporter (fm1t.py and +// the web app work as before). With one, it restores the FM-1 by itself. + +#include +#include + +#define PL_FLASH_OFFSET 0x100000u // 1 MiB into the RP2040 flash +#define PL_MAGIC "FM1-RESCUE-PL-1" // 15 chars + NUL = 16 bytes +#define PL_VERSION 1u +#define PL_LOADER_OFF 0x1000u +#define PL_IMAGE_OFF 0x8000u +#define PL_IMAGE_ADDR 0x4000u +#define PL_IMAGE_LEN 0x8F000u + +typedef struct { + char magic[16]; + uint32_t version; + uint32_t hdr_size; // 256 + uint32_t loader_off; + uint32_t loader_len; + uint32_t loader_crc32; + uint32_t image_off; + uint32_t image_addr; // FM-1 flash address of image[0]: 0x4000 + uint32_t image_len; // 0x8F000 + uint32_t image_crc32; + char label[64]; // e.g. "FM-1_015 official V15", NUL-terminated + uint8_t image_sha256[32]; // checked by the builder; logged here + uint8_t reserved[104]; + uint32_t hdr_crc32; // CRC-32 of bytes 0..251 +} pl_header_t; + +_Static_assert(sizeof(pl_header_t) == 256, "pl_header_t must be 256 bytes"); + +typedef enum { + PL_NONE, // no magic: plain Transporter + PL_VALID, + PL_BAD, // magic present but something does not check out: never write +} pl_status_t; + +// Checks the payload (CRCs over all of it, ~50 ms). Call once. +pl_status_t payload_check(void); + +const pl_header_t *payload_header(void); +const uint8_t *payload_loader(void); +const uint8_t *payload_image(void); + +uint32_t pl_crc32(const uint8_t *data, uint32_t len, uint32_t crc); diff --git a/rescue/firmware/src/pio_host.c b/rescue/firmware/src/pio_host.c new file mode 100644 index 00000000..7e53a78d --- /dev/null +++ b/rescue/firmware/src/pio_host.c @@ -0,0 +1,534 @@ +#include "pio_host.h" + +#include +#include + +#include "pico/stdlib.h" +#include "hardware/dma.h" +#include "hardware/gpio.h" +#include "hardware/watchdog.h" +#include "pio_usb.h" +#include "tusb.h" +#include "class/msc/msc.h" + +#include "autorescue.h" +#include "log.h" +#include "jieli_uboot.h" +#include "recovery.h" +#include "transporter_proto.h" + +#define HOST_RHPORT 1 +#define FM1_VID 0x4C4A +#define FM1_PID 0x8057 +#define FM1_V15_PID 0xC755 // stock FM-1 application (USB audio + MIDI) +#define XFER_TIMEOUT_MS 2000 +#define FIRST_CBW_DELAY_MS 1500 // macOS had the device for seconds before its first CBW +#define INQUIRY_RETRY_MS 300 +#define INQUIRY_TRIES 30 +#define ATTACH_STATUS_MS 2000 +// A target that pulls D+ up but never enumerates (V15 or a fresh UBOOT that +// booted under the running host, without the 1 ms pulses) is recovered by +// rebooting the transporter, which pulses first and then hosts again. +#define REATTACH_AFTER_MS 3000 +#define REATTACH_MAX 3 // consecutive reboots without a mount +#define REATTACH_SCRATCH 1 // watchdog scratch register for the count + +static volatile uint8_t mounted_addr; +static volatile bool probe_pending; +static uint64_t host_start_us; +static uint64_t last_status_us; + +static uint8_t ep_in, ep_out, msc_itf; +static tusb_desc_endpoint_t other_bulk_out; // e.g. V15's USB-MIDI OUT, for 'm' +static bool other_bulk_out_open; +static bool mounted_is_v15; +static uint32_t cbw_tag = 1; +static volatile char pending_cmd; +static uint64_t mount_us; +static uint64_t unmounted_since_us; +static int inquiry_tries; // > 0 while the post-mount INQUIRY loop is active +static uint64_t next_inquiry_us; + +static bool bot_cmd(uint8_t daddr, const uint8_t *cdb, uint8_t cdb_len, bool in, void *buf, + uint16_t len, uint32_t *got); + +static CFG_TUSB_MEM_ALIGN uint8_t cfg_buf[512]; +static CFG_TUSB_MEM_ALIGN uint8_t data_buf[512]; +static CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; +static CFG_TUSB_MEM_ALIGN msc_csw_t csw; + +void fm1_pio_host_start(void) { + pio_usb_configuration_t cfg = PIO_USB_DEFAULT_CONFIG; + cfg.pin_dp = PIN_DP; + // PIO0 holds the recovery programs; give the host all of PIO1. + cfg.pio_tx_num = 1; + cfg.pio_rx_num = 1; + // pio_usb claims tx_ch itself and panics if it is taken. + int ch = dma_claim_unused_channel(true); + dma_channel_unclaim(ch); + cfg.tx_ch = (uint8_t)ch; + + tuh_configure(HOST_RHPORT, TUH_CFGID_RPI_PIO_USB_CONFIGURATION, &cfg); + tuh_init(HOST_RHPORT); + + host_start_us = last_status_us = unmounted_since_us = time_us_64(); +} + +bool fm1_pio_host_mounted(void) { + return mounted_addr != 0; +} + +static bool uboot_ready; // INQUIRY answered on the current mount + +bool fm1_host_bot(const uint8_t *cdb, uint8_t cdb_len, bool in, void *buf, uint16_t len, + uint32_t *got) { + uint8_t daddr = mounted_addr; + if (!daddr || !uboot_ready) return false; + return bot_cmd(daddr, cdb, cdb_len, in, buf, len, got); +} + +bool fm1_host_uboot_ready(void) { + return mounted_addr != 0 && uboot_ready; +} + +bool fm1_host_v15_mounted(void) { + return mounted_addr != 0 && mounted_is_v15; +} + +static bool edpt_sync(uint8_t daddr, uint8_t ep, void *buf, uint16_t len, uint32_t *actual); + +// Stock V15's USB-MIDI receive path compares every 8-byte transfer with +// 04 F0 22 24 07 35 xx F7; xx = 7D calls the mask ROM UBOOT1.00 and never +// returns (fm-1-research-lab tools/fm1_softkey.py). Nothing is written. +bool fm1_host_softkey(void) { + static CFG_TUSB_MEM_ALIGN uint8_t pkt[8] = {0x04, 0xF0, 0x22, 0x24, 0x07, 0x35, 0x7D, 0xF7}; + uint8_t daddr = mounted_addr; + if (!daddr || !mounted_is_v15 || !other_bulk_out.bLength) return false; + if (!other_bulk_out_open) other_bulk_out_open = tuh_edpt_open(daddr, &other_bulk_out); + + dlog("SOFTKEY: sending F0 22 24 35 7D F7 to USB-MIDI OUT %02X", + other_bulk_out.bEndpointAddress); + bool sent = false; + for (int i = 0; i < 3 && mounted_addr == daddr; i++) { + // The unit leaves the bus once it takes the key, so later sends may fail. + sent |= edpt_sync(daddr, other_bulk_out.bEndpointAddress, pkt, sizeof(pkt), NULL); + sleep_ms(20); + } + return sent; +} + +void tuh_mount_cb(uint8_t daddr) { + dlog("HOST: device mounted, addr=%u (%.1f ms after host start)", daddr, + (time_us_64() - host_start_us) / 1000.0); + mounted_addr = daddr; + mount_us = time_us_64(); + watchdog_hw->scratch[REATTACH_SCRATCH] = 0; + uboot_ready = false; + jl_reset(); + probe_pending = true; +} + +void tuh_umount_cb(uint8_t daddr) { + dlog("HOST: device addr=%u detached (%.1f ms after mount)", daddr, + (time_us_64() - mount_us) / 1000.0); + mounted_addr = 0; + uboot_ready = false; + mounted_is_v15 = false; + unmounted_since_us = time_us_64(); + probe_pending = false; + inquiry_tries = 0; + rgb(false, false, true); +} + +//--------------------------------------------------------------------+ +// Blocking bulk transfer, run from the core 1 loop (never from a callback) +//--------------------------------------------------------------------+ + +static volatile xfer_result_t xfer_result; +static volatile uint32_t xfer_actual; + +static void xfer_done(tuh_xfer_t *x) { + xfer_actual = x->actual_len; + xfer_result = x->result; +} + +static bool edpt_sync(uint8_t daddr, uint8_t ep, void *buf, uint16_t len, uint32_t *actual) { + xfer_result = XFER_RESULT_INVALID; + xfer_actual = 0; + + tuh_xfer_t x = { + .daddr = daddr, + .ep_addr = ep, + .buflen = len, + .buffer = buf, + .complete_cb = xfer_done, + }; + if (!tuh_edpt_xfer(&x)) { + dlog("HOST: EP %02X submit failed", ep); + return false; + } + + uint64_t deadline = time_us_64() + XFER_TIMEOUT_MS * 1000ull; + while (xfer_result == XFER_RESULT_INVALID) { + tuh_task(); + if (mounted_addr != daddr) { + dlog("HOST: EP %02X abandoned, device gone", ep); + return false; + } + if (time_us_64() > deadline) { + tuh_edpt_abort_xfer(daddr, ep); + dlog("HOST: EP %02X timeout", ep); + return false; + } + } + + if (actual) *actual = xfer_actual; + if (xfer_result != XFER_RESULT_SUCCESS) { + dlog("HOST: EP %02X result %d", ep, xfer_result); + return false; + } + return true; +} + +static bool ctrl_sync(uint8_t daddr, uint8_t type, uint8_t req, uint16_t value, uint16_t index, + void *buf, uint16_t len) { + const tusb_control_request_t setup = { + .bmRequestType = type, + .bRequest = req, + .wValue = value, + .wIndex = index, + .wLength = len, + }; + xfer_result_t result = XFER_RESULT_INVALID; + tuh_xfer_t x = { + .daddr = daddr, + .ep_addr = 0, + .setup = &setup, + .buffer = buf, + .complete_cb = NULL, // blocking + .user_data = (uintptr_t)&result, + }; + if (!tuh_control_xfer(&x)) { + dlog("HOST: control %02X/%02X submit failed", type, req); + return false; + } + if (result != XFER_RESULT_SUCCESS) { + dlog("HOST: control %02X/%02X result %d%s", type, req, result, + result == XFER_RESULT_STALLED ? " (STALL)" : ""); + return false; + } + return true; +} + +// One Bulk-Only Transport command. len == 0 means no data stage. buf must be +// word-aligned RAM. +static bool bot_cmd(uint8_t daddr, const uint8_t *cdb, uint8_t cdb_len, bool in, void *buf, + uint16_t len, uint32_t *got) { + memset(&cbw, 0, sizeof(cbw)); + cbw.signature = MSC_CBW_SIGNATURE; + cbw.tag = cbw_tag++; + cbw.total_bytes = len; + cbw.dir = in ? TUSB_DIR_IN_MASK : 0; + cbw.lun = 0; + cbw.cmd_len = cdb_len; + memcpy(cbw.command, cdb, cdb_len); + + if (!edpt_sync(daddr, ep_out, &cbw, sizeof(cbw), NULL)) { + dlog("HOST: CBW not accepted"); + return false; + } + if (len && !edpt_sync(daddr, in ? ep_in : ep_out, buf, len, got)) return false; + if (!edpt_sync(daddr, ep_in, &csw, sizeof(csw), NULL)) { + dlog("HOST: no CSW"); + return false; + } + + if (csw.signature != MSC_CSW_SIGNATURE || csw.tag != cbw.tag) { + dlog("HOST: bad CSW sig=%08lx tag=%lu", (unsigned long)csw.signature, + (unsigned long)csw.tag); + return false; + } + if (csw.status != 0) { + dlog("HOST: CSW status %u residue %lu", csw.status, (unsigned long)csw.data_residue); + return false; + } + return true; +} + +//--------------------------------------------------------------------+ +// M0 probe: descriptors + INQUIRY, all read-only +//--------------------------------------------------------------------+ + +static void log_string(uint8_t daddr, const char *what, uint8_t idx) { + if (!idx) return; + uint16_t s[64]; + if (tuh_descriptor_get_string_sync(daddr, idx, 0x0409, s, sizeof(s)) != XFER_RESULT_SUCCESS) { + dlog(" %s: ", what); + return; + } + char a[64]; + int n = ((s[0] & 0xff) - 2) / 2; + if (n < 0) n = 0; + if (n > 63) n = 63; + for (int i = 0; i < n; i++) a[i] = (s[1 + i] < 0x80) ? (char)s[1 + i] : '?'; + a[n] = 0; + dlog(" %s: \"%s\"", what, a); +} + +static bool probe_descriptors(uint8_t daddr) { + tusb_desc_device_t dd; + if (tuh_descriptor_get_device_sync(daddr, &dd, sizeof(dd)) != XFER_RESULT_SUCCESS) { + dlog("HOST: device descriptor read failed"); + return false; + } + + dlog("DEVICE DESCRIPTOR OK"); + dlog(" VID=%04X PID=%04X bcdDevice=%04X bcdUSB=%04X", dd.idVendor, dd.idProduct, + dd.bcdDevice, dd.bcdUSB); + dlog(" class=%02X/%02X/%02X ep0=%u configs=%u", dd.bDeviceClass, dd.bDeviceSubClass, + dd.bDeviceProtocol, dd.bMaxPacketSize0, dd.bNumConfigurations); + log_string(daddr, "manufacturer", dd.iManufacturer); + log_string(daddr, "product", dd.iProduct); + log_string(daddr, "serial", dd.iSerialNumber); + + mounted_is_v15 = dd.idVendor == FM1_VID && dd.idProduct == FM1_V15_PID; + if (mounted_is_v15) { + dlog(" stock FM-1 application; `uboot` (fm1t) or console k enters UBOOT via the soft key"); + } else if (dd.idVendor != FM1_VID || dd.idProduct != FM1_PID) { + dlog(" not the JieLi UBOOT (%04X:%04X expected)", FM1_VID, FM1_PID); + } + + if (tuh_descriptor_get_configuration_sync(daddr, 0, cfg_buf, 9) != XFER_RESULT_SUCCESS) { + dlog("HOST: configuration descriptor read failed"); + return false; + } + uint16_t total = ((tusb_desc_configuration_t *)cfg_buf)->wTotalLength; + if (total > sizeof(cfg_buf)) total = sizeof(cfg_buf); + if (tuh_descriptor_get_configuration_sync(daddr, 0, cfg_buf, total) != XFER_RESULT_SUCCESS) { + dlog("HOST: configuration descriptor (%u bytes) read failed", total); + return false; + } + + dlog("CONFIGURATION DESCRIPTOR (%u bytes), bConfigurationValue=%u", total, + ((tusb_desc_configuration_t *)cfg_buf)->bConfigurationValue); + ep_in = ep_out = 0; + other_bulk_out.bLength = 0; + other_bulk_out_open = false; + const tusb_desc_endpoint_t *bulk_in = NULL, *bulk_out = NULL; + bool in_msc = false; + + for (uint16_t off = 0; off + 2 <= total && cfg_buf[off] >= 2; off += cfg_buf[off]) { + const uint8_t *d = &cfg_buf[off]; + if (d[1] == TUSB_DESC_INTERFACE) { + const tusb_desc_interface_t *itf = (const void *)d; + dlog(" interface %u alt %u: class=%02X/%02X/%02X endpoints=%u", + itf->bInterfaceNumber, itf->bAlternateSetting, itf->bInterfaceClass, + itf->bInterfaceSubClass, itf->bInterfaceProtocol, itf->bNumEndpoints); + in_msc = itf->bInterfaceClass == TUSB_CLASS_MSC; + if (in_msc) msc_itf = itf->bInterfaceNumber; + } else if (d[1] == TUSB_DESC_ENDPOINT) { + const tusb_desc_endpoint_t *ep = (const void *)d; + dlog(" endpoint %02X attr=%02X maxpacket=%u interval=%u", ep->bEndpointAddress, + ep->bmAttributes.xfer, tu_edpt_packet_size(ep), ep->bInterval); + if (!in_msc && ep->bmAttributes.xfer == TUSB_XFER_BULK && + tu_edpt_dir(ep->bEndpointAddress) == TUSB_DIR_OUT && !other_bulk_out.bLength) { + other_bulk_out = *ep; + } + if (in_msc && ep->bmAttributes.xfer == TUSB_XFER_BULK) { + if (tu_edpt_dir(ep->bEndpointAddress) == TUSB_DIR_IN) bulk_in = ep; + else bulk_out = ep; + } + } + } + + if (!bulk_in || !bulk_out) { + dlog("HOST: no MSC bulk IN/OUT pair found"); + return false; + } + + if (!tuh_edpt_open(daddr, bulk_out) || !tuh_edpt_open(daddr, bulk_in)) { + dlog("HOST: opening bulk endpoints failed"); + return false; + } + ep_in = bulk_in->bEndpointAddress; + ep_out = bulk_out->bEndpointAddress; + dlog("HOST: MSC bulk OUT=%02X IN=%02X", ep_out, ep_in); + return true; +} + +static bool probe_inquiry(uint8_t daddr) { + static const uint8_t inquiry[6] = {0x12, 0, 0, 0, 36, 0}; + uint32_t got = 0; + + if (!bot_cmd(daddr, inquiry, sizeof(inquiry), true, data_buf, 36, &got) || got < 36) { + dlog("INQUIRY failed (got %lu bytes)", (unsigned long)got); + return false; + } + + char vendor[9], product[17], rev[5]; + memcpy(vendor, &data_buf[8], 8); + vendor[8] = 0; + memcpy(product, &data_buf[16], 16); + product[16] = 0; + memcpy(rev, &data_buf[32], 4); + rev[4] = 0; + dlog("INQUIRY OK: vendor=\"%s\" product=\"%s\" rev=\"%s\"", vendor, product, rev); + return true; +} + +static void get_max_lun(uint8_t daddr) { + static CFG_TUSB_MEM_ALIGN uint8_t lun; + if (ctrl_sync(daddr, 0xA1, 0xFE, 0, msc_itf, &lun, 1)) dlog("GET MAX LUN: %u", lun); +} + +//--------------------------------------------------------------------+ +// Console commands (read-only diagnostics; no memory or flash access) +//--------------------------------------------------------------------+ + +void fm1_pio_host_command(char c) { + pending_cmd = c; +} + +static void run_command(uint8_t daddr, char c) { + static const uint8_t tur[6] = {0}; + uint32_t got = 0; + + switch (c) { + case 'l': + get_max_lun(daddr); + break; + case 'i': + probe_inquiry(daddr); + break; + case 'u': + dlog("TEST UNIT READY: %s", bot_cmd(daddr, tur, sizeof(tur), true, NULL, 0, NULL) ? "OK" : "failed"); + break; + case 'c': + dlog("SET_CONFIGURATION 1: %s", + ctrl_sync(daddr, 0x00, TUSB_REQ_SET_CONFIGURATION, 1, 0, NULL, 0) ? "OK" : "failed"); + break; + case 'r': + dlog("BOT reset: %s", ctrl_sync(daddr, 0x21, 0xFF, 0, msc_itf, NULL, 0) ? "OK" : "failed"); + dlog("CLEAR_HALT IN: %s", + ctrl_sync(daddr, 0x02, TUSB_REQ_CLEAR_FEATURE, 0, ep_in, NULL, 0) ? "OK" : "failed"); + dlog("CLEAR_HALT OUT: %s", + ctrl_sync(daddr, 0x02, TUSB_REQ_CLEAR_FEATURE, 0, ep_out, NULL, 0) ? "OK" : "failed"); + break; + case 'n': + if (edpt_sync(daddr, ep_in, data_buf, 64, &got)) { + dlog("IN %02X: %lu bytes, first %02X %02X %02X %02X", ep_in, (unsigned long)got, + data_buf[0], data_buf[1], data_buf[2], data_buf[3]); + } + break; + case 'd': + probe_descriptors(daddr); + break; + case 'k': + dlog("soft key: %s", fm1_host_softkey() ? "sent" : "not sent (no stock V15 mounted)"); + break; + case 'm': { + // Bulk OUT sanity check against a non-MSC bulk endpoint, e.g. the + // stock V15 USB-MIDI OUT: one Active Sensing packet, harmless. + static CFG_TUSB_MEM_ALIGN uint8_t pkt[4] = {0x0F, 0xFE, 0x00, 0x00}; + if (!other_bulk_out.bLength) { + dlog("no non-MSC bulk OUT endpoint"); + break; + } + if (!other_bulk_out_open) { + other_bulk_out_open = tuh_edpt_open(daddr, &other_bulk_out); + } + dlog("bulk OUT %02X, 4 bytes: %s", other_bulk_out.bEndpointAddress, + edpt_sync(daddr, other_bulk_out.bEndpointAddress, pkt, sizeof(pkt), NULL) ? "ACKed" : "failed"); + break; + } + default: + dlog("commands: l=GET MAX LUN i=INQUIRY u=TEST UNIT READY c=SET_CONFIGURATION " + "r=BOT reset+clear halt n=read IN once d=descriptors m=bulk OUT test (non-MSC) " + "k=soft key (stock V15 -> UBOOT)"); + break; + } +} + +void fm1_pio_host_task(void) { + tuh_task(); + + uint8_t daddr = mounted_addr; + + uint64_t now = time_us_64(); + + if (probe_pending && daddr) { + probe_pending = false; + if (probe_descriptors(daddr)) { + inquiry_tries = INQUIRY_TRIES; + next_inquiry_us = mount_us + FIRST_CBW_DELAY_MS * 1000ull; + dlog("HOST: first CBW in %d ms", FIRST_CBW_DELAY_MS); + } else { + rgb(true, false, false); + } + } + + if (inquiry_tries > 0 && daddr && now >= next_inquiry_us) { + if (inquiry_tries == INQUIRY_TRIES) { + // macOS asks for the LUN count before its first CBW; do the same. + get_max_lun(daddr); + } + inquiry_tries--; + dlog("INQUIRY attempt %d (%.1f ms after mount)", INQUIRY_TRIES - inquiry_tries, + (time_us_64() - mount_us) / 1000.0); + if (probe_inquiry(daddr)) { + inquiry_tries = 0; + uboot_ready = true; + rgb(false, true, false); + dlog("UBOOT READY: enumerated and answered INQUIRY via the PIO host."); + } else if (!mounted_addr) { + // detached mid-attempt; tuh_umount_cb already stopped the loop + } else if (inquiry_tries == 0) { + rgb(true, false, false); + dlog("UBOOT: INQUIRY never accepted. Type h on the console for diagnostics."); + } else { + next_inquiry_us = time_us_64() + INQUIRY_RETRY_MS * 1000ull; + } + } + + fm1_proto_poll(); + ar_task(); + + char c = pending_cmd; + if (c) { + pending_cmd = 0; + if (daddr && ((ep_in && ep_out) || c == 'm' || c == 'k')) { + dlog("> %c", c); + run_command(daddr, c); + } else { + dlog("> %c ignored: no UBOOT mounted", c); + } + } + + if (!daddr && now - unmounted_since_us > REATTACH_AFTER_MS * 1000ull) { + // Pico-PIO-USB inverts the pad input (GPIO_OVERRIDE_INVERT), so a + // pulled-up D+ reads as 0 here. With nothing mounted there is no bus + // traffic, so the level is steady. + bool pulled_up = true; + for (int i = 0; i < 20 && pulled_up; i++) { + pulled_up = !gpio_get(PIN_DP); + busy_wait_us_32(100); + } + uint32_t n = watchdog_hw->scratch[REATTACH_SCRATCH]; + if (pulled_up && n < REATTACH_MAX) { + watchdog_hw->scratch[REATTACH_SCRATCH] = n + 1; + dlog("HOST: D+ pulled up but nothing enumerated for %d ms - rebooting the " + "transporter to pulse and re-host (%lu/%d)", REATTACH_AFTER_MS, + (unsigned long)(n + 1), REATTACH_MAX); + sleep_ms(100); // let core 0 flush the log + watchdog_reboot(0, 0, 10); + for (;;) tight_loop_contents(); + } + unmounted_since_us = now; // re-check after another interval + } + + if (!daddr && now - last_status_us > ATTACH_STATUS_MS * 1000ull) { + dlog("HOST: no device mounted yet (%.1f s after host start)", + (now - host_start_us) / 1e6); + last_status_us = now; + } +} diff --git a/rescue/firmware/src/pio_host.h b/rescue/firmware/src/pio_host.h new file mode 100644 index 00000000..9bfcd7ed --- /dev/null +++ b/rescue/firmware/src/pio_host.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +// FM-1-facing PIO USB host (TinyUSB rhport 1, Pico-PIO-USB on PIO1, +// GP0 = D+, GP1 = D-). Runs entirely on core 1, after recovery. +// +// M0 scope: enumerate the JieLi ROM UBOOT, log its descriptors and run a +// read-only SCSI INQUIRY over Bulk-Only Transport. No memory or flash +// commands. + +// Takes GP0/GP1. Call immediately after recovery_release_bus(); the gap +// between the last ROM pulse and this call should be as short as possible. +void fm1_pio_host_start(void); + +// Services the host stack. Call continuously on core 1. +void fm1_pio_host_task(void); + +bool fm1_pio_host_mounted(void); + +// True once the mounted device answered INQUIRY as the JieLi UBOOT. +bool fm1_host_uboot_ready(void); + +// True while the stock FM-1 application (4C4A:C755) is mounted. +bool fm1_host_v15_mounted(void); + +// Sends the USB-MIDI soft key that makes stock V15 jump into the mask ROM +// UBOOT1.00 (the unit then re-attaches as 4C4A:8057). Core 1 only. +bool fm1_host_softkey(void); + +// One Bulk-Only Transport command to the mounted UBOOT (core 1 only). +// buf must be word-aligned RAM; len == 0 means no data stage. +bool fm1_host_bot(const uint8_t *cdb, uint8_t cdb_len, bool in, void *buf, uint16_t len, + uint32_t *got); + +// Queues a one-letter console command for core 1 (safe to call from core 0). +void fm1_pio_host_command(char c); diff --git a/rescue/firmware/src/recovery.c b/rescue/firmware/src/recovery.c new file mode 100644 index 00000000..f1715c1d --- /dev/null +++ b/rescue/firmware/src/recovery.c @@ -0,0 +1,399 @@ +// FM-1 Transporter - JieLi USB_KEY entry and ROM keep-alive pulses. +// +// The key sender and ACK detector are the known-good recovery baseline, +// unchanged except that only polarity A is used. Hardware findings from +// fm-1-research-lab (2026-09-30 / 2026-10-01) that shape the rest: +// - Polarity A (D+ = clock, D- = data) took the key every time; B never did. +// - After the ACK the ROM pulls D+ up within ~2 ms and keeps it up +// while 1 ms pulses arrive (6 s in earlier runs). On 2026-10-01 it +// released D+ after 4 s instead and re-attached ~1 s later. +// - If the pulses stop before a host takes over, the ROM gives up and boots +// flash. So the pulses are left running until the PIO USB host is ready. + +#include "recovery.h" + +#include +#include + +#include "pico/stdlib.h" +#include "hardware/pio.h" +#include "hardware/clocks.h" +#include "hardware/gpio.h" + +#include "autorescue.h" +#include "log.h" +#include "usb_key.pio.h" +#if FM1T_LED_WS2812 +#include "ws2812.pio.h" +#endif + +#if FM1T_BOARD_DEBUGPROBE +// Debug Probe: red, green and yellow LEDs, lit high (yellow stands in for blue). +#define LED_R 2 +#define LED_G 15 +#define LED_B 16 +#define LED_ON 1 +#elif FM1T_LED_MONO +// Raspberry Pi Pico and Pico-style boards: one plain LED on GP25, lit high. +// Colours become on/off; autorescue.c uses blink patterns instead. +#define LED_MONO_PIN 25 +#elif FM1T_LED_WS2812 +// Waveshare RP2040-Zero: one WS2812 on GP16, driven by a PIO0 state machine. +#define LED_WS_PIN 16 +#define LED_LEVEL 40 // of 255: bright enough, not blinding +#else +#define LED_R 17 +#define LED_G 16 +#define LED_B 25 +#define LED_ON 0 +#endif + +// The key program sets both bus pins' directions with one immediate. +#if PIN_DM == PIN_DP + 1 +#define KEY_PROGRAM usb_key_pp_program +#define KEY_CONFIG usb_key_pp_program_get_default_config +#elif PIN_DM == PIN_DP + 2 +#define KEY_PROGRAM usb_key_pp_gap_program +#define KEY_CONFIG usb_key_pp_gap_program_get_default_config +#else +#error "PIN_DM must be one or two pins above PIN_DP" +#endif + +#define USB_KEY_WORD 0x16EF +#define PIO_HZ 1000000 +#define KEY_PACKET_US 340 +#define GAP_PROBES 4 +#define GAP_PROBE_SPACING_US 35 +#define ACK_PROBE_LOWS 2 +#define DP_HIGH_TIMEOUT_MS 500 +#define PULSE_SAMPLE_US 100 +#define PULSE_LOW_SAMPLES 3 // 300 us low = not just one of our 4 us pulses +#define HANDOFF_PULSE_MS 6000 // matches every proven run; try lower once M0 works +#define CAL_DONE_MIN_MS 1000 // a D+ drop after this long under pulses = calibration done + +static PIO pio = pio0; +static uint sm_key, sm_sof, off_key, off_sof; + +#if FM1T_LED_WS2812 +static int sm_led = -1; +static uint32_t led_last = 0xFFFFFFFFu; + +void rgb(bool r, bool g, bool b) { + if (sm_led < 0) return; + uint32_t grb = (g ? LED_LEVEL : 0) << 16 | (r ? LED_LEVEL : 0) << 8 | (b ? LED_LEVEL : 0); + if (grb == led_last || pio_sm_is_tx_fifo_full(pio, (uint)sm_led)) return; + led_last = grb; + pio_sm_put(pio, (uint)sm_led, grb << 8); +} + +static void led_init(void) { + uint off = pio_add_program(pio, &ws2812_program); + sm_led = pio_claim_unused_sm(pio, true); + pio_gpio_init(pio, LED_WS_PIN); + pio_sm_set_consecutive_pindirs(pio, (uint)sm_led, LED_WS_PIN, 1, true); + pio_sm_config c = ws2812_program_get_default_config(off); + sm_config_set_sideset_pins(&c, LED_WS_PIN); + sm_config_set_out_shift(&c, false, true, 24); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + int cycles = ws2812_T1 + ws2812_T2 + ws2812_T3; + sm_config_set_clkdiv(&c, (float)clock_get_hz(clk_sys) / (800000.0f * cycles)); + pio_sm_init(pio, (uint)sm_led, off, &c); + pio_sm_set_enabled(pio, (uint)sm_led, true); +} +#elif FM1T_LED_MONO +void rgb(bool r, bool g, bool b) { + gpio_put(LED_MONO_PIN, r || g || b); +} + +static void led_init(void) { + gpio_init(LED_MONO_PIN); + gpio_set_dir(LED_MONO_PIN, GPIO_OUT); +} +#else +void rgb(bool r, bool g, bool b) { + gpio_put(LED_R, LED_ON ? r : !r); + gpio_put(LED_G, LED_ON ? g : !g); + gpio_put(LED_B, LED_ON ? b : !b); +} + +static void led_init(void) { + gpio_init(LED_R); + gpio_set_dir(LED_R, GPIO_OUT); + gpio_init(LED_G); + gpio_set_dir(LED_G, GPIO_OUT); + gpio_init(LED_B); + gpio_set_dir(LED_B, GPIO_OUT); +} +#endif + +static void pad_setup(uint pin, enum gpio_drive_strength ds) { + gpio_set_drive_strength(pin, ds); + gpio_set_slew_rate(pin, GPIO_SLEW_RATE_SLOW); + gpio_set_pulls(pin, false, true); +} + +void recovery_release_bus(void) { + pio_sm_set_enabled(pio, sm_key, false); + pio_sm_set_enabled(pio, sm_sof, false); + + const uint pins[] = {PIN_DP, PIN_DM}; + for (uint i = 0; i < 2; i++) { + uint pin = pins[i]; + gpio_set_function(pin, GPIO_FUNC_SIO); + gpio_set_dir(pin, GPIO_IN); + gpio_put(pin, 0); + gpio_set_outover(pin, GPIO_OVERRIDE_NORMAL); + gpio_set_oeover(pin, GPIO_OVERRIDE_NORMAL); + gpio_set_inover(pin, GPIO_OVERRIDE_NORMAL); + } +} + +static bool dp(void) { return gpio_get(PIN_DP); } +static bool dm(void) { return gpio_get(PIN_DM); } + +static bool probe_high(uint pin) { + gpio_set_function(pin, GPIO_FUNC_SIO); + gpio_put(pin, 1); + gpio_set_dir(pin, GPIO_OUT); + busy_wait_us_32(2); + bool v = gpio_get(pin); + gpio_set_dir(pin, GPIO_IN); + gpio_put(pin, 0); + return v; +} + +// Polarity A: D+ is the clock (side-set), D- carries the data. +static void key_start(void) { + pio_sm_set_enabled(pio, sm_key, false); + + pio_sm_config c = KEY_CONFIG(off_key); + sm_config_set_set_pins(&c, PIN_DP, PIN_DM - PIN_DP + 1); + sm_config_set_out_pins(&c, PIN_DM, 1); + sm_config_set_sideset_pins(&c, PIN_DP); + sm_config_set_out_shift(&c, false, false, 32); + sm_config_set_clkdiv(&c, (float)clock_get_hz(clk_sys) / PIO_HZ); + + pio_sm_init(pio, sm_key, off_key, &c); + + uint32_t mask = (1u << PIN_DP) | (1u << PIN_DM); + pio_sm_set_pins_with_mask(pio, sm_key, 0, mask); + pio_sm_set_pindirs_with_mask(pio, sm_key, 0, mask); + pio_sm_clear_fifos(pio, sm_key); + pio_sm_set_enabled(pio, sm_key, true); +} + +static void key_send_packet(void) { + pio_gpio_init(pio, PIN_DP); + pio_gpio_init(pio, PIN_DM); + pio_sm_put_blocking(pio, sm_key, (uint32_t)USB_KEY_WORD << 16); + sleep_us(KEY_PACKET_US); +} + +static int gap_sense(uint data_pin, bool *alive) { + int lows = 0; + int dp_highs = 0; + + for (int i = 0; i < GAP_PROBES; i++) { + sleep_us(GAP_PROBE_SPACING_US); + + if (dp()) { + if (++dp_highs >= 2) return 2; + } else { + dp_highs = 0; + } + + if (probe_high(data_pin)) { + *alive = true; + lows = 0; + } else if (*alive && ++lows >= ACK_PROBE_LOWS) { + return 1; + } + } + + return 0; +} + +static void pulse_start(void) { + gpio_set_drive_strength(PIN_DP, GPIO_DRIVE_STRENGTH_8MA); + pio_gpio_init(pio, PIN_DP); + + pio_sm_config c = sof_pulse_program_get_default_config(off_sof); + sm_config_set_set_pins(&c, PIN_DP, 1); + sm_config_set_clkdiv(&c, (float)clock_get_hz(clk_sys) / PIO_HZ); + + pio_sm_init(pio, sm_sof, off_sof, &c); + pio_sm_set_pins_with_mask(pio, sm_sof, 0, 1u << PIN_DP); + pio_sm_set_pindirs_with_mask(pio, sm_sof, 0, 1u << PIN_DP); + pio_sm_set_enabled(pio, sm_sof, true); +} + +// Waits for the ROM's D+ pull-up after an ACK. A D- pull-up instead means the +// two data wires are swapped (seen on hardware after rewiring). +static bool wait_dp_high(uint32_t timeout_ms) { + uint64_t deadline = time_us_64() + (uint64_t)timeout_ms * 1000; + int highs = 0; + int dm_highs = 0; + + while (time_us_64() < deadline) { + if (dp()) { + if (++highs >= 5) return true; + } else { + highs = 0; + } + + if (dm()) { + if (++dm_highs == 5) { + dlog("D- pulled up instead of D+ - are D+/D- wired swapped?"); + } + } else { + dm_highs = 0; + } + + sleep_us(50); + } + + return false; +} + +// Feeds 1 ms pulses and returns, with the pulse state machine still running, +// as soon as the host should take over: +// - D+ drops after CAL_DONE_MIN_MS: the ROM finished calibrating and is +// about to re-attach as UBOOT. Seen on hardware 2026-10-01: drop at 4.0 s, +// re-attach at 5.1 s, gave up at 7.2 s when no host answered. The host +// must already be running when the re-attach comes. +// - D+ held high for HANDOFF_PULSE_MS (the 6 s pattern from earlier runs). +static void pulse_phase(void) { + dlog("PULSE: D+ high (ROM pull-up), sending 4 us pulses every 1 ms"); + pulse_start(); + + uint64_t start = time_us_64(); + uint32_t low_samples = 0; + + for (;;) { + sleep_us(PULSE_SAMPLE_US); + uint64_t now = time_us_64(); + uint64_t elapsed_us = now - start; + + if (!dp()) { + if (++low_samples == PULSE_LOW_SAMPLES) { + if (elapsed_us >= (uint64_t)CAL_DONE_MIN_MS * 1000) { + dlog("PULSE: D+ released after %.1f ms - calibration done, host takes over", + elapsed_us / 1000.0); + return; + } + dlog("PULSE: early D+ blip at %.1f ms, ignored", elapsed_us / 1000.0); + } + } else { + low_samples = 0; + } + + if (elapsed_us >= (uint64_t)HANDOFF_PULSE_MS * 1000) { + dlog("PULSE: %d ms of pulses, D+=%d - handing off", HANDOFF_PULSE_MS, dp()); + return; + } + } +} + +void recovery_run(void) { + uint32_t packets = 0; + bool alive = false; + bool was_alive = false; + uint64_t start = time_us_64(); + uint64_t last_status = start; + uint64_t last_blink = start; + bool blink = false; + + key_start(); + dlog("KEY: sending 0x%04X, polarity A (D+ clock, D- data). Switch the FM-1 ON now.", + USB_KEY_WORD); + + for (;;) { + key_send_packet(); + packets++; + + int s = gap_sense(PIN_DM, &alive); + + if (alive && !was_alive) { + dlog("data line probe responds (not proof of a target)"); + was_alive = true; + } + + if (s) { + recovery_release_bus(); + dlog("%s after %lu packets", + s == 1 ? "ACK (data line held low)" : "D+ high in gap (ACK missed?)", + (unsigned long)packets); + rgb(true, true, false); + + if (s == 2 || wait_dp_high(DP_HIGH_TIMEOUT_MS)) { + pulse_phase(); + return; + } + + dlog("no D+ pull-up within %d ms (D+=%d D-=%d) - false ACK, resuming key", + DP_HIGH_TIMEOUT_MS, dp(), dm()); + alive = false; + was_alive = false; + key_start(); + continue; + } + + uint64_t now = time_us_64(); + + if (now - last_blink > 250000) { + blink = !blink; + // Stand-alone rescue: yellow = waiting (red is kept for errors). + rgb(blink, ar_enabled() && blink, false); + last_blink = now; + } + + if (now - last_status > 2000000) { + dlog("KEY: %lu packets", (unsigned long)packets); + last_status = now; + } + } +} + +bool recovery_wait_detached(uint32_t timeout_ms) { + uint64_t deadline = time_us_64() + (uint64_t)timeout_ms * 1000; + int lows = 0; + while (time_us_64() < deadline) { + if (!dp()) { + if (++lows >= 20) return true; // 2 ms steadily low + } else { + lows = 0; + } + sleep_us(100); + } + return false; +} + +bool recovery_target_attached(void) { + for (int i = 0; i < 50; i++) { + if (!dp()) return false; + sleep_us(1000); + } + return true; +} + +void recovery_pulses_only(uint32_t ms) { + dlog("PULSE: %lu ms of 1 ms pulses for an already attached target", (unsigned long)ms); + pulse_start(); + sleep_ms(ms); +} + +void recovery_init(void) { + led_init(); + rgb(false, false, false); + + gpio_init(PIN_DP); + gpio_init(PIN_DM); + pad_setup(PIN_DP, GPIO_DRIVE_STRENGTH_2MA); + pad_setup(PIN_DM, GPIO_DRIVE_STRENGTH_2MA); + + off_key = pio_add_program(pio, &KEY_PROGRAM); + off_sof = pio_add_program(pio, &sof_pulse_program); + sm_key = pio_claim_unused_sm(pio, true); + sm_sof = pio_claim_unused_sm(pio, true); + recovery_release_bus(); +} diff --git a/rescue/firmware/src/recovery.h b/rescue/firmware/src/recovery.h new file mode 100644 index 00000000..e24195fc --- /dev/null +++ b/rescue/firmware/src/recovery.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +#if FM1T_BOARD_DEBUGPROBE +// Raspberry Pi Debug Probe, UART connector: TX (orange, GP4) -> FM-1 D+, +// RX (yellow) -> FM-1 D-, GND (black) -> GND. RX reaches GP6 through 100R; +// GP5 only reads it through a buffer and cannot drive it, so D- is GP6. +#define PIN_DP 4 +#define PIN_DM 6 +#else +// Seeed XIAO RP2040 / Waveshare RP2040-Zero / Pico: GP0 -> FM-1 D+ (green), +// GP1 -> FM-1 D- (white), GND -> GND (black). XIAO labels: GP0 = D6, GP1 = D7. +// Seeed XIAO RP2040: GP0/D6 -> FM-1 D+, GP1/D7 -> FM-1 D-, GND -> GND. +#define PIN_DP 0 +#define PIN_DM 1 +#endif + +// Claims PIO0 state machines and leaves the target bus released. +void recovery_init(void); + +// True if something already pulls D+ up at boot: a running FM-1 application, +// or a ROM UBOOT left waiting. The key is pointless then; go straight to host. +bool recovery_target_attached(void); + +// Waits until nothing pulls D+ up (e.g. the loader's watchdog reset fired). +bool recovery_wait_detached(uint32_t timeout_ms); + +// Feeds the 1 ms pulses for ms without keying, then returns with them still +// running. Stock V15 also failed its first SETUP without them; with 6 s of +// pulses before the host started it enumerated every time. +void recovery_pulses_only(uint32_t ms); + +// Sends the JieLi USB_KEY until the ROM acknowledges, then keeps feeding +// 1 ms pulses. Returns with the pulses STILL RUNNING: the ROM gives up if +// they stop before a USB host takes over. +void recovery_run(void); + +// Stops every PIO0 state machine, returns GP0/GP1 to SIO inputs and clears +// any pad overrides. Must be called immediately before the PIO USB host +// takes the pins. +void recovery_release_bus(void); + +void rgb(bool r, bool g, bool b); diff --git a/rescue/firmware/src/transporter_proto.c b/rescue/firmware/src/transporter_proto.c new file mode 100644 index 00000000..18603383 --- /dev/null +++ b/rescue/firmware/src/transporter_proto.c @@ -0,0 +1,410 @@ +#include "transporter_proto.h" + +#include +#include +#include +#include + +#include "pico/stdlib.h" +#include "hardware/sync.h" +#include "tusb.h" + +#include "autorescue.h" +#include "jieli_uboot.h" +#include "log.h" +#include "pio_host.h" + +#define DATA_ITF 1 +#define TX_SIZE 16384 // power of two +#define LINE_MAX 64 + +// core 0 -> core 1: one request line at a time, plus the 4 KiB payload of a +// `wsec` request. +static char rx_line[LINE_MAX]; +static unsigned rx_len; +static uint8_t __attribute__((aligned(4))) sector[JL_SECTOR_SIZE]; +static unsigned sector_fill; +static bool rx_binary; // collecting a wsec/memw payload +static unsigned rx_expect; // payload size: 4096 for wsec, LEN for memw +static char req[LINE_MAX]; +static volatile bool req_pending; + +// core 1 -> core 0: output stream with backpressure. +static uint8_t tx[TX_SIZE]; +static volatile uint32_t tx_head; // core 1 +static volatile uint32_t tx_tail; // core 0 + +static uint8_t __attribute__((aligned(4))) io[JL_READ_MAX]; + +//--------------------------------------------------------------------+ +// core 0 +//--------------------------------------------------------------------+ + +void fm1_proto_rx(const char *buf, unsigned len) { + for (unsigned i = 0; i < len; i++) { + if (rx_binary) { + unsigned n = len - i; + if (n > rx_expect - sector_fill) n = rx_expect - sector_fill; + memcpy(§or[sector_fill], &buf[i], n); + sector_fill += n; + i += n - 1; + if (sector_fill == rx_expect) { + rx_binary = false; + __dmb(); + req_pending = true; // req already holds the wsec line + } + continue; + } + char c = buf[i]; + if (c == '\r') continue; + if (c != '\n') { + if (rx_len < LINE_MAX - 1) rx_line[rx_len++] = c; + continue; + } + rx_line[rx_len] = 0; + rx_len = 0; + if (!strcmp(rx_line, "rekey")) { + extern void fm1_rekey(void); + tud_cdc_n_write_str(DATA_ITF, "OK rekey\n"); + tud_cdc_n_write_flush(DATA_ITF); + fm1_rekey(); + continue; + } + if (!strcmp(rx_line, "rescue")) { + // Answered here, on core 0, so the progress can be read while + // core 1 is busy writing (the FM-1 Rescue Android app polls it). + char st[160] = "OK "; + ar_status_line(st + 3, sizeof(st) - 4); + strcat(st, "\n"); + tud_cdc_n_write_str(DATA_ITF, st); + tud_cdc_n_write_flush(DATA_ITF); + continue; + } + if (!strcmp(rx_line, "ping")) { + // Answered here so fm1t can find the port while core 1 is still + // busy with the USB_KEY recovery. + tud_cdc_n_write_str(DATA_ITF, "PONG\n"); + tud_cdc_n_write_flush(DATA_ITF); + continue; + } + if (req_pending) continue; // one request at a time; drop extras + memcpy(req, rx_line, sizeof(req)); + if (!strncmp(rx_line, "wsec ", 5)) { + sector_fill = 0; + rx_expect = JL_SECTOR_SIZE; + rx_binary = true; // the request fires once 4 KiB arrived + continue; + } + if (!strncmp(rx_line, "ldr ", 4)) { + // ldr , then raw bytes (1..4096) + char *a = strchr(rx_line + 4, ' '); + unsigned long n = a ? strtoul(a + 1, NULL, 0) : 0; + if (n >= 1 && n <= JL_SECTOR_SIZE) { + sector_fill = 0; + rx_expect = (unsigned)n; + rx_binary = true; + continue; + } + } + if (!strncmp(rx_line, "memw ", 5)) { + // memw , then raw bytes (1..4096) + char *p = strchr(rx_line + 5, ' '); + unsigned long n = p ? strtoul(p + 1, NULL, 0) : 0; + if (n >= 1 && n <= JL_SECTOR_SIZE) { + sector_fill = 0; + rx_expect = (unsigned)n; + rx_binary = true; + continue; + } + // bad length: hand the line to core 1, which answers ERR + } + __dmb(); + req_pending = true; + } +} + +void fm1_proto_drain(void) { + if (!tud_cdc_n_connected(DATA_ITF)) { + tx_tail = tx_head; // nobody listening; discard + return; + } + for (;;) { + uint32_t h = tx_head; + __dmb(); + uint32_t t = tx_tail; + if (h == t) break; + uint32_t avail = tud_cdc_n_write_available(DATA_ITF); + if (!avail) break; + uint32_t idx = t & (TX_SIZE - 1); + uint32_t n = h - t; + if (n > TX_SIZE - idx) n = TX_SIZE - idx; + if (n > avail) n = avail; + n = tud_cdc_n_write(DATA_ITF, &tx[idx], n); + __dmb(); + tx_tail = t + n; + } + tud_cdc_n_write_flush(DATA_ITF); +} + +//--------------------------------------------------------------------+ +// core 1 +//--------------------------------------------------------------------+ + +static void tx_bytes(const void *data, uint32_t len) { + const uint8_t *p = data; + while (len) { + uint32_t h = tx_head; + uint32_t space = TX_SIZE - (h - tx_tail); + if (!space) { + tight_loop_contents(); // core 0 is draining + continue; + } + uint32_t n = len < space ? len : space; + for (uint32_t i = 0; i < n; i++) tx[(h + i) & (TX_SIZE - 1)] = p[i]; + __dmb(); + tx_head = h + n; + p += n; + len -= n; + } +} + +static void tx_line(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void tx_line(const char *fmt, ...) { + char line[96]; + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(line, sizeof(line) - 1, fmt, ap); + va_end(ap); + if (n < 0) return; + if (n > (int)sizeof(line) - 2) n = (int)sizeof(line) - 2; + line[n++] = '\n'; + tx_bytes(line, (uint32_t)n); +} + +// zlib-compatible CRC-32, so the Mac side can use zlib.crc32. +static uint32_t crc32_update(uint32_t crc, const uint8_t *p, uint32_t len) { + crc = ~crc; + while (len--) { + crc ^= *p++; + for (int b = 0; b < 8; b++) crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1))); + } + return ~crc; +} + +// wsec : write one 4 KiB sector (payload already received). +static void do_write_sector(uint32_t addr, uint32_t crc) { + uint32_t got = crc32_update(0, sector, JL_SECTOR_SIZE); + if (got != crc) { + tx_line("ERR crc %08lX", (unsigned long)got); + return; + } + if (addr < JL_WRITE_MIN || addr >= JL_WRITE_END || (addr % JL_SECTOR_SIZE)) { + tx_line("ERR range"); + return; + } + dlog("PROTO: write sector %06lX", (unsigned long)addr); + tx_line(jl_flash_write_sector(addr, sector) ? "OK" : "ERR write"); +} + +static void do_read(uint32_t addr, uint32_t len) { + if (len == 0 || addr >= JL_FLASH_SIZE || len > JL_FLASH_SIZE - addr) { + tx_line("ERR range"); + return; + } + if (!jl_ensure_loader()) { + tx_line("ERR loader"); + return; + } + + dlog("PROTO: read %06lX+%lu", (unsigned long)addr, (unsigned long)len); + uint64_t t0 = time_us_64(); + tx_line("DATA %lu", (unsigned long)len); + + uint32_t crc = 0; + uint32_t chunk = jl_read_chunk(); + for (uint32_t off = 0; off < len; off += chunk) { + uint16_t n = (uint16_t)((len - off) < chunk ? (len - off) : chunk); + bool ok = false; + for (int attempt = 0; attempt < 3 && !ok; attempt++) { + ok = jl_flash_read(addr + off, n, io); + } + if (!ok) { + // The Mac side counts bytes, so the stream cannot be resynced. + // Pad with zeros and report the failure in END. + memset(io, 0, n); + tx_bytes(io, n); + for (off += n; off < len; off += chunk) { + uint32_t m = (len - off) < chunk ? (len - off) : chunk; + tx_bytes(io, m); + } + tx_line("END FAIL"); + return; + } + crc = crc32_update(crc, io, n); + tx_bytes(io, n); + } + + tx_line("END %08lX", (unsigned long)crc); + dlog("PROTO: read done, %lu bytes in %.2f s, crc32 %08lX", (unsigned long)len, + (time_us_64() - t0) / 1e6, (unsigned long)crc); +} + +//--------------------------------------------------------------------+ +// RAM-run (ROM UBOOT1.00 stage, before the loader) +//--------------------------------------------------------------------+ + +// memw : payload already in sector[0..len) +static void do_memw(uint32_t addr, uint32_t len, uint32_t crc) { + if (len < 1 || len > JL_SECTOR_SIZE) { + tx_line("ERR len"); + return; + } + uint32_t got = crc32_update(0, sector, len); + if (got != crc) { + tx_line("ERR crc %08lX", (unsigned long)got); + return; + } + if (jl_loader_running()) { + tx_line("ERR loader-running"); + return; + } + for (uint32_t off = 0; off < len; off += JL_IO_SIZE) { + uint16_t n = (uint16_t)((len - off) < JL_IO_SIZE ? (len - off) : JL_IO_SIZE); + if (!jl_rom_mem_write(addr + off, §or[off], n)) { + tx_line("ERR memw at %08lX", (unsigned long)(addr + off)); + return; + } + } + tx_line("OK"); +} + +// memr : DATA , raw bytes, END +static void do_memr(uint32_t addr, uint32_t len) { + if (len < 1 || len > JL_READ_MAX) { + tx_line("ERR len"); + return; + } + if (jl_loader_running()) { + tx_line("ERR loader-running"); + return; + } + for (uint32_t off = 0; off < len; off += JL_IO_SIZE) { + uint16_t n = (uint16_t)((len - off) < JL_IO_SIZE ? (len - off) : JL_IO_SIZE); + if (!jl_rom_mem_read(addr + off, n, &io[off])) { + tx_line("ERR memr at %08lX", (unsigned long)(addr + off)); + return; + } + } + tx_line("DATA %lu", (unsigned long)len); + tx_bytes(io, len); + tx_line("END %08lX", (unsigned long)crc32_update(0, io, len)); +} + +// ldr : payload already in sector[0..len) +static void do_ldr(uint32_t off, uint32_t len, uint32_t crc) { + uint32_t got = crc32_update(0, sector, len); + if (got != crc) { + tx_line("ERR crc %08lX", (unsigned long)got); + return; + } + if (jl_loader_running()) { + tx_line("ERR loader-running"); + return; + } + tx_line(jl_loader_load(off, sector, len) ? "OK" : "ERR loader-range"); +} + +// jump : call RAM code through the ROM; it must return (< ~2 s) +static void do_jump(uint32_t addr, uint32_t arg) { + if (jl_loader_running()) { + tx_line("ERR loader-running"); + return; + } + dlog("PROTO: jump %08lX arg %04lX", (unsigned long)addr, (unsigned long)arg); + uint64_t t0 = time_us_64(); + bool ok = jl_rom_jump(addr, (uint16_t)arg); + uint32_t ms = (uint32_t)((time_us_64() - t0) / 1000); + if (ok) tx_line("OK ms=%lu", (unsigned long)ms); + else tx_line("ERR jump ms=%lu", (unsigned long)ms); +} + +void fm1_proto_poll(void) { + if (!req_pending) { + jl_keepalive(); + return; + } + __dmb(); + char line[LINE_MAX]; + memcpy(line, req, sizeof(line)); + req_pending = false; + + char *argv[4] = {0}; + int argc = 0; + for (char *tok = strtok(line, " \t"); tok && argc < 4; tok = strtok(NULL, " \t")) { + argv[argc++] = tok; + } + if (!argc) return; + + if (!strcmp(argv[0], "status")) { + tx_line("OK uboot=%d v15=%d loader=%d loader_running=%d", fm1_host_uboot_ready(), + fm1_host_v15_mounted(), jl_have_loader(), jl_loader_running()); + } else if (!strcmp(argv[0], "uboot")) { + if (fm1_host_uboot_ready()) { + tx_line("OK uboot"); + } else if (fm1_host_softkey()) { + tx_line("OK softkey"); // poll `status` for uboot=1 + } else { + tx_line("ERR no-v15"); + } + } else if (!strcmp(argv[0], "info")) { + jl_info_t info; + if (!fm1_host_uboot_ready()) { + tx_line("ERR no-uboot"); + } else if (!jl_info(&info)) { + tx_line("ERR info"); + } else { + dlog("PROTO: chip key %04X, device type %u, flash id %06lX", info.chip_key, + info.dev_type, (unsigned long)info.flash_id); + tx_line("OK key=%04X type=%u id=%06lX", info.chip_key, info.dev_type, + (unsigned long)info.flash_id); + } + } else if (!strcmp(argv[0], "read") && argc == 3) { + if (!fm1_host_uboot_ready()) { + tx_line("ERR no-uboot"); + } else { + do_read(strtoul(argv[1], NULL, 0), strtoul(argv[2], NULL, 0)); + } + } else if (!strcmp(argv[0], "runapp")) { + tx_line(jl_run_app() ? "OK" : "ERR no-loader"); + } else if (!strcmp(argv[0], "wsec") && argc == 3) { + if (!fm1_host_uboot_ready()) { + tx_line("ERR no-uboot"); + } else { + do_write_sector(strtoul(argv[1], NULL, 0), strtoul(argv[2], NULL, 16)); + } + } else if (!strcmp(argv[0], "ldr") && argc == 4) { + do_ldr(strtoul(argv[1], NULL, 0), strtoul(argv[2], NULL, 0), + strtoul(argv[3], NULL, 16)); + } else if (!strcmp(argv[0], "memw") && argc == 4) { + if (!fm1_host_uboot_ready()) { + tx_line("ERR no-uboot"); + } else { + do_memw(strtoul(argv[1], NULL, 0), strtoul(argv[2], NULL, 0), + strtoul(argv[3], NULL, 16)); + } + } else if (!strcmp(argv[0], "memr") && argc == 3) { + if (!fm1_host_uboot_ready()) { + tx_line("ERR no-uboot"); + } else { + do_memr(strtoul(argv[1], NULL, 0), strtoul(argv[2], NULL, 0)); + } + } else if (!strcmp(argv[0], "jump") && argc == 3) { + if (!fm1_host_uboot_ready()) { + tx_line("ERR no-uboot"); + } else { + do_jump(strtoul(argv[1], NULL, 0), strtoul(argv[2], NULL, 0)); + } + } else { + tx_line("ERR unknown"); + } +} diff --git a/rescue/firmware/src/transporter_proto.h b/rescue/firmware/src/transporter_proto.h new file mode 100644 index 00000000..e77328d8 --- /dev/null +++ b/rescue/firmware/src/transporter_proto.h @@ -0,0 +1,33 @@ +#pragma once + +// Mac-facing data channel on the second CDC interface (tools/fm1t.py). +// +// Requests are text lines; replies are text lines, and `read` replies carry +// a raw binary payload: +// +// ping -> PONG +// rescue -> OK state=... phase=... sector=n/143 ... (stand-alone +// rescue progress, see ar_status_line; answered on +// core 0, also while a restore runs) +// status -> OK uboot=<0|1> v15=<0|1> loader=<0|1> +// uboot -> OK uboot | OK softkey | ERR no-v15 +// (soft key: stock V15 -> mask ROM UBOOT1.00) +// runapp -> OK | ERR no-loader (loader RUN_APP: boot firmware) +// rekey -> OK rekey, then the transporter reboots into +// USB_KEY mode (for a unit stuck with USB up) +// info -> OK key=980F type=3 id=856014 | ERR +// read -> DATA \n END \n | ERR +// ldr \n +// -> OK | ERR (upload wl82loader.bin in order) +// wsec \n <4096 raw bytes> +// -> OK | ERR (erase + write + read-back verify) +// +// Writes are accepted only for whole 4 KiB sectors in [0x4000, 0x93000); +// see jieli_uboot.h. No block/chip erase exists. + +// core 0: feed bytes received on CDC 1; drain queued output to CDC 1. +void fm1_proto_rx(const char *buf, unsigned len); +void fm1_proto_drain(void); + +// core 1: handle a pending request, if any. +void fm1_proto_poll(void); diff --git a/rescue/firmware/src/tusb_config.h b/rescue/firmware/src/tusb_config.h new file mode 100644 index 00000000..a785c50e --- /dev/null +++ b/rescue/firmware/src/tusb_config.h @@ -0,0 +1,42 @@ +#ifndef TUSB_CONFIG_H +#define TUSB_CONFIG_H + +// rhport 0: RP2040 native USB, device, Mac-facing CDC console. +// rhport 1: Pico-PIO-USB on GP0/GP1, host, FM-1 JieLi ROM/UBOOT. + +#define CFG_TUSB_OS OPT_OS_PICO +#define CFG_TUSB_MEM_SECTION +#define CFG_TUSB_MEM_ALIGN __attribute__((aligned(4))) + +// CFG_TUSB_DEBUG comes from CMake (LOG=2). Host enumeration logs at level 2 +// go to our console; the device stack stays quiet. +#define CFG_TUH_LOG_LEVEL 2 +#define CFG_TUD_LOG_LEVEL 3 + +//--------------------------------------------------------------------+ +// Device (native USB) +//--------------------------------------------------------------------+ +#define CFG_TUD_ENABLED 1 +#define CFG_TUD_ENDPOINT0_SIZE 64 +#define CFG_TUD_CDC 2 // console + fm1t data +#define CFG_TUD_CDC_RX_BUFSIZE 256 +#define CFG_TUD_CDC_TX_BUFSIZE 2048 +#define CFG_TUD_CDC_EP_BUFSIZE 64 + +//--------------------------------------------------------------------+ +// Host (PIO USB) +//--------------------------------------------------------------------+ +#define CFG_TUH_ENABLED 1 +#define CFG_TUH_RPI_PIO_USB 1 +#define CFG_TUH_ENUMERATION_BUFSIZE 512 // stock V15 (4C4A:C755) has a 293-byte config +#define CFG_TUH_HUB 0 +#define CFG_TUH_DEVICE_MAX 1 +// Required for tuh_edpt_xfer() completion callbacks; without it TinyUSB +// drops the completion of our raw bulk transfers. +#define CFG_TUH_API_EDPT_XFER 1 +// No class drivers: the JieLi UBOOT speaks Bulk-Only Transport with vendor +// CDBs, so we drive its bulk endpoints directly instead of letting the MSC +// driver send its own SCSI commands at mount time. +#define CFG_TUH_MSC 0 + +#endif diff --git a/rescue/firmware/src/usb_device.c b/rescue/firmware/src/usb_device.c new file mode 100644 index 00000000..1e6dbe9f --- /dev/null +++ b/rescue/firmware/src/usb_device.c @@ -0,0 +1,156 @@ +// Mac-facing USB device on the RP2040 native controller (rhport 0): +// CDC 0: log console (src/log.c, one-letter diagnostics) +// CDC 1: fm1t data channel (src/transporter_proto.c) +// Raspberry Pi reset interface, so `picotool -f` and a 1200 baud touch on +// the console still reboot the board into BOOTSEL. + +#include "pico/bootrom.h" +#include "pico/unique_id.h" +#include "pico/usb_reset_interface.h" +#include "hardware/watchdog.h" +#include "tusb.h" +#include "device/usbd_pvt.h" + +#define USBD_VID 0x2E8A // Raspberry Pi +#define USBD_PID 0x000A // Pico SDK CDC (RP2040), what picotool expects + +#define TUD_RPI_RESET_DESC_LEN 9 +#define USBD_DESC_LEN (TUD_CONFIG_DESC_LEN + 2 * TUD_CDC_DESC_LEN + TUD_RPI_RESET_DESC_LEN) + +#define USBD_ITF_CDC0 0 // two interfaces each +#define USBD_ITF_CDC1 2 +#define USBD_ITF_RESET 4 +#define USBD_ITF_MAX 5 + +enum { STR_LANG, STR_MANUF, STR_PRODUCT, STR_SERIAL, STR_CDC0, STR_CDC1, STR_RESET, STR_COUNT }; + +static const tusb_desc_device_t desc_device = { + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + .bDeviceClass = TUSB_CLASS_MISC, + .bDeviceSubClass = MISC_SUBCLASS_COMMON, + .bDeviceProtocol = MISC_PROTOCOL_IAD, + .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, + .idVendor = USBD_VID, + .idProduct = USBD_PID, + .bcdDevice = 0x0100, + .iManufacturer = STR_MANUF, + .iProduct = STR_PRODUCT, + .iSerialNumber = STR_SERIAL, + .bNumConfigurations = 1, +}; + +static const uint8_t desc_cfg[USBD_DESC_LEN] = { + TUD_CONFIG_DESCRIPTOR(1, USBD_ITF_MAX, 0, USBD_DESC_LEN, 0, 100), + TUD_CDC_DESCRIPTOR(USBD_ITF_CDC0, STR_CDC0, 0x81, 8, 0x02, 0x82, 64), + TUD_CDC_DESCRIPTOR(USBD_ITF_CDC1, STR_CDC1, 0x83, 8, 0x04, 0x84, 64), + 9, TUSB_DESC_INTERFACE, USBD_ITF_RESET, 0, 0, TUSB_CLASS_VENDOR_SPECIFIC, + RESET_INTERFACE_SUBCLASS, RESET_INTERFACE_PROTOCOL, STR_RESET, +}; + +static char serial_str[PICO_UNIQUE_BOARD_ID_SIZE_BYTES * 2 + 1]; + +static const char *const desc_str[STR_COUNT] = { + [STR_MANUF] = "kurogedelic", + [STR_PRODUCT] = "FM-1 Transporter", + [STR_SERIAL] = serial_str, + [STR_CDC0] = "FM-1 Transporter console", + [STR_CDC1] = "FM-1 Transporter data", + [STR_RESET] = "Reset", +}; + +const uint8_t *tud_descriptor_device_cb(void) { + return (const uint8_t *)&desc_device; +} + +const uint8_t *tud_descriptor_configuration_cb(uint8_t index) { + (void)index; + return desc_cfg; +} + +const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void)langid; + static uint16_t out[32]; + uint8_t len; + + if (!serial_str[0]) pico_get_unique_board_id_string(serial_str, sizeof(serial_str)); + + if (index == STR_LANG) { + out[1] = 0x0409; + len = 1; + } else { + if (index >= STR_COUNT) return NULL; + const char *s = desc_str[index]; + for (len = 0; len < 31 && s[len]; len++) out[1 + len] = (uint8_t)s[len]; + } + + out[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * len + 2)); + return out; +} + +//--------------------------------------------------------------------+ +// Reset interface (same protocol as pico_stdio_usb's reset_interface.c, +// which is compiled out whenever the TinyUSB host stack is linked) +//--------------------------------------------------------------------+ + +static uint8_t reset_itf; + +static void resetd_init(void) {} + +static void resetd_reset(uint8_t rhport) { + (void)rhport; + reset_itf = 0; +} + +static uint16_t resetd_open(uint8_t rhport, tusb_desc_interface_t const *itf, uint16_t max_len) { + (void)rhport; + TU_VERIFY(itf->bInterfaceClass == TUSB_CLASS_VENDOR_SPECIFIC && + itf->bInterfaceSubClass == RESET_INTERFACE_SUBCLASS && + itf->bInterfaceProtocol == RESET_INTERFACE_PROTOCOL, 0); + TU_VERIFY(max_len >= sizeof(tusb_desc_interface_t), 0); + reset_itf = itf->bInterfaceNumber; + return sizeof(tusb_desc_interface_t); +} + +static bool resetd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *req) { + (void)rhport; + if (stage != CONTROL_STAGE_SETUP) return true; + if (req->wIndex != reset_itf) return false; + + if (req->bRequest == RESET_REQUEST_BOOTSEL) { + int gpio = (req->wValue & 0x100) ? (int)(req->wValue >> 9) : -1; + rom_reset_usb_boot_extra(gpio, req->wValue & 0x7f, req->wValue & 0x200); + // does not return + } + + if (req->bRequest == RESET_REQUEST_FLASH) { + watchdog_reboot(0, 0, 100); + return true; + } + + return false; +} + +static bool resetd_xfer_cb(uint8_t rhport, uint8_t ep, xfer_result_t result, uint32_t n) { + (void)rhport; (void)ep; (void)result; (void)n; + return true; +} + +static const usbd_class_driver_t resetd_driver = { + .init = resetd_init, + .reset = resetd_reset, + .open = resetd_open, + .control_xfer_cb = resetd_control_xfer_cb, + .xfer_cb = resetd_xfer_cb, + .sof = NULL, +}; + +usbd_class_driver_t const *usbd_app_driver_get_cb(uint8_t *driver_count) { + *driver_count = 1; + return &resetd_driver; +} + +void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const *coding) { + if (itf == 0 && coding->bit_rate == 1200) rom_reset_usb_boot_extra(-1, 0, false); +} diff --git a/rescue/firmware/test/host_test.c b/rescue/firmware/test/host_test.c new file mode 100644 index 00000000..54db026f --- /dev/null +++ b/rescue/firmware/test/host_test.c @@ -0,0 +1,229 @@ +// Host test of the stand-alone rescue (payload.c + autorescue.c, unmodified) +// against a mock FM-1: a 1 MiB flash behind mock jl_* / fm1_host_* calls. +// +// test/run.sh RESCUE.uf2 FM-1_V15_REGION.bin (rescue/build.sh runs it) +// +// Checks: the payload from the real .uf2 is accepted, a damaged one is +// refused, only differing sectors of 0x4000..0x92FFF are written, the head +// and the data area are never touched, a wrong chip is refused, a write that +// keeps failing ends in an error, an already-right unit is not written. + +#include +#include +#include +#include + +#include "autorescue.h" +#include "jieli_uboot.h" +#include "log.h" +#include "payload.h" +#include "pio_host.h" +#include "recovery.h" +#include "hardware/watchdog.h" + +uint8_t test_rp_flash[2 * 1024 * 1024]; +test_watchdog_t test_watchdog; +static uint64_t now_us; +uint64_t time_us_64(void) { return now_us += 50; } + +static int quiet = 1; +void dlog(const char *fmt, ...) { + if (quiet) return; + va_list ap; + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + putchar('\n'); +} +void rgb(bool r, bool g, bool b) { (void)r; (void)g; (void)b; } + +// ---- mock FM-1 ---- +static uint8_t fm1[JL_FLASH_SIZE]; +static int sector_writes[JL_FLASH_SIZE / JL_SECTOR_SIZE]; +static bool uboot = true, v15 = false, have_loader; +static uint16_t chip_key = JL_CHIP_KEY; +static uint32_t flash_id = JL_FLASH_ID; +static int fail_writes_at = -1; // sector address whose writes always fail +static int softkeys; + +bool fm1_pio_host_mounted(void) { return uboot || v15; } +bool fm1_host_uboot_ready(void) { return uboot; } +bool fm1_host_v15_mounted(void) { return v15; } +bool fm1_host_softkey(void) { softkeys++; v15 = false; uboot = true; return true; } +bool jl_have_loader(void) { return have_loader; } +bool jl_loader_load(uint32_t off, const uint8_t *d, uint32_t len) { + const pl_header_t *h = payload_header(); + if (off || len != JL_LOADER_SIZE || pl_crc32(d, len, 0) != h->loader_crc32) return false; + have_loader = true; + return true; +} +bool jl_info(jl_info_t *i) { + if (!have_loader || !uboot) return false; + i->chip_key = chip_key; i->dev_type = 3; i->flash_id = flash_id; + return true; +} +uint16_t jl_read_chunk(void) { return 4096; } +bool jl_flash_read(uint32_t a, uint16_t n, uint8_t *b) { + if (!uboot || a + n > JL_FLASH_SIZE) return false; + memcpy(b, fm1 + a, n); + return true; +} +bool jl_flash_write_sector(uint32_t a, const uint8_t *d) { // same guard as jieli_uboot.c + if (a < JL_WRITE_MIN || a >= JL_WRITE_END || a % JL_SECTOR_SIZE) return false; + if (!uboot) return false; + if ((int)a == fail_writes_at) { memset(fm1 + a, 0x00, JL_SECTOR_SIZE); return false; } + memcpy(fm1 + a, d, JL_SECTOR_SIZE); + sector_writes[a / JL_SECTOR_SIZE]++; + return true; +} + +// ---- helpers ---- +static int failures; +#define CHECK(c, ...) do { if (!(c)) { failures++; printf(" FAIL: " __VA_ARGS__); printf("\n"); } } while (0) + +static uint8_t *region; // 0x8F000 bytes of V15 + +static void load_uf2(const char *path) { + FILE *f = fopen(path, "rb"); + if (!f) { perror(path); exit(2); } + memset(test_rp_flash, 0xFF, sizeof(test_rp_flash)); + uint8_t b[512]; + int n = 0; + while (fread(b, 1, 512, f) == 512) { + uint32_t addr, size; + memcpy(&addr, b + 12, 4); + memcpy(&size, b + 16, 4); + if (addr < 0x10000000 || addr + size > 0x10000000 + sizeof(test_rp_flash)) { printf("bad block\n"); exit(2); } + memcpy(test_rp_flash + (addr - 0x10000000), b + 32, size); + n++; + } + fclose(f); + printf("loaded %d UF2 blocks\n", n); +} + +static void reset_unit(uint8_t fill) { + for (uint32_t a = 0; a < JL_FLASH_SIZE; a++) fm1[a] = (uint8_t)(fill ^ (a * 7) ^ (a >> 9)); + memset(sector_writes, 0, sizeof(sector_writes)); + uboot = true; v15 = false; have_loader = false; + chip_key = JL_CHIP_KEY; flash_id = JL_FLASH_ID; fail_writes_at = -1; softkeys = 0; + memset(&test_watchdog, 0, sizeof(test_watchdog)); +} + +static ar_state_t drive(int steps) { + ar_init(); + for (int i = 0; i < steps; i++) { + ar_task(); + now_us += 100000; + ar_state_t s = ar_state(); + if (s == AR_DONE || s == AR_ERROR || s == AR_BAD_PAYLOAD || s == AR_OFF) break; + } + return ar_state(); +} + +static void check_untouched(const uint8_t *before) { + CHECK(memcmp(fm1, before, JL_WRITE_MIN) == 0, "boot head changed"); + CHECK(memcmp(fm1 + JL_WRITE_END, before + JL_WRITE_END, JL_FLASH_SIZE - JL_WRITE_END) == 0, + "data area 0x93000.. changed"); +} + +int main(int argc, char **argv) { + if (argc < 3) { fprintf(stderr, "usage: host_test RESCUE.uf2 REGION.bin [-v]\n"); return 2; } + quiet = !(argc > 3 && !strcmp(argv[3], "-v")); + load_uf2(argv[1]); + region = malloc(PL_IMAGE_LEN); + FILE *f = fopen(argv[2], "rb"); + if (!f || fread(region, 1, PL_IMAGE_LEN, f) != PL_IMAGE_LEN) { perror(argv[2]); return 2; } + fclose(f); + static uint8_t before[JL_FLASH_SIZE]; + + printf("0. before the payload is checked the status says boot, never off\n"); + { + char line[160]; + ar_status_line(line, sizeof(line)); + CHECK(strncmp(line, "state=boot ", 11) == 0, "status line: %s", line); + } + + printf("1. bricked unit (random app region) -> restored, head and data untouched\n"); + reset_unit(0x5A); + memcpy(before, fm1, sizeof(fm1)); + CHECK(drive(100) == AR_DONE, "state %s", ar_describe()); + CHECK(memcmp(fm1 + JL_WRITE_MIN, region, PL_IMAGE_LEN) == 0, "region != V15"); + check_untouched(before); + int total = 0; + for (int s = 0; s < (int)(JL_FLASH_SIZE / JL_SECTOR_SIZE); s++) { + total += sector_writes[s]; + CHECK(sector_writes[s] <= 1, "sector %05X written %d times", s * 4096, sector_writes[s]); + } + CHECK(total == 143, "%d sectors written, expected 143", total); + char line[160]; + ar_status_line(line, sizeof(line)); + CHECK(strstr(line, "state=done phase=idle sector=143/143 written=143 same=0") != NULL, + "status line: %s", line); + + printf("2. half-written unit -> only the differing sectors are written\n"); + reset_unit(0x11); + memcpy(fm1 + JL_WRITE_MIN, region, 40 * JL_SECTOR_SIZE); + memcpy(before, fm1, sizeof(fm1)); + CHECK(drive(100) == AR_DONE, "state %s", ar_describe()); + total = 0; + for (int s = 0; s < 4 + 40; s++) total += sector_writes[s]; + CHECK(total == 0, "%d already-right sectors were rewritten", total); + CHECK(memcmp(fm1 + JL_WRITE_MIN, region, PL_IMAGE_LEN) == 0, "region != V15"); + check_untouched(before); + + printf("3. unit already on V15 -> nothing written\n"); + reset_unit(0x22); + memcpy(fm1 + JL_WRITE_MIN, region, PL_IMAGE_LEN); + CHECK(drive(100) == AR_DONE, "state %s", ar_describe()); + total = 0; + for (int s = 0; s < (int)(JL_FLASH_SIZE / JL_SECTOR_SIZE); s++) total += sector_writes[s]; + CHECK(total == 0, "%d sectors written", total); + + printf("4. running stock V15 -> soft key, then restore\n"); + reset_unit(0x33); + uboot = false; v15 = true; + CHECK(drive(200) == AR_DONE, "state %s", ar_describe()); + CHECK(softkeys == 1, "%d soft keys", softkeys); + + printf("5. wrong chip / flash -> error, nothing written\n"); + reset_unit(0x44); + flash_id = 0xEF4014; + memcpy(before, fm1, sizeof(fm1)); + CHECK(drive(100) == AR_ERROR, "state %s", ar_describe()); + CHECK(memcmp(fm1, before, sizeof(fm1)) == 0, "flash changed"); + reset_unit(0x44); + flash_id = 0xB36014; // the 2026 part is accepted + CHECK(drive(100) == AR_DONE, "B36014: state %s", ar_describe()); + reset_unit(0x44); + chip_key = 0x1234; + CHECK(drive(100) == AR_ERROR, "bad key: state %s", ar_describe()); + + printf("6. a sector that never takes the write -> error\n"); + reset_unit(0x55); + fail_writes_at = 0x20000; + CHECK(drive(100) == AR_ERROR, "state %s", ar_describe()); + CHECK(strstr(ar_describe(), "err=write addr=020000") != NULL, "%s", ar_describe()); + + printf("7. second unit on the same board power cycle -> restored again\n"); + reset_unit(0x66); + CHECK(drive(100) == AR_DONE, "state %s", ar_describe()); + total = 0; + for (int s = 0; s < (int)(JL_FLASH_SIZE / JL_SECTOR_SIZE); s++) total += sector_writes[s]; + CHECK(total == 143, "%d sectors written", total); + + printf("8. damaged payload (one image byte flipped) -> refused, nothing written\n"); + reset_unit(0x77); + memcpy(before, fm1, sizeof(fm1)); + test_rp_flash[PL_FLASH_OFFSET + PL_IMAGE_OFF + 12345] ^= 1; + CHECK(drive(10) == AR_BAD_PAYLOAD, "state %s", ar_describe()); + CHECK(memcmp(fm1, before, sizeof(fm1)) == 0, "flash changed"); + test_rp_flash[PL_FLASH_OFFSET + PL_IMAGE_OFF + 12345] ^= 1; + + printf("9. no payload -> plain Transporter, rescue off\n"); + reset_unit(0x88); + memset(test_rp_flash + PL_FLASH_OFFSET, 0xFF, 16); + CHECK(drive(10) == AR_OFF, "state %s", ar_describe()); + + printf(failures ? "\n%d FAILURE(S)\n" : "\nall rescue host tests passed\n", failures); + return failures ? 1 : 0; +} diff --git a/rescue/firmware/test/run.sh b/rescue/firmware/test/run.sh new file mode 100755 index 00000000..40d69ef0 --- /dev/null +++ b/rescue/firmware/test/run.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Host test of the stand-alone rescue logic: test/run.sh RESCUE.uf2 V15_REGION.bin [-v] +set -e +HERE="$(cd "$(dirname "$0")" && pwd)" +OUT="${TMPDIR:-/tmp}/fm1-rescue-host-test" +cc -std=c11 -O1 -Wall -Wextra -Werror -I"$HERE/stub" -I"$HERE/../src" \ + "$HERE/host_test.c" "$HERE/../src/payload.c" "$HERE/../src/autorescue.c" -o "$OUT" +"$OUT" "$@" diff --git a/rescue/firmware/test/stub/hardware/flash.h b/rescue/firmware/test/stub/hardware/flash.h new file mode 100644 index 00000000..6f70f09b --- /dev/null +++ b/rescue/firmware/test/stub/hardware/flash.h @@ -0,0 +1 @@ +#pragma once diff --git a/rescue/firmware/test/stub/hardware/watchdog.h b/rescue/firmware/test/stub/hardware/watchdog.h new file mode 100644 index 00000000..8109a8c5 --- /dev/null +++ b/rescue/firmware/test/stub/hardware/watchdog.h @@ -0,0 +1,5 @@ +#pragma once +#include +typedef struct { uint32_t scratch[8]; } test_watchdog_t; +extern test_watchdog_t test_watchdog; +#define watchdog_hw (&test_watchdog) diff --git a/rescue/firmware/test/stub/pico/stdlib.h b/rescue/firmware/test/stub/pico/stdlib.h new file mode 100644 index 00000000..f48af9e6 --- /dev/null +++ b/rescue/firmware/test/stub/pico/stdlib.h @@ -0,0 +1,8 @@ +// Host stub for the rescue tests. +#pragma once +#include +#include +#include +extern uint8_t test_rp_flash[]; +#define XIP_BASE ((uintptr_t)test_rp_flash) +uint64_t time_us_64(void); diff --git a/rescue/fm1-rescue.html b/rescue/fm1-rescue.html new file mode 100644 index 00000000..bca6bd8f --- /dev/null +++ b/rescue/fm1-rescue.html @@ -0,0 +1,495 @@ + + + + + +FM-1 Rescue + + + +
+

FM-1 Rescue

+

+ +
+

1

+ + + +
+ +
+

2

+

+ +

+
+
+ +
+

3

+

+
+ +
+ +
+

4

+ +
+
+ +
+

5

+
    +
    + +
    +

    +
    +
    + +

    +
    + + + + diff --git a/rescue/make_page.py b/rescue/make_page.py new file mode 100755 index 00000000..e3d38450 --- /dev/null +++ b/rescue/make_page.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Make rescue/fm1-rescue.html: page.template.html with builder.js and the two +base firmware images (rescue/base/*.uf2) inlined, so the page works offline, +opened as a local file or from any static host. + + python3 rescue/make_page.py +""" +import base64 +import re +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def main(): + page = (HERE / "page.template.html").read_text(encoding="utf-8") + builder = (HERE / "builder.js").read_text(encoding="utf-8") + builder = re.sub(r"^export ", "", builder, flags=re.M) + for board in ("zero", "xiao", "pico"): + uf2 = (HERE / "base" / ("fm1-rescue-base-%s.uf2" % board)).read_bytes() + if len(uf2) % 512 or not uf2: + raise SystemExit("base/%s: not a UF2" % board) + mark = "%%%%BASE_%s%%%%" % board.upper() + if page.count(mark) != 1: + raise SystemExit("page.template.html must contain %s once" % mark) + page = page.replace(mark, base64.b64encode(uf2).decode()) + page = page.replace("%%BUILDER%%", builder) + if "%%" in page: + raise SystemExit("a placeholder was left in the page") + out = HERE / "fm1-rescue.html" + out.write_text(page, encoding="utf-8") + print("%s: %d bytes" % (out, len(page.encode()))) + + +if __name__ == "__main__": + main() diff --git a/rescue/make_uf2.mjs b/rescue/make_uf2.mjs new file mode 100644 index 00000000..ca47daaf --- /dev/null +++ b/rescue/make_uf2.mjs @@ -0,0 +1,27 @@ +#!/usr/bin/env node +// SPDX-License-Identifier: MIT +// Command-line version of fm1-rescue.html: +// node rescue/make_uf2.mjs BASE.uf2 FM-1.fwsc wl82loader.bin OUT.uf2 [REGION_OUT.bin] +// REGION_OUT.bin (optional): the V15 region 0x4000..0x92FFF, for test/run.sh. +import { readFileSync, writeFileSync } from "node:fs"; +import { buildRescueUf2, checkPackage } from "./builder.js"; + +const [base, fwsc, loader, out, regionOut] = process.argv.slice(2); +if (!out) { + console.error("usage: node make_uf2.mjs BASE.uf2 FM-1.fwsc wl82loader.bin OUT.uf2 [REGION_OUT.bin]"); + process.exit(2); +} +try { + const pkg = new Uint8Array(readFileSync(fwsc)); + const r = await buildRescueUf2({ + baseUf2: new Uint8Array(readFileSync(base)), + fwsc: pkg, + loader: new Uint8Array(readFileSync(loader)), + }); + writeFileSync(out, r.uf2); + if (regionOut) writeFileSync(regionOut, (await checkPackage(pkg)).region); + console.log(`${out}: ${r.uf2.length} bytes (${r.identity}${r.official ? ", official V15" : ", JIANT"})`); +} catch (e) { + console.error("refused: " + e.message); + process.exit(1); +} diff --git a/rescue/package.json b/rescue/package.json new file mode 100644 index 00000000..8898b262 --- /dev/null +++ b/rescue/package.json @@ -0,0 +1 @@ +{ "type": "module", "private": true } diff --git a/rescue/page.template.html b/rescue/page.template.html new file mode 100644 index 00000000..e580af78 --- /dev/null +++ b/rescue/page.template.html @@ -0,0 +1,240 @@ + + + + + +FM-1 Rescue + + + +
    +

    FM-1 Rescue

    +

    + +
    +

    1

    + + + +
    + +
    +

    2

    +

    + +

    +
    +
    + +
    +

    3

    +

    +
    + +
    + +
    +

    4

    + +
    +
    + +
    +

    5

    +
      +
      + +
      +

      +
      +
      + +

      +
      + + + +