From cd0841a76c5218bb0f34510fe422e32f615909cb Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Sat, 31 Oct 2026 06:01:41 -0700 Subject: [PATCH 1/2] Bluetooth MIDI on Felucca's platform --- LICENSES/Apache-2.0.txt | 201 +++++ LICENSING.md | 15 + README.md | 20 +- platform/ble/ble.h | 95 +++ platform/ble/ble_aes.c | 196 +++++ platform/ble/ble_aes.h | 40 + platform/ble/ble_att.c | 481 +++++++++++ platform/ble/ble_central.c | 340 ++++++++ platform/ble/ble_cfg.h | 239 ++++++ platform/ble/ble_diag.c | 623 ++++++++++++++ platform/ble/ble_diag.h | 329 ++++++++ platform/ble/ble_gattc.c | 341 ++++++++ platform/ble/ble_host.c | 320 ++++++++ platform/ble/ble_host.h | 68 ++ platform/ble/ble_hw.h | 160 ++++ platform/ble/ble_hw_stub.c | 43 + platform/ble/ble_hw_wl82.c | 1219 ++++++++++++++++++++++++++++ platform/ble/ble_hw_wl82_central.c | 471 +++++++++++ platform/ble/ble_ll.c | 840 +++++++++++++++++++ platform/ble/ble_ll.h | 100 +++ platform/ble/ble_ll_central.c | 536 ++++++++++++ platform/ble/ble_midi.c | 234 ++++++ platform/ble/ble_midi.h | 51 ++ platform/ble/ble_prim.c | 92 +++ platform/ble/ble_prim.h | 36 + platform/ble/ble_scan.c | 244 ++++++ platform/ble/ble_scan.h | 68 ++ platform/ble/ble_smp.c | 354 ++++++++ platform/ble/ble_smp_init.c | 309 +++++++ platform/ble/ble_stack.c | 29 + platform/ble/ble_store.c | 122 +++ platform/ble/ble_store.h | 72 ++ platform/ble/ble_util.h | 40 + platform/ble/ble_vm.c | 207 +++++ platform/ble/ble_vm.h | 94 +++ platform/ble/rf_share.h | 41 + platform/bt.c | 194 +++++ platform/fm1.c | 18 +- platform/fm1.h | 10 +- platform/hal/ble_rf_tables.h | 5 + platform/hal/ble_rf_tables_v15.h | 304 +++++++ platform/hal/fm1_ble.h | 321 ++++++++ platform/hal/fm1_ble_rf.h | 514 ++++++++++++ platform/hal/fm1_flash.h | 17 + platform/hal/fm1_rf_cal.h | 912 +++++++++++++++++++++ src/main.c | 2 +- tools/build.py | 4 +- 47 files changed, 10959 insertions(+), 12 deletions(-) create mode 100644 LICENSES/Apache-2.0.txt create mode 100644 platform/ble/ble.h create mode 100644 platform/ble/ble_aes.c create mode 100644 platform/ble/ble_aes.h create mode 100644 platform/ble/ble_att.c create mode 100644 platform/ble/ble_central.c create mode 100644 platform/ble/ble_cfg.h create mode 100644 platform/ble/ble_diag.c create mode 100644 platform/ble/ble_diag.h create mode 100644 platform/ble/ble_gattc.c create mode 100644 platform/ble/ble_host.c create mode 100644 platform/ble/ble_host.h create mode 100644 platform/ble/ble_hw.h create mode 100644 platform/ble/ble_hw_stub.c create mode 100644 platform/ble/ble_hw_wl82.c create mode 100644 platform/ble/ble_hw_wl82_central.c create mode 100644 platform/ble/ble_ll.c create mode 100644 platform/ble/ble_ll.h create mode 100644 platform/ble/ble_ll_central.c create mode 100644 platform/ble/ble_midi.c create mode 100644 platform/ble/ble_midi.h create mode 100644 platform/ble/ble_prim.c create mode 100644 platform/ble/ble_prim.h create mode 100644 platform/ble/ble_scan.c create mode 100644 platform/ble/ble_scan.h create mode 100644 platform/ble/ble_smp.c create mode 100644 platform/ble/ble_smp_init.c create mode 100644 platform/ble/ble_stack.c create mode 100644 platform/ble/ble_store.c create mode 100644 platform/ble/ble_store.h create mode 100644 platform/ble/ble_util.h create mode 100644 platform/ble/ble_vm.c create mode 100644 platform/ble/ble_vm.h create mode 100644 platform/ble/rf_share.h create mode 100644 platform/bt.c create mode 100644 platform/hal/ble_rf_tables.h create mode 100644 platform/hal/ble_rf_tables_v15.h create mode 100644 platform/hal/fm1_ble.h create mode 100644 platform/hal/fm1_ble_rf.h create mode 100644 platform/hal/fm1_rf_cal.h diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSING.md b/LICENSING.md index 6f99887..38e1786 100644 --- a/LICENSING.md +++ b/LICENSING.md @@ -13,6 +13,21 @@ The USB audio from a computer in `platform/src/usb.c` (`FOMA_USB_AUDIO`) is port it be used under GPL-3.0; foma's version uses integer math. The TRS MIDI input (`platform/src/midi_uart.c`, `platform/hal/fm1_uart.h`) is Felucca's. +Bluetooth MIDI on Felucca's platform (the `bluetooth` option): + +- `platform/ble/`: Henri David's (hdavid) BLE stack from [Optimist](https://github.com/w0ts/optimist), as + [fm1-base](https://github.com/charlesvestal/fm1-base) (Charles Vestal) carries it in `bt/ble` (commit 4039a8b, with + its one fix in `ble_att.c`). Its files are `GPL-3.0-only OR MPL-2.0` + ([w0ts/optimist#55](https://github.com/w0ts/optimist/issues/55)), used here under GPL-3.0-only. +- `platform/hal/fm1_ble.h`, `fm1_ble_rf.h`: the radio drivers, Optimist's, from + [felucca-bsp](https://github.com/hugelton/felucca-bsp) (commit b0b2428), `GPL-3.0-only OR MPL-2.0`. The flash's + unique-ID read (`fl_uid_ram` in `platform/hal/fm1_flash.h`) is felucca-bsp's too (MPL-2.0). +- `platform/hal/ble_rf_tables_v15.h` (the radio's start-up writes, recorded from M-VAVE's stock V15 firmware: JieLi's + and M-VAVE's) and `platform/hal/fm1_rf_cal.h` (JieLi's radio calibration, rewritten in C by Charles Vestal), from + felucca-bsp (b0b2428): Apache-2.0 (`LICENSES/Apache-2.0.txt`, which a firmware built with them ships). Their + headers say where they come from and what changed. +- `platform/bt.c` (the glue) is foma's; the radio's constant trims in it are fm1-base's. + `platform/mvave` (the `"mvave"` platform) is from M-VAVE's [fm1_open](https://github.com/m-vave/fm1_open) (commit in `platform/mvave/sdk/VERSION`): `board/`, `sdk/include`, `sdk/config` and the boot resources are GPLv3 with M-VAVE's FM1 SDK linking exception or Apache-2.0, `sdk/lib/libfm1_engine.a` is M-VAVE's binary SDK under its own diff --git a/README.md b/README.md index 63eab2f..43aa453 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ turning one off takes its code and memory out of the firmware: | `usb_audio` | A computer or tablet can pick the FM-1 as a 44.1 kHz stereo output. `audio_in()` gives `audio()` that sound: play it, process it, record it. | 10 KiB RAM | | `trs_midi` | MIDI in on the 3.5 mm TRS jack (a TRS-to-DIN adapter for most gear), through `midi_read()`, which says where each message came from. | <1 KiB | | `midi_clock` | One MIDI clock for `audio()`: its own tempo or the clock coming in, sent out over USB if you like. `clock_events()` gives each block's ticks, start and stop at the frame they fall on. | 1 KiB RAM | -| `bluetooth` | Only with `"platform": "mvave"` (below), and on there unless turned off: BLE MIDI in and out, and audio from a phone or computer. | <1 KiB | +| `bluetooth` | BLE MIDI in and out ([below](#bluetooth-midi)). Off unless turned on; on by default with `"platform": "mvave"`, which also has audio from a phone or computer. | 30 KiB code, 6 KiB RAM | ```json { "name": "MY SYNTH", "version": "0.1", "identity": "FM-1_95", "options": { "usb_audio": false } } @@ -77,6 +77,24 @@ In your code, `#if FOMA_USB_AUDIO` (and `FOMA_TRS_MIDI`, `FOMA_MIDI_CLOCK`, `FOM FM-1 has no MIDI out on the TRS jack, so that can't be an option. The emulator follows MIDI clock from Web MIDI; it has no USB audio input (`audio_in()` gives 0) and no Bluetooth (the calls answer "not ready"). +### Bluetooth MIDI + +`"options": { "bluetooth": true }` makes the FM-1 a Bluetooth MIDI device that a computer, phone or tablet connects +to. `bt_enable(BT_MIDI)` (from `loop()`) starts it; until then none of it runs. It shows up as your firmware's name +and four hex digits (`FOMA FC75`), the same on every boot. MIDI from it comes in through `midi_read` (`MIDI_BLE`), +clock and start / stop through the clock helper (`clock_follow(MIDI_BLE)`), and `midi_send` goes out over it too. +`bt_status()` says whether it's advertising, connected or ready for MIDI. Notes held when the link drops get their +note-offs. + +On Felucca's platform it's Henri David's Bluetooth stack from [Optimist](https://github.com/w0ts/optimist) with the +radio drivers of [felucca-bsp](https://github.com/hugelton/felucca-bsp) (`platform/ble`, `platform/hal/fm1_ble*.h`, +`platform/bt.c`): written from the Bluetooth specifications and measurements of the FM-1's radio, no JieLi library. +It calibrates the radio when it starts, so nothing stored on the FM-1 is needed. It's a peripheral only: no pairing +(macOS and iOS connect without it), no connecting out to a controller (`ble_central` answers "not ready") and no +audio. Tested on an FM-1 with a Mac, both ways. + +To connect from a Mac: Audio MIDI Setup, Window > Show MIDI Studio, the Bluetooth button, then Connect. + ### Platforms: Felucca's, or M-VAVE's SDK (Bluetooth) `"platform"` in `firmware.json` picks what runs under your code on the FM-1. Your code and `fm1.h` stay the same. diff --git a/platform/ble/ble.h b/platform/ble/ble.h new file mode 100644 index 0000000..833d956 --- /dev/null +++ b/platform/ble/ble.h @@ -0,0 +1,95 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The BLE-MIDI peripheral as the firmware sees it (route C: our own stack, docs/BLE-STACK.md). + * + * ble_init(addr, random) once at start, before the driver's interrupts are on + * ble_enable(on) advertise as BLE_DEVICE_NAME with the BLE-MIDI service / stop and disconnect + * ble_midi_ready() a central is connected and has turned the MIDI notifications on + * + * The firmware gives the stack its MIDI through four functions (io/midi/midi_ble.c, or a test's fakes). All + * are called from the BLE interrupts' context (ble_hw.h); they must only touch single-producer rings. */ +#ifndef BLE_H +#define BLE_H +#include +#include "ble_cfg.h" + +BLE_API void ble_init(const uint8_t addr[6], uint8_t addr_random); +BLE_API void ble_enable(int on); +BLE_API int ble_midi_ready(void); +BLE_API int ble_connected(void); + +/* ---- the firmware implements these ---- */ +/* the oldest MIDI event waiting to go out (a USB-MIDI event packet and the millisecond it happened): 1, or 0 + * when there is none. The stack takes it with ble_app_midi_pop() once it is in a notification. */ +BLE_API int ble_app_midi_peek(uint32_t *pkt, uint32_t *t_ms); +BLE_API void ble_app_midi_pop(void); +/* one message received (a USB-MIDI event packet), with its 13-bit timestamp and the last timestamp of the + * BLE packet it came in (the newest: the difference is how long before the packet's end it happened) */ +BLE_API void ble_app_midi_in(uint32_t pkt, uint16_t ts, uint16_t last_ts); +/* a central connected (1) or left (0); its MIDI notifications on or off (ble_midi_ready()) */ +BLE_API void ble_app_state(void); +#if BLE_SMP_LEGACY +/* a central bonded: its key (Rand, EDIV, LTK least significant octet first) to keep across power-offs and give back + * with ble_host_set_key (ble_host.h) after ble_init. BLE interrupts' context: copy it and save it later */ +BLE_API void ble_app_bond(const uint8_t rand[8], uint16_t ediv, const uint8_t ltk[16]); +/* the bonded peer's identity (SMP Identity Information + Identity Address Information): its IRK and identity address + * (least significant octet first; addr_rand 1 random static, 0 public). BLE interrupts' context: copy it */ +BLE_API void ble_app_peer_id(const uint8_t irk[16], const uint8_t addr[6], uint8_t addr_rand); +#endif + +#if BLE_CENTRAL +/* ---- connecting out as central (BLE_CENTRAL, docs/BLE-DEVICES-DESIGN.md §4; ble_central.c) */ +struct ble_peer { + uint8_t addr[6], addr_rand; /* its AdvA as heard now (least significant octet first; an RPA stays one) */ + uint8_t bonded; /* ltk / rand / ediv are its bond: the link is encrypted with them */ + uint8_t sec; /* BLE_PEER_*: what is known of its security */ + uint8_t ltk[16], rand[8]; + uint16_t ediv; +}; +#define BLE_PEER_AUTH 1u /* the bond is authenticated (a passkey pairing: MITM protection) */ +#define BLE_PEER_MITM 2u /* it needs an authenticated link: a pairing goes straight to the passkey */ +/* the keys a pairing as initiator took from the peripheral (Core Vol 3 Part H 3.6) */ +#define BLE_KEYS_LTK 1u /* ltk / rand / ediv: the bond (Encryption Information, Master Identification) */ +#define BLE_KEYS_ID 2u /* irk / id / id_rand: its identity (Identity Information + Address) */ +#define BLE_KEYS_AUTH 4u /* the pairing was authenticated (passkey entry): the LTK has MITM protection */ +struct ble_keys { + uint8_t has; /* BLE_KEYS_* */ + uint8_t ltk[16], rand[8]; + uint16_t ediv; + uint8_t irk[16], id[6], id_rand; +}; +enum { BLE_CS_IDLE, BLE_CS_CONNECTING, BLE_CS_SETUP, BLE_CS_READY }; /* ble_central_state */ +enum { BLE_CF_NONE, BLE_CF_LOST, BLE_CF_NO_MIDI, BLE_CF_PAIRING, BLE_CF_AUTH, BLE_CF_GATT, + BLE_CF_NEED_MITM, BLE_CF_KEY, BLE_CF_NEED_PAIR }; /* ble_central_fail; NEED_MITM: it needs a passkey and + * refused the pairing with MITM on the link (Just Works refused before): connect again + * with BLE_PEER_MITM, without the unauthenticated bond; KEY: it left while our encryption + * with p's bond was starting (MIC Failure 0x3D, Key Missing 0x06: the bond is no good to + * it); NEED_PAIR (BLE_CENTRAL 3): it asked for security (a Security Request, Insufficient Authentication / Encryption), + * and this level does not pair */ +/* initiate to p (advertising or scanning stop: one link) -> 1 started, 0 not now (off, or a link is up). From there: + * connected as master, the BLE-MIDI characteristic found and subscribed (pairing or encrypting with p's bond when the + * peripheral asks, or wants it), MIDI both ways: BLE_CS_READY. Called like ble_enable (the BLE interrupts held) */ +BLE_API int ble_central_connect(const struct ble_peer *p); +BLE_API void ble_central_cancel(void); /* stop initiating, or leave our central link (a peripheral link stays) */ +BLE_API uint8_t ble_central_state(void); +BLE_API uint8_t ble_central_fail(void); /* why the last connection out ended before / after READY (BLE_CF_*) */ +BLE_API uint8_t ble_central_code(void); /* ... its code: the LL reason, the ATT error or the SMP reason */ +#if BLE_CEN_PAIR +BLE_API int ble_central_pairing(void); /* 1: a pairing of ours runs on the link */ +BLE_API int ble_central_prompted(void); /* 1: a pairing of ours started on the last attempt's link (a phone asked its + * user): the firmware does not make that link again by itself */ +BLE_API int ble_central_mitm(void); /* 1: the last attempt's peer needs an authenticated link (a passkey) */ +#endif +/* the passkey to show while a passkey pairing waits for the peer's user (Core Vol 3 Part H 2.3.5.3: we display, the + * phone's user types it), 0..999999; BLE_NO_PASSKEY when there is none (always at BLE_CENTRAL 3) */ +#define BLE_NO_PASSKEY 0xFFFFFFFFu +#if BLE_CEN_PAIR +BLE_API uint32_t ble_central_passkey(void); +/* 1: addr is a resolvable private address made from irk (ah, Core Vol 3 Part H 2.2.2; least significant first) */ +BLE_API int ble_rpa_resolve(const uint8_t irk[16], const uint8_t addr[6]); +/* the firmware implements: a pairing as initiator ended with these keys of the peripheral (BLE interrupts' context: + * copy them) */ +BLE_API void ble_app_central_keys(const struct ble_keys *k); +#endif +#endif + +#endif diff --git a/platform/ble/ble_aes.c b/platform/ble/ble_aes.c new file mode 100644 index 0000000..fd45fce --- /dev/null +++ b/platform/ble/ble_aes.c @@ -0,0 +1,196 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* AES-128 encryption (FIPS-197) for size: the round keys are made on the fly, one S-box, no T-tables. CCM as the + * LL uses it (Core Specification Vol 6 Part E 2): M = 4 (MIC), L = 2, a 13-octet nonce of the 39-bit packet + * counter, the direction bit and the IV; one octet of additional data, the PDU header with NESN, SN and MD + * cleared. */ +#include "ble_aes.h" +#include "ble_util.h" + +#ifndef BLE_AES_HW +static const uint8_t ble_sbox[256] = { + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; + +static uint8_t ble_xt(uint32_t x) { return (uint8_t)(x << 1 ^ (x >> 7) * 0x1Bu); } + +BLE_API void ble_aes128(const uint8_t key[16], const uint8_t in[16], uint8_t out[16]) +{ + uint8_t s[16], k[16], t[16]; + uint32_t i, r, rc = 1; + for (i = 0; i < 16u; i++) { + k[i] = key[i]; + s[i] = (uint8_t)(in[i] ^ key[i]); + } + for (r = 1; r <= 10u; r++) { + for (i = 0; i < 16u; i++) /* SubBytes and ShiftRows (column-major: row = i & 3) */ + t[i] = ble_sbox[s[(i + 4u * (i & 3u)) & 15u]]; + for (i = 0; i < 16u; i += 4) { /* MixColumns (not in the last round) */ + uint8_t a0 = t[i], a1 = t[i + 1], a2 = t[i + 2], a3 = t[i + 3], x = (uint8_t)(a0 ^ a1 ^ a2 ^ a3); + if (r == 10u) { + s[i] = a0, s[i + 1] = a1, s[i + 2] = a2, s[i + 3] = a3; + continue; + } + s[i] = (uint8_t)(a0 ^ x ^ ble_xt(a0 ^ a1)); + s[i + 1] = (uint8_t)(a1 ^ x ^ ble_xt(a1 ^ a2)); + s[i + 2] = (uint8_t)(a2 ^ x ^ ble_xt(a2 ^ a3)); + s[i + 3] = (uint8_t)(a3 ^ x ^ ble_xt(a3 ^ a0)); + } + k[0] ^= (uint8_t)(ble_sbox[k[13]] ^ rc); /* the next round key */ + k[1] ^= ble_sbox[k[14]]; + k[2] ^= ble_sbox[k[15]]; + k[3] ^= ble_sbox[k[12]]; + for (i = 4; i < 16u; i++) + k[i] ^= k[i - 4u]; + rc = ble_xt(rc); + for (i = 0; i < 16u; i++) + s[i] ^= k[i]; + } + ble_cpy(out, s, 16); +} +#endif + +/* block 0 of the counter (A_i, flags 0x01) or MAC (B_0, flags 0x49) sequence */ +static void ble_ccm_block(const struct ble_ccm *c, uint8_t flags, uint32_t tail, uint8_t b[16]) +{ + b[0] = flags; + b[1] = (uint8_t)c->ctr; + b[2] = (uint8_t)(c->ctr >> 8); + b[3] = (uint8_t)(c->ctr >> 16); + b[4] = (uint8_t)(c->ctr >> 24); + b[5] = (uint8_t)((c->ctr_hi & 0x7Fu) | (uint32_t)c->dir << 7); + ble_cpy(b + 6, c->iv, 8); + b[14] = (uint8_t)(tail >> 8); /* the length (B_0) or the block counter (A_i), big-endian */ + b[15] = (uint8_t)tail; +} + +/* the MIC over plain text p (len octets): T xor S_0 */ +static void ble_ccm_mic(const struct ble_ccm *c, uint8_t hdr, const uint8_t *p, uint32_t len, uint8_t mic[4]) +{ + uint8_t x[16], b[16]; + uint32_t i, j; + ble_ccm_block(c, 0x49u, len, b); + ble_aes128(c->key, b, x); + x[0] ^= 0x00; /* B_1: the additional data's length (1) and the header */ + x[1] ^= 0x01; + x[2] ^= (uint8_t)(hdr & 0xE3u); + ble_aes128(c->key, x, x); + for (i = 0; i < len; i += 16) { + for (j = 0; j < 16u && i + j < len; j++) + x[j] ^= p[i + j]; + ble_aes128(c->key, x, x); + } + ble_ccm_block(c, 0x01u, 0, b); + ble_aes128(c->key, b, b); + for (i = 0; i < 4u; i++) + mic[i] = (uint8_t)(x[i] ^ b[i]); +} + +static void ble_ccm_ctr(const struct ble_ccm *c, uint8_t *p, uint32_t len) +{ + uint8_t s[16]; + uint32_t i, j; + for (i = 0; i < len; i += 16) { + ble_ccm_block(c, 0x01u, i / 16u + 1u, s); + ble_aes128(c->key, s, s); + for (j = 0; j < 16u && i + j < len; j++) + p[i + j] ^= s[j]; + } +} + +static void ble_ccm_step(struct ble_ccm *c) +{ + if (!++c->ctr) + c->ctr_hi = (uint8_t)((c->ctr_hi + 1u) & 0x7Fu); +} + +BLE_API void ble_ccm_encrypt(struct ble_ccm *c, uint8_t hdr, uint8_t *p, uint8_t len) +{ + ble_ccm_mic(c, hdr, p, len, p + len); + ble_ccm_ctr(c, p, len); + ble_ccm_step(c); +} + +BLE_API int ble_ccm_decrypt(struct ble_ccm *c, uint8_t hdr, uint8_t *p, uint8_t len) +{ + uint8_t mic[4]; + if (len < 5u) + return 0; + len = (uint8_t)(len - 4u); + ble_ccm_ctr(c, p, len); + ble_ccm_mic(c, hdr, p, len, mic); + if (!ble_eq(mic, p + len, 4)) { + ble_ccm_ctr(c, p, len); /* leave the cipher text as it came */ + return 0; + } + ble_ccm_step(c); + return 1; +} + +#if BLE_SMP_LEGACY +/* e() on values as SMP sends them, least significant octet first */ +static void ble_e_le(const uint8_t k[16], const uint8_t in[16], uint8_t out[16]) +{ + uint8_t kb[16], ib[16], ob[16]; + uint32_t i; + for (i = 0; i < 16u; i++) { + kb[i] = k[15u - i]; + ib[i] = in[15u - i]; + } + ble_aes128(kb, ib, ob); + for (i = 0; i < 16u; i++) + out[i] = ob[15u - i]; +} + +/* the confirm value function c1 (Core Vol 3 Part H 2.2.3), everything least significant octet first: + * p1 = pres || preq || rat' || iat', p2 = padding || ia || ra, c1 = e(k, e(k, r ^ p1) ^ p2) */ +BLE_API void ble_smp_c1(const uint8_t k[16], const uint8_t r[16], const uint8_t preq[7], const uint8_t pres[7], + uint8_t iat, const uint8_t ia[6], uint8_t rat, const uint8_t ra[6], uint8_t out[16]) +{ + uint8_t p[16], x[16]; + uint32_t i; + p[0] = iat; + p[1] = rat; + ble_cpy(p + 2, preq, 7); + ble_cpy(p + 9, pres, 7); + for (i = 0; i < 16u; i++) + x[i] = (uint8_t)(r[i] ^ p[i]); + ble_e_le(k, x, x); + ble_cpy(p, ra, 6); + ble_cpy(p + 6, ia, 6); + ble_zero(p + 12, 4); + for (i = 0; i < 16u; i++) + x[i] ^= p[i]; + ble_e_le(k, x, out); +} + +/* the key generation function s1 (Core Vol 3 Part H 2.2.4): e(k, r1' || r2'), r1' and r2' the low 64 bits */ +BLE_API void ble_smp_s1(const uint8_t k[16], const uint8_t r1[16], const uint8_t r2[16], uint8_t out[16]) +{ + uint8_t x[16]; + ble_cpy(x, r2, 8); + ble_cpy(x + 8, r1, 8); + ble_e_le(k, x, out); +} + +BLE_API void ble_smp_passkey_tk(uint32_t passkey, uint8_t tk[16]) +{ + ble_zero(tk, 16); + tk[0] = (uint8_t)passkey; + tk[1] = (uint8_t)(passkey >> 8); + tk[2] = (uint8_t)(passkey >> 16); +} +#endif diff --git a/platform/ble/ble_aes.h b/platform/ble/ble_aes.h new file mode 100644 index 0000000..4a92d65 --- /dev/null +++ b/platform/ble/ble_aes.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* AES-128 (FIPS-197, encryption only) and the LL's AES-CCM (Core Specification Vol 6 Part E, sample data in + * Vol 6 Part C 1). Byte order: AES's own (the Bluetooth security function e() with its most significant octet + * first); the LL turns the least-significant-first fields it receives around before calling it. + * + * Replacing the software AES with the chip's AES block: build with BLE_AES_HW=1 and give the driver a + * ble_aes128() with this signature; ble_aes.c then leaves its own out. CCM stays here, on top of it. */ +#ifndef BLE_AES_H +#define BLE_AES_H +#include +#include "ble_cfg.h" + +BLE_API void ble_aes128(const uint8_t key[16], const uint8_t in[16], uint8_t out[16]); + +/* one direction of an encrypted link */ +struct ble_ccm { + uint8_t key[16]; /* the session key SK, most significant octet first */ + uint8_t iv[8]; /* IV = IVm || IVs as the nonce takes it: IVm's octets (least significant + * first) then IVs's */ + uint32_t ctr; /* packetCounter, low 32 bits */ + uint8_t ctr_hi; /* ... and bits 32..38 */ + uint8_t dir; /* directionBit: 1 central -> peripheral, 0 peripheral -> central */ +}; +/* p: the payload (len octets, 1..251 - 4); the MIC goes after it. The counter steps on. */ +BLE_API void ble_ccm_encrypt(struct ble_ccm *c, uint8_t hdr, uint8_t *p, uint8_t len); +/* p: payload and MIC (len octets, 5..255); 1 if the MIC is right (p then holds len - 4 octets of plain text, + * and the counter steps on), 0 if not */ +BLE_API int ble_ccm_decrypt(struct ble_ccm *c, uint8_t hdr, uint8_t *p, uint8_t len); + +#if BLE_SMP_LEGACY +/* LE legacy pairing's c1 and s1 (Core Vol 3 Part H 2.2.3, 2.2.4); every value least significant octet first, as SMP + * sends it; preq / pres: the Pairing Request / Response PDUs (opcode first); iat / rat: 1 for a random address */ +BLE_API void ble_smp_c1(const uint8_t k[16], const uint8_t r[16], const uint8_t preq[7], const uint8_t pres[7], + uint8_t iat, const uint8_t ia[6], uint8_t rat, const uint8_t ra[6], uint8_t out[16]); +BLE_API void ble_smp_s1(const uint8_t k[16], const uint8_t r1[16], const uint8_t r2[16], uint8_t out[16]); +/* passkey entry's TK (2.3.5.3): the passkey 0..999999 as a 128-bit value, least significant octet first */ +BLE_API void ble_smp_passkey_tk(uint32_t passkey, uint8_t tk[16]); +#endif + +#endif diff --git a/platform/ble/ble_att.c b/platform/ble/ble_att.c new file mode 100644 index 0000000..5cb0cab --- /dev/null +++ b/platform/ble/ble_att.c @@ -0,0 +1,481 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The ATT server (Core Specification Vol 3 Part F) over a static GATT database (Part G), and the BLE-MIDI + * service's data path. + * + * Handles (fixed: Service Changed is never indicated, the database never changes while we run; docs/BLE-STACK.md §5): + * 1 GAP service 0x1800 2,3 Device Name (read) 4,5 Appearance (read) + * 6,7 Peripheral Preferred Connection Parameters (read) + * 8 GATT service 0x1801 9,10 Service Changed (indicate) 11 its CCCD + * 12 BLE-MIDI service 03B80E5A-… 13,14 MIDI I/O 7772E5DB-… (read: empty, write without response, notify) + * 15 its CCCD + * Requests: MTU exchange, Find Information, Find By Type Value, Read By Type, Read, Read Blob, Read By Group Type, + * Write Request and Command; notifications and the Service Changed indication with its confirmation. Anything + * else: Request Not Supported (commands: ignored). No attribute needs security, but with BLE_MIDI_NEED_ENC the MIDI + * I/O value and its CCCD (Insufficient Authentication until the link is encrypted). */ +#include "ble.h" +#include "ble_host.h" +#include "ble_ll.h" +#include "ble_midi.h" +#include "ble_util.h" +#include "ble_diag.h" + +/* the MIDI I/O characteristic 7772E5DB-3868-4112-A1A9-F2669D106BF3, least significant octet first */ +static const uint8_t ATT_UUID_MIDI_IO[16] = {0xF3, 0x6B, 0x10, 0x9D, 0x66, 0xF2, 0xA9, 0xA1, + 0x12, 0x41, 0x68, 0x38, 0xDB, 0xE5, 0x72, 0x77}; +/* the Bluetooth base UUID 0000xxxx-0000-1000-8000-00805F9B34FB, octets 12 and 13 left for the 16-bit value */ +static const uint8_t ATT_BASE[16] = {0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +enum { H_GAP = 1, H_NAME_D, H_NAME, H_APP_D, H_APP, H_PPCP_D, H_PPCP, H_GATT, H_SC_D, H_SC, H_SC_CCC, H_MIDI, + H_MIDI_D, H_MIDI_IO, H_MIDI_CCC, H_LAST = H_MIDI_CCC }; +enum { A_R = 1, A_W = 2, A_SVC = 4, A_128 = 8 }; /* readable, writable, a service declaration, 128-bit type */ +enum { ATT_ERR_HANDLE = 0x01, ATT_ERR_READ = 0x02, ATT_ERR_WRITE = 0x03, ATT_ERR_PDU = 0x04, ATT_ERR_AUTHEN = 0x05, + ATT_ERR_NOT_SUPP = 0x06, ATT_ERR_OFFSET = 0x07, ATT_ERR_NOT_FOUND = 0x0A, ATT_ERR_VAL_LEN = 0x0D, + ATT_ERR_GROUP = 0x10 }; + +static const uint8_t V_GAP[] = {0x00, 0x18}, V_GATT[] = {0x01, 0x18}; +static const uint8_t V_NAME_D[] = {0x02, H_NAME, 0, 0x00, 0x2A}, V_APP_D[] = {0x02, H_APP, 0, 0x01, 0x2A}; +static const uint8_t V_PPCP_D[] = {0x02, H_PPCP, 0, 0x04, 0x2A}, V_SC_D[] = {0x20, H_SC, 0, 0x05, 0x2A}; +static const uint8_t V_APP[] = {BLE_APPEARANCE & 0xFF, BLE_APPEARANCE >> 8}; +static const uint8_t V_PPCP[] = {BLE_CONN_MIN & 0xFF, BLE_CONN_MIN >> 8, BLE_CONN_MAX & 0xFF, BLE_CONN_MAX >> 8, + BLE_CONN_LATENCY & 0xFF, BLE_CONN_LATENCY >> 8, BLE_CONN_TIMEOUT & 0xFF, + BLE_CONN_TIMEOUT >> 8}; +static const uint8_t V_SC[] = {0x01, 0x00, 0xFF, 0xFF}; +static const uint8_t V_MIDI_D[] = {0x16, H_MIDI_IO, 0, 0xF3, 0x6B, 0x10, 0x9D, 0x66, 0xF2, 0xA9, 0xA1, + 0x12, 0x41, 0x68, 0x38, 0xDB, 0xE5, 0x72, 0x77}; /* read, write w/o rsp, notify */ + +static const struct { + uint16_t type; /* 16-bit UUID (A_128: the MIDI I/O characteristic's) */ + uint8_t flags, len; + const uint8_t *val; /* (0: a value kept in RAM) */ +} ATT_DB[H_LAST + 1] = { + {0, 0, 0, 0}, + {0x2800, A_R | A_SVC, 2, V_GAP}, + {0x2803, A_R, 5, V_NAME_D}, + {0x2A00, A_R, 1, 0}, /* (the name in RAM: ble_gap_name, "Optimist XXXX") */ + {0x2803, A_R, 5, V_APP_D}, + {0x2A01, A_R, 2, V_APP}, + {0x2803, A_R, 5, V_PPCP_D}, + {0x2A04, A_R, 8, V_PPCP}, + {0x2800, A_R | A_SVC, 2, V_GATT}, + {0x2803, A_R, 5, V_SC_D}, + {0x2A05, 0, 4, V_SC}, + {0x2902, A_R | A_W, 2, 0}, + {0x2800, A_R | A_SVC, 16, BLE_UUID_MIDI_SVC}, + {0x2803, A_R, 19, V_MIDI_D}, + {0, A_R | A_W | A_128, 0, 0}, + {0x2902, A_R | A_W, 2, 0}, +}; + +static struct { + uint16_t mtu; + uint8_t ccc_sc, ccc_midi; /* the client's CCCD values (bit 0 notify, bit 1 indicate) */ + uint8_t sc_due, ind_wait; /* a Service Changed indication to send / waiting for its confirmation */ + struct ble_midi_enc enc; + struct ble_midi_dec dec; + uint8_t buf[BLE_ATT_MTU_MAX]; /* responses and notifications */ + uint8_t dyn[2]; /* a RAM value read out */ +} batt; + +BLE_API void ble_att_reset(void) +{ + batt.mtu = 23; + batt.ccc_sc = batt.ccc_midi = batt.sc_due = batt.ind_wait = 0; + ble_midi_enc_reset(&batt.enc); + ble_midi_dec_reset(&batt.dec); +} + +BLE_API int ble_midi_ready(void) +{ +#if BLE_CENTRAL + if (ble_ll_central()) + return ble_gattc_midi() != 0; /* as central: the peripheral's notifications are on */ +#endif + return ble_ll_connected() && (batt.ccc_midi & 1u); +} + +BLE_API void ble_att_set_mtu(uint16_t client_mtu) +{ + batt.mtu = (uint16_t)ble_min(client_mtu < 23u ? 23u : client_mtu, BLE_ATT_MTU_MAX); +} + +BLE_API uint16_t ble_att_mtu(void) { return batt.mtu; } + +static void att_send(uint16_t n) { ble_ll_send(L2CAP_CID_ATT, batt.buf, n); } + +/* BLE_MIDI_NEED_ENC: the MIDI I/O value and its CCCD only over an encrypted link */ +static int att_need_enc(uint16_t h) +{ + return BLE_MIDI_NEED_ENC && (h == H_MIDI_IO || h == H_MIDI_CCC) && !ble_ll_encrypted(); +} + +static void att_error(uint8_t op, uint16_t h, uint8_t err) +{ + batt.buf[0] = 0x01; + batt.buf[1] = op; + ble_wr16(batt.buf + 2, h); + batt.buf[4] = err; + att_send(5); +} + +static uint8_t att_len(uint16_t h, const uint8_t **v) /* an attribute's value */ +{ + if (ATT_DB[h].val || !ATT_DB[h].len) { + *v = ATT_DB[h].val; + return ATT_DB[h].len; + } + if (h == H_NAME) + return ble_gap_name(v); + batt.dyn[0] = h == H_SC_CCC ? batt.ccc_sc : batt.ccc_midi; + batt.dyn[1] = 0; + *v = batt.dyn; + return 2; +} + +/* the request's UUID (2 or 16 octets) as a 16-bit one; 0 for a 128-bit UUID that is not a base one */ +static uint16_t att_uuid16(const uint8_t *u, uint16_t n) +{ + if (n == 2u) + return ble_rd16(u); + if (n == 16u && ble_eq(u, ATT_BASE, 12) && !u[14] && !u[15]) + return ble_rd16(u + 12); + return 0; +} + +static int att_type_is(uint16_t h, const uint8_t *u, uint16_t n) +{ + if (ATT_DB[h].flags & A_128) + return n == 16u && ble_eq(u, ATT_UUID_MIDI_IO, 16); + return ATT_DB[h].type == att_uuid16(u, n) && ATT_DB[h].type; +} + +static uint16_t att_group_end(uint16_t h) /* the last handle of the service declared at h */ +{ + while (h < H_LAST && !(ATT_DB[h + 1u].flags & A_SVC)) + h++; + return h; +} + +static int att_range(const uint8_t *p, uint16_t *s, uint16_t *e) +{ + *s = ble_rd16(p + 1); + *e = ble_rd16(p + 3); + if (!*s || *s > *e) { + att_error(p[0], *s, ATT_ERR_HANDLE); + return 0; + } + return 1; +} + +static void att_find_info(const uint8_t *p) +{ + uint16_t s, e, h, k = 2; + if (!att_range(p, &s, &e)) + return; + batt.buf[0] = 0x05; + for (h = s; h <= e && h <= H_LAST; h++) { + uint8_t fmt = ATT_DB[h].flags & A_128 ? 2u : 1u, ul = fmt == 2u ? 16u : 2u; + if (k == 2u) + batt.buf[1] = fmt; + else if (batt.buf[1] != fmt) + break; + if (k + 2u + ul > batt.mtu) + break; + ble_wr16(batt.buf + k, h); + if (fmt == 2u) + ble_cpy(batt.buf + k + 2u, ATT_UUID_MIDI_IO, 16); + else + ble_wr16(batt.buf + k + 2u, ATT_DB[h].type); + k = (uint16_t)(k + 2u + ul); + } + if (k == 2u) + att_error(p[0], s, ATT_ERR_NOT_FOUND); + else + att_send(k); +} + +static void att_find_by_type(const uint8_t *p, uint16_t n) +{ + uint16_t s, e, h, k = 1, type = ble_rd16(p + 5); + if (!att_range(p, &s, &e)) + return; + batt.buf[0] = 0x07; + for (h = s; h <= e && h <= H_LAST && k + 4u <= batt.mtu; h++) { + const uint8_t *v; + uint8_t vl; + if ((ATT_DB[h].flags & A_128) || ATT_DB[h].type != type) + continue; + vl = att_len(h, &v); + if (vl != n - 7u || !ble_eq(v, p + 7, vl)) + continue; + ble_wr16(batt.buf + k, h); + ble_wr16(batt.buf + k + 2u, (ATT_DB[h].flags & A_SVC) ? att_group_end(h) : h); + k = (uint16_t)(k + 4u); + } + if (k == 1u) + att_error(p[0], s, ATT_ERR_NOT_FOUND); + else + att_send(k); +} + +/* Read By Type (0x08) and Read By Group Type (0x10): handle (+ group end) + value, all of one length */ +static void att_read_by(const uint8_t *p, uint16_t n) +{ + uint16_t s, e, h, k = 2, grp = p[0] == 0x10u, ul = (uint16_t)(n - 5u), t; + if (ul != 2u && ul != 16u) { + att_error(p[0], 0, ATT_ERR_PDU); + return; + } + if (!att_range(p, &s, &e)) + return; + t = att_uuid16(p + 5, ul); + if (grp && t != 0x2800u && t != 0x2801u) { + att_error(p[0], s, ATT_ERR_GROUP); + return; + } + batt.buf[0] = (uint8_t)(p[0] + 1u); + for (h = s; h <= e && h <= H_LAST; h++) { + const uint8_t *v; + uint32_t vl, el; + if (!att_type_is(h, p + 5, ul)) + continue; + if (!(ATT_DB[h].flags & A_R)) { + if (k == 2u) + att_error(p[0], h, ATT_ERR_READ); + else + break; + return; + } + vl = ble_min(att_len(h, &v), (uint32_t)batt.mtu - 2u - (grp ? 4u : 2u)); + vl = ble_min(vl, 251u); + el = (grp ? 4u : 2u) + vl; + if (k == 2u) + batt.buf[1] = (uint8_t)el; + else if (batt.buf[1] != el || k + el > batt.mtu) + break; + ble_wr16(batt.buf + k, h); + if (grp) + ble_wr16(batt.buf + k + 2u, att_group_end(h)); + ble_cpy(batt.buf + k + el - vl, v, vl); + k = (uint16_t)(k + el); + } + if (k == 2u) + att_error(p[0], s, ATT_ERR_NOT_FOUND); + else + att_send(k); +} + +static void att_read(const uint8_t *p, uint16_t n) +{ + uint16_t h = ble_rd16(p + 1), off = p[0] == 0x0Cu ? ble_rd16(p + 3) : 0u; + const uint8_t *v; + uint32_t vl; + if (n < (p[0] == 0x0Cu ? 5u : 3u)) { + att_error(p[0], 0, ATT_ERR_PDU); + return; + } + if (!h || h > H_LAST) { + att_error(p[0], h, ATT_ERR_HANDLE); + return; + } + if (!(ATT_DB[h].flags & A_R)) { + att_error(p[0], h, ATT_ERR_READ); + return; + } + if (att_need_enc(h)) { + att_error(p[0], h, ATT_ERR_AUTHEN); + return; + } + vl = att_len(h, &v); + if (off > vl) { + att_error(p[0], h, ATT_ERR_OFFSET); + return; + } + vl = ble_min(vl - off, (uint32_t)batt.mtu - 1u); + batt.buf[0] = (uint8_t)(p[0] + 1u); + if (vl) /* (an empty value, the MIDI I/O's, may have no pointer: no NULL + 0) */ + ble_cpy(batt.buf + 1, v + off, vl); + att_send((uint16_t)(1u + vl)); +} + +static void att_midi_in(void *ctx, uint32_t pkt, uint16_t ts) +{ + BLE_DIAG_MIDI_KIND(ble_dg, pkt); + ble_app_midi_in(pkt, ts, *(const uint16_t *)ctx); +} + +/* one BLE-MIDI packet in: a central's write to our MIDI I/O, or (as central) the peripheral's notification */ +BLE_API void ble_att_midi_packet(const uint8_t *v, uint16_t n) +{ + uint16_t last = ble_midi_last_ts(v, n); +#if BLE_DIAG + uint32_t i, r = ble_dg.mi_raw_n++ & 3u; + for (i = 0; i < 12u; i++) + ble_dg.mi_raw[r][i] = i < n ? v[i] : 0u; + ble_dg.mi_raw_len[r] = (uint8_t)(n > 255u ? 255u : n); + if (ble_midi_dec(&batt.dec, v, n, att_midi_in, &last)) + ble_dg.mi_pkts++; + else + ble_dg.mi_bad_hdr++; +#else + (void)ble_midi_dec(&batt.dec, v, n, att_midi_in, &last); +#endif +} + +/* returns an ATT error code, 0 when written */ +static uint8_t att_write(uint16_t h, const uint8_t *v, uint16_t n) +{ + if (!h || h > H_LAST) + return ATT_ERR_HANDLE; + if (!(ATT_DB[h].flags & A_W)) + return ATT_ERR_WRITE; + if (att_need_enc(h)) + return ATT_ERR_AUTHEN; + if (h == H_MIDI_IO) { + ble_att_midi_packet(v, n); + return 0; + } + if (n != 2u) + return ATT_ERR_VAL_LEN; + if (h == H_SC_CCC) { + batt.ccc_sc = v[0] & 2u; /* indications only */ + batt.sc_due = BLE_SC_ON_SUBSCRIBE && batt.ccc_sc; + } else { + uint8_t was = batt.ccc_midi; + batt.ccc_midi = v[0] & 1u; /* notifications only */ + if (batt.ccc_midi != was) { + if (batt.ccc_midi) { + ble_midi_enc_reset(&batt.enc); + ble_sig_want_fast(); /* stock asks for 7.5..11.25 ms here too */ + } + ble_app_state(); + } + } + return 0; +} + +BLE_API void ble_att_rx(const uint8_t *p, uint16_t n) +{ + uint8_t op, err; + if (!n) + return; + op = p[0]; + BLE_DG(ble_diag_last(ble_dg.att_rx, &ble_dg.att_rx_n, op)); +#if BLE_CENTRAL + if (ble_ll_central() && ble_gattc_rx(p, n)) + return; /* (a response to our client, a notification: ble_gattc.c) */ +#endif + switch (op) { + case 0x02: /* Exchange MTU */ + if (n != 3u) + break; + batt.mtu = (uint16_t)ble_min(ble_rd16(p + 1) < 23u ? 23u : ble_rd16(p + 1), BLE_ATT_MTU_MAX); + batt.buf[0] = 0x03; + ble_wr16(batt.buf + 1, BLE_ATT_MTU_MAX); + att_send(3); + return; + case 0x04: + if (n != 5u) + break; + att_find_info(p); + return; + case 0x06: + if (n < 7u) + break; + att_find_by_type(p, n); + return; + case 0x08: + case 0x10: + if (n < 7u) + break; + att_read_by(p, n); + return; + case 0x0A: + case 0x0C: + att_read(p, n); + return; + case 0x12: /* Write Request */ + case 0x52: /* Write Command */ + if (n < 3u) + break; + if (ble_rd16(p + 1) != H_MIDI_IO) { + BLE_DG(ble_dg.mi_w_other++); + BLE_DG(ble_dg.mi_w_other_h = ble_rd16(p + 1)); + } else if (op == 0x52) + BLE_DG(ble_dg.mi_wcmd++); + else + BLE_DG(ble_dg.mi_wreq++); + err = att_write(ble_rd16(p + 1), p + 3, (uint16_t)(n - 3u)); + if (op == 0x52) + return; + if (err) + att_error(op, ble_rd16(p + 1), err); + else { + batt.buf[0] = 0x13; + att_send(1); + } + return; + case 0x1E: /* Handle Value Confirmation */ + batt.ind_wait = 0; + return; + default: + if (!(op & 0x40u) && (op & 1u) == 0 && op != 0x1Eu) + att_error(op, 0, ATT_ERR_NOT_SUPP); /* requests (even opcodes) we do not serve */ + return; + } + att_error(op, 0, ATT_ERR_PDU); +} + +/* the queued MIDI events as notifications, at most BLE_MIDI_PER_EVENT a connection event */ +static void att_midi_out(void) +{ + uint32_t pkt, t, k; + uint16_t h = H_MIDI_IO; + uint8_t op = 0x1B, on = batt.ccc_midi & 1u; /* Handle Value Notification to the central that listens */ +#if BLE_CENTRAL + if (ble_ll_central()) { /* as central: Write Without Response to the peripheral's MIDI I/O */ + h = ble_gattc_midi(); + op = 0x52; + on = h != 0; + } +#endif + if (!on) { + while (ble_app_midi_peek(&pkt, &t)) /* nobody listening: nothing goes stale */ + ble_app_midi_pop(); + return; + } + for (k = 0; k < BLE_MIDI_PER_EVENT; k++) { + uint16_t len; + if (!ble_app_midi_peek(&pkt, &t) || ble_ll_tx_room() < batt.mtu + BLE_ATT_RESERVE) + return; + ble_midi_enc_begin(&batt.enc, batt.buf + 3, (uint16_t)(batt.mtu - 3u)); + while (ble_app_midi_peek(&pkt, &t)) { + int r = ble_midi_enc_add(&batt.enc, pkt, t); + if (!r) + break; + ble_app_midi_pop(); /* (added, or not a message: dropped) */ + } + len = ble_midi_enc_len(&batt.enc); + if (!len) + return; + batt.buf[0] = op; /* Handle Value Notification / Write Command */ + ble_wr16(batt.buf + 1, h); + att_send((uint16_t)(3u + len)); +#if BLE_CENTRAL + BLE_DG(ble_dgc.gc_wcmd_tx += op == 0x52); +#endif + } +} + +BLE_API void ble_att_event(void) +{ + if (batt.sc_due && !batt.ind_wait && ble_ll_tx_room() >= 7u + BLE_ATT_RESERVE) { + batt.buf[0] = 0x1D; /* Handle Value Indication: Service Changed, 0x0001..0xFFFF */ + ble_wr16(batt.buf + 1, H_SC); + ble_cpy(batt.buf + 3, V_SC, 4); + att_send(7); + batt.sc_due = 0; + batt.ind_wait = 1; + } + att_midi_out(); +} diff --git a/platform/ble/ble_central.c b/platform/ble/ble_central.c new file mode 100644 index 0000000..479a25a --- /dev/null +++ b/platform/ble/ble_central.c @@ -0,0 +1,340 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The host's side of the central role (BLE_CENTRAL; docs/BLE-STACK.md §9.2, docs/BLE-DEVICES-DESIGN.md §4): one connection out to a + * BLE-MIDI peripheral, from the initiator to "ready" (MIDI both ways): + * ble_central_connect initiate (ble_ll_connect) to the peer's AdvA; connected as master -> the GATT client + * (ble_gattc.c) starts, and with the peer's bond the link is encrypted at once (Apple's + * peripherals want it: QA1831), so the BLE-MIDI characteristic is found and subscribed; + * security the peripheral's SMP Security Request, an Insufficient Authentication / Encryption answer, + * or a bond the peripheral lost (LL_REJECT with PIN or Key Missing) -> encrypt with the bond, + * else pair as initiator (ble_smp_init.c); the GATT request that asked goes again once the + * link is encrypted (or the pairing done and our keys sent). Refused again after a Just Works + * pairing (an iPhone app's MIDI characteristic): paired again with MITM on the same link + * (the passkey; the LL pauses the encryption and restarts it with the new key); a peer that + * refuses that pairing before any passkey is shown -> BLE_CF_NEED_MITM (the firmware makes a + * new link with BLE_PEER_MITM); + * its requests an L2CAP Connection Parameter Update Request is answered and carried out as an + * LL_CONNECTION_UPDATE_IND (ble_ll_conn_update); + * the end a failure (no BLE-MIDI service, pairing failed, authentication refused, a GATT error or + * timeout) leaves the link; ble_central_fail / _code say why until the next attempt. + * RPA resolution (ah, Core Vol 3 Part H 2.2.2) for finding LAST behind a private address: ble_rpa_resolve. + * The levels (ble_cfg.h): BLE_CENTRAL 1 all of the above; 3 (no BLE_CEN_PAIR) no security at all: whatever asks for it + * (the Security Request, Insufficient Authentication / Encryption) leaves the link with BLE_CF_NEED_PAIR + * (ble_central_no_pairing). */ +#include "ble.h" +#include "ble_host.h" +#include "ble_ll.h" +#include "ble_aes.h" +#include "ble_util.h" +#include "ble_diag.h" + +static struct { + uint8_t st, fail, code; /* BLE_CS_*; BLE_CF_* and its code (the last attempt) */ +#if BLE_CEN_PAIR + uint8_t enc_tried, pairing, encrypted; /* the bond's LTK tried; a pairing of ours runs; the link encrypted */ + uint8_t mitm, auth; /* pair with a passkey (the peer needs it); the link's key is + * authenticated */ +#endif + uint8_t leave; /* bcen_fail: leave once the TX queue is empty (or 1 s) */ +#if BLE_CEN_PAIR + uint8_t repair; /* 1: pairing again with MITM on this encrypted link, 2: done */ + uint8_t prompted; /* a pairing of ours started on the link (a prompt on a phone) */ + uint8_t gatt_after_keys; /* the GATT request goes again once our keys have gone */ + uint8_t late_due; /* a Just Works pairing ended on the link: iOS may still send its + * Pairing Failed for it (blell-dev3 / dev4: 3 events after our keys) */ +#endif + uint32_t leave_t; + struct ble_peer peer; +} bcen; + +BLE_API uint8_t ble_central_state(void) { return bcen.st; } +BLE_API uint8_t ble_central_fail(void) { return bcen.fail; } +BLE_API uint8_t ble_central_code(void) { return bcen.code; } + +BLE_API int ble_central_connect(const struct ble_peer *p) +{ + if (!ble_ll_connect(p->addr, p->addr_rand)) + return 0; +#if BLE_CEN_PAIR + bcen.prompted = 0; +#endif + bcen.peer = *p; + bcen.st = BLE_CS_CONNECTING; + bcen.fail = BLE_CF_NONE; + bcen.code = 0; + return 1; +} + +BLE_API void ble_central_cancel(void) +{ + if (ble_ll_initiating()) { + ble_ll_connect_cancel(); + bcen.st = BLE_CS_IDLE; + } else if (ble_ll_central()) + ble_ll_disconnect(BLE_ERR_REMOTE_USER); /* (ble_central_disconnected when it is gone) */ +} + +/* leave the link for this reason (it is kept until the next attempt), once what is queued has gone (a Pairing Failed + * of ours: ble_ll_disconnect drops what was not sent), at the next event */ +static void bcen_fail(uint8_t why, uint8_t code) +{ + if (bcen.fail == BLE_CF_NONE) { + bcen.fail = why; + bcen.code = code; + } + if (!bcen.leave) { + bcen.leave = 1; + bcen.leave_t = ble_hw_time_us(); + } +} + +BLE_API void ble_central_connected(void) +{ + if (!ble_ll_central()) + return; + bcen.st = BLE_CS_SETUP; +#if BLE_CEN_PAIR + bcen.enc_tried = bcen.pairing = bcen.encrypted = bcen.leave = bcen.auth = 0; + bcen.repair = bcen.prompted = bcen.gatt_after_keys = bcen.late_due = 0; + bcen.mitm = (uint8_t)(bcen.peer.sec & BLE_PEER_MITM ? 1u : 0u); +#else + bcen.leave = 0; +#endif + ble_gattc_start(); +#if BLE_CEN_PAIR + if (bcen.peer.bonded) { /* a bonded peer: encrypted before it has to ask */ + bcen.enc_tried = 1; + ble_ll_start_enc(bcen.peer.ltk, bcen.peer.rand, bcen.peer.ediv); + } +#endif +} + +BLE_API void ble_central_disconnected(uint8_t reason) +{ + if (bcen.st == BLE_CS_SETUP || bcen.st == BLE_CS_READY) { + if (bcen.fail == BLE_CF_NONE) { /* gone without a reason of ours: lost (it left, or out of range); */ + bcen.fail = BLE_CF_LOST; /* it left with MIC Failure / Key Missing while our encryption with */ + bcen.code = reason; /* the bond started: the bond is no good to it (KEY) */ +#if BLE_CEN_PAIR + if (bcen.peer.bonded && bcen.enc_tried && !bcen.encrypted && !bcen.pairing && + (reason == BLE_ERR_MIC_FAILURE || reason == BLE_ERR_PIN_KEY_MISSING)) + bcen.fail = BLE_CF_KEY; +#endif + } + bcen.st = BLE_CS_IDLE; + } + ble_gattc_reset(); +} + +#if BLE_CEN_PAIR +static void bcen_pair(void) +{ + bcen.pairing = 1; + bcen.prompted = 1; + ble_smp_pair(bcen.mitm); +} +#endif + +/* security is needed (the peripheral asked, or refused a GATT request with this ATT error; 0: a Security Request): + * the bond's key first, else a pairing (Just Works unless the peer is known to need a passkey). Encrypted already and + * refused with Insufficient Authentication by a key without MITM protection: the peer needs a passkey. It is asked for + * on this link (Core Vol 3 Part H 2.4: a pairing on an encrypted link; the STK replaces the key through the LL's + * encryption pause, Vol 6 Part B 5.1.3.2), once: no disconnection, no new connection to establish, the phone's user + * sees the passkey prompt as with a new link. 1: something started (wait for it), 0: nothing left to try */ +#if BLE_CEN_PAIR +static int bcen_secure(uint8_t code) +{ + if (bcen.pairing) + return 1; + if (bcen.encrypted) { + if (code == 0x05u && !bcen.auth && !bcen.mitm && !bcen.repair) { + BLE_DG(ble_dgc.cen_need_mitm++); + BLE_DG(ble_dgc.si_repair++); + bcen.mitm = 1; + bcen.repair = 1; + bcen_pair(); + return 1; + } + return 0; + } + if (bcen.peer.bonded) { + if (!bcen.enc_tried) { + bcen.enc_tried = 1; + ble_ll_start_enc(bcen.peer.ltk, bcen.peer.rand, bcen.peer.ediv); + } + return 1; /* (on its way; refused: ble_host_enc_failed pairs) */ + } + bcen_pair(); + return 1; +} + +BLE_API int ble_central_pairing(void) { return bcen.pairing; } +BLE_API int ble_central_prompted(void) { return bcen.prompted; } +BLE_API int ble_central_mitm(void) { return bcen.mitm; } +#else +/* BLE_CENTRAL 3: the peripheral wants security (0: its Security Request, answered Pairing Not Supported by ble_smp.c; + * else the ATT error it refused a GATT request with): this level has none, the link is left (NEEDS PAIRING, held by + * the firmware until the user acts) */ +BLE_API void ble_central_no_pairing(uint8_t code) +{ + BLE_DG(ble_dgc.si_sec_req_rx += code == 0u); + bcen_fail(BLE_CF_NEED_PAIR, code); +} + +static int bcen_secure(uint8_t code) +{ + ble_central_no_pairing(code); + return 0; +} +#endif + +/* (ble_gattc.c) */ +static void ble_central_gattc_ready(void) +{ + bcen.st = BLE_CS_READY; + ble_app_state(); +} + +static void ble_central_gattc_fail(uint8_t why, uint8_t code) +{ + if (why == BLE_CF_NO_MIDI) + BLE_DG(ble_dgc.gc_no_midi++); + bcen_fail(why, code); +} + +static int ble_central_gattc_auth(uint8_t code) +{ + return bcen_secure(code); +} + +#if BLE_CEN_PAIR +/* (ble_smp_init.c) a Security Request: its AuthReq's MITM bit asks for a passkey */ +static void ble_central_sec_req(uint8_t auth_req) +{ + if (auth_req & 0x04u) + bcen.mitm = 1; + if (!bcen_secure(0)) + ble_gattc_retry(); +} + +static void ble_central_encrypted(void) /* encrypted with the bond's LTK */ +{ + bcen.encrypted = 1; + bcen.auth = (uint8_t)(bcen.peer.sec & BLE_PEER_AUTH ? 1u : 0u); + if (!bcen.pairing) + ble_gattc_retry(); +} + +/* the pairing ended: ok, or failed with reason; auth: the keys are authenticated (ok), a passkey was shown (failed) */ +static void ble_central_paired(int ok, uint8_t reason, uint8_t auth) +{ + bcen.pairing = 0; + if (!ok) { /* (Authentication Requirements, either way: AUTH) */ + if (bcen.repair == 1 && !auth && reason != 0x03u) { + BLE_DG(ble_dgc.si_repair_fallback++); /* (refused on this link before any passkey: a new link) */ + bcen_fail(BLE_CF_NEED_MITM, reason); + return; + } + bcen_fail(reason == 0x03u ? BLE_CF_AUTH : BLE_CF_PAIRING, reason); + return; + } + if (bcen.repair == 1) + bcen.repair = 2; + bcen.late_due = (uint8_t)!auth; + bcen.encrypted = 1; /* (with the STK, the keys exchanged) */ + bcen.auth = auth; + bcen.gatt_after_keys = 1; /* (in a later event than our keys: ble_central_event) */ +} + +/* (ble_smp_init.c) a Pairing Failed from the peripheral, at: 0 no pairing of ours runs, 1 ours waits for its Pairing + * Response, 2 ours is further on -> 1: late (counted, ignored): with none of ours running; or iOS's Unspecified Reason + * for the Just Works pairing that ended on this link (it came 3 events after our keys, blell-dev3 / dev4) arriving + * after our Pairing Request with MITM went (its Pairing Response is still awaited). 0: it ends the pairing that runs */ +static int ble_central_late_fail(uint8_t reason, int at) +{ + int late = bcen.late_due && reason == 0x08u; + if (at == 2) + return 0; + if (late) + bcen.late_due = 0; + return at == 0 || late; +} + +/* as master, our LL_ENC_REQ was refused: the peripheral lost the bond (Key Missing) -> pair afresh */ +BLE_API void ble_host_enc_failed(uint8_t err) +{ + if (!ble_ll_central()) + return; + if (bcen.pairing) { /* (the STK refused: the pairing is over) */ + bcen.pairing = 0; + bcen_fail(BLE_CF_PAIRING, err); + return; + } + bcen.peer.bonded = 0; + bcen_pair(); +} +#endif + +BLE_API void ble_central_event(void) +{ + uint32_t now; + if (!ble_ll_central()) + return; + now = ble_hw_time_us(); + if (bcen.leave) { + if (ble_ll_tx_room() + 4u >= BLE_LL_TX_RING || now - bcen.leave_t > 1000000u) { + bcen.leave = 0; + ble_ll_disconnect(BLE_ERR_REMOTE_USER); + } + return; + } + ble_gattc_event(now); +#if BLE_CEN_PAIR + if (bcen.gatt_after_keys && ble_ll_tx_room() + 4u >= BLE_LL_TX_RING) { + bcen.gatt_after_keys = 0; /* (our keys handed to the engine: the request again; after the + * GATT timeout check, whose `now` is older than this request) */ + ble_gattc_retry(); + } + if (bcen.repair == 1 && smp_init_rsp_late(now)) { /* no answer to the pairing on this link: a new link */ + bcen.pairing = 0; + BLE_DG(ble_dgc.si_repair_fallback++); + bcen_fail(BLE_CF_NEED_MITM, 0xFF); + } else if (smp_init_timed_out(now)) { + bcen.pairing = 0; + bcen_fail(BLE_CF_PAIRING, 0xFF); + } +#endif +} + +/* an L2CAP Connection Parameter Update Request (Core Vol 3 Part A 4.20): 0 accepted (carried out with an + * LL_CONNECTION_UPDATE_IND at an instant), 1 rejected */ +BLE_API uint8_t ble_central_sig(const uint8_t *d, uint16_t n) +{ + uint16_t imin, imax, lat, to; + BLE_DG(ble_dgc.m_l2_upd_rx++); + if (n < 8u) + return 1; + imin = ble_rd16(d), imax = ble_rd16(d + 2), lat = ble_rd16(d + 4), to = ble_rd16(d + 6); + if (imin < 6u || imin > imax || imax > 3200u || lat > 499u || to < 10u || to > 3200u || + (uint32_t)to * 4u <= (1u + lat) * imax) + return 1; + ble_ll_conn_update(imin, imax, to); /* (later when a procedure of ours runs: kept) */ + return 0; +} + +#if BLE_CEN_PAIR +/* ah(k, r) = e(k, 0^104 || r) mod 2^24 against the hash in an RPA's low 24 bits (top two bits 01) */ +BLE_API int ble_rpa_resolve(const uint8_t irk[16], const uint8_t addr[6]) +{ + uint8_t k[16], x[16], i; + if ((addr[5] >> 6) != 1u) + return 0; + for (i = 0; i < 16u; i++) + k[i] = irk[15 - i]; /* (e() takes its key most significant octet first) */ + ble_zero(x, 13); + x[13] = addr[5]; /* prand, most significant octet first */ + x[14] = addr[4]; + x[15] = addr[3]; + ble_aes128(k, x, x); + return x[15] == addr[0] && x[14] == addr[1] && x[13] == addr[2]; +} +#endif diff --git a/platform/ble/ble_cfg.h b/platform/ble/ble_cfg.h new file mode 100644 index 0000000..1cb4788 --- /dev/null +++ b/platform/ble/ble_cfg.h @@ -0,0 +1,239 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* BLE stack configuration (route C, docs/BLE-STACK.md). Every value can be set with -D; the defaults are the + * FM-1 build's. Sizes are in bytes; times in the Bluetooth units named. + * + * Written from the Bluetooth Core Specification (v5.x, LE 1M only) and the MIDI Association's + * "Specification for MIDI over Bluetooth Low Energy" 1.0. No vendor code. */ +#ifndef BLE_CFG_H +#define BLE_CFG_H + +#ifndef BLE_API +#define BLE_API /* the stack's functions: extern; static in the firmware's unity build */ +#endif + +/* ---- GAP */ +#ifndef BLE_DEVICE_NAME +#define BLE_DEVICE_NAME "Optimist" /* the advertised name and GAP Device Name: "Optimist XXXX", XXXX the last four hex + * digits of the device address (BLE_NAME_HEX; docs/BLE-DEVICES-DESIGN.md §1; + * stock V15's was "FM-1_BLE", Optimist's before 2026-10-16 "FM-1 XXXX"; at most 24 characters; not "Optimist (Felucca)" as the + * USB name: a scanned device's name is kept to BLE_NAME_MAX = 16 characters, which would cut the XXXX; the + * editors match /felucca|optimist/i) */ +#endif +#ifndef BLE_NAME_HEX +#define BLE_NAME_HEX 1 /* 1: " XXXX" after BLE_DEVICE_NAME; 0: the name as it is */ +#endif +#ifndef BLE_APPEARANCE +#define BLE_APPEARANCE 0x0000u /* GAP Appearance: 0 = unknown (no category is claimed) */ +#endif +#ifndef BLE_ADV_INTERVAL +#define BLE_ADV_INTERVAL 160u /* x 0.625 ms = 100 ms (stock: 0xA0) */ +#endif +#ifndef BLE_ADV_CHANNELS +#define BLE_ADV_CHANNELS 7u /* bit 0: channel 37, bit 1: 38, bit 2: 39 */ +#endif + +/* ---- connection parameters the peripheral asks for once the MIDI notifications are on (stock: {6, 9, 0, 100}, + * then {12, 12, 0, 100} once). Interval x 1.25 ms, timeout x 10 ms. Also the GAP Peripheral Preferred + * Connection Parameters characteristic. */ +#ifndef BLE_CONN_MIN +#define BLE_CONN_MIN 6u +#endif +#ifndef BLE_CONN_MAX +#define BLE_CONN_MAX 9u +#endif +#ifndef BLE_CONN_LATENCY +#define BLE_CONN_LATENCY 0u +#endif +#ifndef BLE_CONN_TIMEOUT +#define BLE_CONN_TIMEOUT 100u +#endif +#ifndef BLE_CONN_RETRY_MIN +#define BLE_CONN_RETRY_MIN 12u /* the second request after a reject (0 = no second request) */ +#endif +#ifndef BLE_CONN_RETRY_MAX +#define BLE_CONN_RETRY_MAX 12u +#endif +/* while Bluetooth audio streams (ble_host.c ble_sig_audio): 30..45 ms, 2 s (Apple's rules: min >= 15 ms, max >= min + + * 15 ms, timeout 2..6 s). At 7.5..11.25 ms a connection event, which wins the radio over the audio's 3.75 ms packets + * (bt/bt_inq.c BTI_ACL_PRIO), leaves room for about one audio packet between two: the stream's 115 a second with no + * margin, crackles on the XM4 with the screen mirror on (2026-10-24) */ +#ifndef BLE_CONN_AUDIO_MIN +#define BLE_CONN_AUDIO_MIN 24u +#endif +#ifndef BLE_CONN_AUDIO_MAX +#define BLE_CONN_AUDIO_MAX 36u +#endif +#ifndef BLE_CONN_AUDIO_TIMEOUT +#define BLE_CONN_AUDIO_TIMEOUT 200u +#endif +#ifndef BLE_SIG_AUDIO_RETRY_US +#define BLE_SIG_AUDIO_RETRY_US 5000000u /* the link still fast while the audio streams: asked again this long after */ +#endif + +/* ---- link layer */ +#ifndef BLE_LL_MAX_OCTETS +#define BLE_LL_MAX_OCTETS 251u /* largest LL payload sent or received (27..251; 27 = no data length ext.) */ +#endif +#ifndef BLE_LL_TX_RING +#define BLE_LL_TX_RING 1024u /* queued L2CAP frames (bytes, a power of two) */ +#endif +#ifndef BLE_LL_CTRL_Q +#define BLE_LL_CTRL_Q 4u /* queued LL control PDUs */ +#endif +#ifndef BLE_LL_VERSION +#define BLE_LL_VERSION 9u /* VersNr: 9 = Core 5.0 */ +#endif +#ifndef BLE_LL_COMPANY +#define BLE_LL_COMPANY 0xFFFFu /* CompId: 0xFFFF, the value for no assigned company identifier */ +#endif +#ifndef BLE_LL_SUBVERSION +#define BLE_LL_SUBVERSION 0x0001u +#endif +#ifndef BLE_LL_PERIPH_FEAT +#define BLE_LL_PERIPH_FEAT 1 /* start the feature exchange ourselves when the central has not */ +#endif +#ifndef BLE_CENTRAL +#if defined(FELUCCA_BLE_CENTRAL) +#define BLE_CENTRAL FELUCCA_BLE_CENTRAL /* builder item BLE_CENTRAL */ +#else +#define BLE_CENTRAL 0 /* 1 or 3: the central role (docs/BLE-DEVICES-DESIGN.md): the scanner for the + * DEVICES list, connecting out to a BLE-MIDI peripheral (initiator, master + * link, GATT client, SMP initiator) and reconnecting to LAST. One link, + * time-sliced with advertising. Level 1 brings bonding (BLE_LL_ENC, SMP) + * with it (its levels: below) */ +#endif +#endif +/* BLE_CENTRAL's level (the builder's choice, docs/BLE-DEVICES-DESIGN.md §4.5; `#if BLE_CENTRAL`: any level): + * 1 FULL pairing as initiator with Just Works or a passkey we display (an iPhone app that needs MITM), the + * pairing again with the passkey on the same link, LAST found behind a resolvable private address; + * 3 MINIMAL no pairing and no encryption from the central role: no SMP initiator, no LL encryption as master, no + * bonds; a peer that asks for security is left ("FAILED: NEEDS PAIRING"). Controllers and FM-1 to + * FM-1 need none. BLE_BOND (the peripheral's pairing as responder) stays as it is at every level + * (2 was a Just Works only level, removed: it saved 2.2 KB over FULL; the builder refuses it) */ +#if BLE_CENTRAL < 0 || BLE_CENTRAL > 3 || BLE_CENTRAL == 2 +#error "BLE_CENTRAL: 0 off, 1 full, 3 minimal" +#endif +#ifndef BLE_CEN_PAIR +#define BLE_CEN_PAIR (BLE_CENTRAL == 1) /* the central pairs (SMP initiator, LL encryption as master, passkey, RPA search) */ +#endif +#if (defined(FELUCCA_BLE_BOND) && FELUCCA_BLE_BOND) || BLE_CEN_PAIR +/* builder item BLE_BOND: bonding (SMP Just Works + LL encryption); BLE_CENTRAL level 1 needs it too: Apple's + * BLE-MIDI peripherals (QA1831) and many controllers ask the central to pair, so connecting out pairs as initiator */ +#ifndef BLE_LL_ENC +#define BLE_LL_ENC 1 +#endif +#ifndef BLE_SMP_LEGACY +#define BLE_SMP_LEGACY 1 +#endif +#endif +#ifndef BLE_LL_ENC +#define BLE_LL_ENC 0 /* LL encryption (needs keys: a pairing method in ble_smp.c); 0 = refused */ +#endif + +/* ---- security (ble_smp.c) */ +#ifndef BLE_SMP_LEGACY +#define BLE_SMP_LEGACY 0 /* LE legacy pairing, Just Works, with bonding (needs BLE_LL_ENC); 0: a Pairing + * Request gets Pairing Failed, Pairing Not Supported */ +#endif +#ifndef BLE_SMP_SEC_REQ +#define BLE_SMP_SEC_REQ 0 /* send an SMP Security Request (bonding) when a connection starts, as stock V15 + * is reported to; Apple's Accessory Design Guidelines (58.10) advise against */ +#endif +#ifndef BLE_MIDI_NEED_ENC +#define BLE_MIDI_NEED_ENC 0 /* the MIDI I/O value and its CCCD need an encrypted link: Insufficient + * Authentication (0x05) until then, the way Apple's guidelines (58.10) ask a + * peripheral to start pairing */ +#endif +#if BLE_SMP_LEGACY && !BLE_LL_ENC +#error "BLE_SMP_LEGACY needs BLE_LL_ENC=1" +#endif +#if (BLE_SMP_SEC_REQ || BLE_MIDI_NEED_ENC) && !BLE_SMP_LEGACY +#error "BLE_SMP_SEC_REQ / BLE_MIDI_NEED_ENC need BLE_SMP_LEGACY=1" +#endif +#if BLE_CEN_PAIR && !BLE_SMP_LEGACY +#error "BLE_CENTRAL 1 (the central pairs) needs BLE_SMP_LEGACY=1" +#endif + +/* ---- central role, part 1: scanning for the DEVICES list (docs/BLE-STACK.md §9.1, HW §21.2) */ +#ifndef BLE_SCAN_INTERVAL +#define BLE_SCAN_INTERVAL 64u /* x 0.625 ms = 40 ms: the channel moves on 37 -> 38 -> 39 every interval */ +#endif +#ifndef BLE_SCAN_WINDOW +#define BLE_SCAN_WINDOW 60u /* x 0.625 ms: window + 4 <= interval (the vendor's rule, HW §21.2 step 3) */ +#endif +#ifndef BLE_SCAN_ACTIVE +#define BLE_SCAN_ACTIVE 1 /* 1: SCAN_REQ (sent by the engine, with the Core's backoff) to get the names + * most controllers put in their scan response; 0: passive */ +#endif +#ifndef BLE_SCAN_RING +#define BLE_SCAN_RING 16u /* raw reports between the RX interrupt and the main loop (a power of two): a + * burst is ADV_IND + SCAN_RSP on 3 channels; 8 lost 4 reports in + * tests/ble_emu_test.py once the boot dinghy shifted the run's timeline */ +#endif +#if BLE_CENTRAL && (BLE_SCAN_RING & (BLE_SCAN_RING - 1u)) +#error "BLE_SCAN_RING: a power of two" +#endif + +/* ---- central role, part 2: connecting out (docs/BLE-STACK.md §9.1, HW §21.3 / §21.4). Our CONNECT_IND: + * a random access address (Core Vol 6 Part B 2.1.2) and a random CRCInit (the vendor's fixed 0x1983AE is not used), + * WinSize 2 and WinOffset random in [Interval / 2, Interval - 1] as the vendor (§21.3), Hop random 5..16, all 37 + * channels, and these: */ +#ifndef BLE_CENTRAL_INTERVAL +#define BLE_CENTRAL_INTERVAL 9u /* x 1.25 ms = 11.25 ms: the top of the 7.5..11.25 ms our peripheral asks for + * (BLE_CONN_MIN / MAX, as stock V15 asks); one PDU pair per event each way is + * ~89 BLE-MIDI packets a second, each holding many messages; 7.5 ms would add + * a third more event and RX interrupts beside the audio while the cost of the + * software AES-CCM in them is unmeasured on the FM-1 (design P1 risks) */ +#endif +#ifndef BLE_CENTRAL_TIMEOUT +#define BLE_CENTRAL_TIMEOUT 200u /* x 10 ms = 2 s supervision timeout */ +#endif +#ifndef BLE_CENTRAL_WINSIZE +#define BLE_CENTRAL_WINSIZE 2u /* x 1.25 ms: the transmit window (the vendor's, §21.3) */ +#endif +#ifndef BLE_CENTRAL_SCA +#define BLE_CENTRAL_SCA 0u /* 251-500 ppm, as the vendor's CONNECT_IND (§21.6): the FM-1's sleep clock + * accuracy is not measured, and claiming the worst only widens the peer's + * window by a few us at 11.25 ms */ +#endif +#ifndef BLE_INIT_INTERVAL +#define BLE_INIT_INTERVAL 64u /* initiating windows: as scanning (x 0.625 ms), the channel moved each */ +#endif +#ifndef BLE_INIT_WINDOW +#define BLE_INIT_WINDOW 60u +#endif +#if BLE_CENTRAL_INTERVAL < 6u || BLE_CENTRAL_INTERVAL > 3200u || BLE_CENTRAL_TIMEOUT * 4u <= BLE_CENTRAL_INTERVAL +#error "BLE_CENTRAL_INTERVAL: 6..3200, and BLE_CENTRAL_TIMEOUT x 10 ms more than two intervals" +#endif +#ifndef BLE_GATTC_TIMEOUT_US +#define BLE_GATTC_TIMEOUT_US 30000000u /* ATT (Core Vol 3 Part F 3.3.3) and SMP (Part H 3.4) transaction timeout */ +#endif + +/* ---- host */ +#ifndef BLE_ATT_MTU_MAX +#define BLE_ATT_MTU_MAX 247u /* our ATT receive MTU: 247 fills one 251-byte LL PDU (23..517) */ +#endif +#ifndef BLE_SC_ON_SUBSCRIBE +#define BLE_SC_ON_SUBSCRIBE 0 /* 1: indicate Service Changed (0x0001..0xFFFF) whenever a client subscribes to + * it. Off: on the FM-1 (blell10-12, 2026-10-09) the Mac confirmed that + * indication and then never discovered the MIDI characteristic; the database + * never changes while we run, so the indication is never due (§5) */ +#endif +#ifndef BLE_MIDI_RUNNING_STATUS +#define BLE_MIDI_RUNNING_STATUS 1 /* the encoder drops a repeated status byte inside a packet */ +#endif +#ifndef BLE_MIDI_PER_EVENT +#define BLE_MIDI_PER_EVENT 2u /* notifications queued per connection event at most */ +#endif + +#if BLE_LL_MAX_OCTETS < 27u || BLE_LL_MAX_OCTETS > 251u +#error "BLE_LL_MAX_OCTETS: 27..251" +#endif +#if BLE_ATT_MTU_MAX < 23u || BLE_ATT_MTU_MAX > 517u +#error "BLE_ATT_MTU_MAX: 23..517" +#endif +#if (BLE_LL_TX_RING & (BLE_LL_TX_RING - 1u)) || BLE_LL_TX_RING < 2u * (BLE_ATT_MTU_MAX + 4u + 2u) +#error "BLE_LL_TX_RING: a power of two, room for two full ATT frames" +#endif + +#endif diff --git a/platform/ble/ble_diag.c b/platform/ble/ble_diag.c new file mode 100644 index 0000000..c65aee9 --- /dev/null +++ b/platform/ble/ble_diag.c @@ -0,0 +1,623 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The console's `blell` (docs/BLE-STACK.md §11): ble_diag.h's counters, the link layer's state and, on the FM-1, the + * engine's registers, one "key value" line each in the console's style. Included after ble_ll.c (it reads bll). */ +#include "ble_diag.h" + +#if BLE_DIAG /* (without it: nothing, the console has no blell either) */ + +typedef void (*ble_diag_put)(const char *s); + +static void bd_hex(ble_diag_put put, uint32_t v, uint32_t digits) +{ + char b[9]; + uint32_t i; + for (i = 0; i < digits && i < 8u; i++) + b[i] = "0123456789ABCDEF"[(v >> ((digits - 1u - i) * 4u)) & 15u]; + b[i] = 0; + put(b); +} + +static void bd_dec(ble_diag_put put, uint32_t v) +{ + char b[11]; + uint32_t n = 10; + b[10] = 0; + do + b[--n] = (char)('0' + v % 10u); + while ((v /= 10u) != 0 && n); + put(b + n); +} + +static void bd_kv(ble_diag_put put, const char *k, uint32_t v) +{ + put(k); + put(" "); + bd_dec(put, v); + put("\r\n"); +} + +static void bd_kx(ble_diag_put put, const char *k, uint32_t v, uint32_t digits) +{ + put(k); + put(" "); + bd_hex(put, v, digits); + put("\r\n"); +} + +/* the last n (at most BLE_DIAG_LAST) of a ring of opcodes, oldest first */ +static void bd_ops(ble_diag_put put, const char *k, const uint8_t *ring, uint32_t total) +{ + uint32_t i, n = total < BLE_DIAG_LAST ? total : BLE_DIAG_LAST; + bd_kv(put, k, total); + put(k); + put("_last"); + for (i = total - n; i != total; i++) { + put(" "); + bd_hex(put, ring[i & (BLE_DIAG_LAST - 1u)], 2); + } + put("\r\n"); +} + +static const char *const BD_EV[BDE_COUNT] = { + "-", "enable", "adv_start", "adv_stop", "adv_drop", "cind_rx", "cind_ok", "cind_rej", "conn_set", "first_evt", + "first_rx", "rx_bad", "rx_desync", "c3_zero", "ctl_rx", "ctl_tx", "instant", "close", "busy", "init", "master", "init_hit"}; +static const char *const BD_LL[5] = {"off", "adv", "conn", "scan", "init"}; +static const char *const BD_STOP[BDS_COUNT] = {"adv", "scan", "init", "conn", "open"}; +static const char *const BD_HW[5] = {"off", "adv", "conn", "scan", "init"}; + +static void bd_regs(ble_diag_put put, const struct ble_diag_regs *r) +{ + static const char *const COL[BLE_DIAG_COLS] = {"col0", "col1", "col2", "col3", "col4", "col5", "col6", "col14", + "col15"}; + uint32_t i; + put("hw_state "); + put(BD_HW[r->hw_state % 5u]); + put("\r\n"); + for (i = 0; i < BLE_DIAG_COLS; i++) + bd_kx(put, COL[i], r->col[i], 4); + bd_kv(put, "col2_state", r->col[2] >> 12 & 7u); /* HW §2.5: 2 advertising, 7 peripheral */ + bd_kx(put, "clock", r->clock, 6); + bd_kx(put, "ien", r->ien, 4); + bd_kx(put, "ipnd", r->ipnd, 4); + bd_kx(put, "g2en", r->g2en, 4); + bd_kx(put, "g2pnd", r->g2pnd, 4); + bd_kx(put, "bbstat", r->stat, 4); + bd_kx(put, "txtog", r->txtog, 4); + bd_kx(put, "rxtog", r->rxtog, 4); + bd_kv(put, "rx_next", r->rx_next); + bd_kv(put, "rx_sn", r->rx_sn); + bd_kv(put, "tx_n", r->tx_n); + bd_kv(put, "win_wide", r->win_wide); + bd_kx(put, "txbufcntl", (uint32_t)r->txbufcntl[0] << 8 | r->txbufcntl[1], 4); + bd_kx(put, "rxbufcntl", (uint32_t)r->rxbufcntl[0] << 8 | r->rxbufcntl[1], 4); + bd_kx(put, "rxstat", (uint32_t)r->rxstat[0] << 16 | r->rxstat[1], 8); + bd_kx(put, "rxahdr", (uint32_t)r->rxahdr[0] << 16 | r->rxahdr[1], 8); + bd_kx(put, "rxdhdr", (uint32_t)r->rxdhdr[0] << 16 | r->rxdhdr[1], 8); + bd_kx(put, "txdhdr", (uint32_t)r->txdhdr[0] << 16 | r->txdhdr[1], 8); + bd_kx(put, "intframe", r->intframe, 4); + bd_kx(put, "format", r->format, 4); + bd_kx(put, "optcntl", r->optcntl, 4); + bd_kv(put, "evtcount", r->evtcount); + bd_kv(put, "wincntl0", r->wincntl0); +} + +static void bd_cind(ble_diag_put put, const struct ble_diag *d) +{ + uint32_t chm = (uint32_t)d->cind_chm[0] | (uint32_t)d->cind_chm[1] << 8 | (uint32_t)d->cind_chm[2] << 16 | + (uint32_t)d->cind_chm[3] << 24; + bd_kv(put, "cind_rx", d->cind_rx); + bd_kv(put, "cind_ok", d->cind_ok); + bd_kv(put, "cind_rej", d->cind_rej); + bd_kv(put, "cind_rej_why", d->cind_rej_why); + bd_kx(put, "cind_hdr", d->cind_hdr, 2); + bd_kx(put, "cind_aa", d->cind_aa, 8); + bd_kx(put, "cind_crc", d->cind_crc, 6); + bd_kv(put, "cind_win_size", d->cind_win_size); + bd_kv(put, "cind_win_off", d->cind_win_off); + bd_kv(put, "cind_interval", d->cind_interval); + bd_kv(put, "cind_latency", d->cind_latency); + bd_kv(put, "cind_timeout", d->cind_timeout); + bd_kv(put, "sa_calls", d->sa_calls); + bd_kv(put, "sa_on", d->sa_on); + bd_kv(put, "sa_sent", d->sa_sent); + bd_kv(put, "sa_full", d->sa_full); + bd_kv(put, "sa_iv", d->sa_iv); + bd_kv(put, "sa_fast", d->sa_fast); + bd_kv(put, "sa_slow", d->sa_slow); + put("cind_chm "); + bd_hex(put, d->cind_chm[4], 2); + bd_hex(put, chm, 8); + put("\r\n"); + bd_kv(put, "cind_hop", d->cind_hop); + bd_kv(put, "cind_sca", d->cind_sca); + bd_kv(put, "cind_isr_us", d->cind_isr_us); + bd_kv(put, "first_evt", d->first_evt); + bd_kv(put, "first_rx_us", d->first_rx_us); + bd_kv(put, "first_rx_evt", d->first_rx_evt); +} + +static void bd_conn(ble_diag_put put, const struct ble_diag *d) +{ + bd_kv(put, "evt_irqs", d->evt_irqs); + bd_kv(put, "rx_irqs", d->rx_irqs); + bd_kv(put, "conn_events", d->conn_events); + bd_kv(put, "c3_zero", d->c3_zero); + bd_kv(put, "evt_same", d->evt_same); + bd_kv(put, "last_evt", d->last_evt); + bd_kv(put, "rx_good", d->rx_good); + bd_kv(put, "rx_crc_bad", d->rx_crc_bad); + bd_kx(put, "rx_bad_stat", d->rx_bad_stat, 4); + bd_kv(put, "rx_repeat", d->rx_repeat); + bd_kv(put, "rx_empty", d->rx_empty); + bd_kv(put, "rx_nothing", d->rx_nothing); + bd_kv(put, "rx_desync", d->rx_desync); + bd_kv(put, "tx_queued", d->tx_queued); + bd_kv(put, "tx_acked", d->tx_acked); + bd_kv(put, "tx_none", d->tx_none); + bd_kv(put, "clk_step_max", d->clk_step_max); + bd_ops(put, "ctl_rx", d->ctl_rx, d->ctl_rx_n); + bd_ops(put, "ctl_tx", d->ctl_tx, d->ctl_tx_n); + bd_ops(put, "att_rx", d->att_rx, d->att_rx_n); + bd_kv(put, "closes", d->closes); + bd_kx(put, "close_reason", d->close_reason, 2); + bd_kv(put, "close_by", d->close_by); + bd_kv(put, "close_evt", d->close_evt); + bd_kv(put, "close_since_rx_us", d->close_since_rx_us); + bd_kv(put, "close_since_start_us", d->close_since_start_us); + bd_kv(put, "sup_timeouts", d->sup_timeouts); + bd_kv(put, "estab_fails", d->estab_fails); + bd_kv(put, "peer_terms", d->peer_terms); +} + +#if defined(BLE_HW_WL82) && BLE_HW_WL82 +static const uint8_t BLE_DIAG_COL[BLE_DIAG_COLS] = {0, 1, 2, 3, 4, 5, 6, 14, 15}; /* the columns read (op 2) */ +/* the engine's side (the WL82 driver, ble_hw_wl82.c, in the same unity build): column reads (op 2), the interrupt + * registers, the control block words the link runs on. Main loop, the BLE interrupts held, only after + * ble_hw_wl82_start. */ +static void ble_hw_diag_regs(struct ble_diag_regs *r) +{ + uint32_t i, w[5]; + r->valid = 1; + r->hw_state = drv.state; + r->rx_next = drv.rx_next; + r->rx_sn = drv.rx_sn; + r->tx_n = (uint8_t)(drv.tx_rec[0] + drv.tx_rec[1]); /* PDUs of ours handed to the engine */ + r->win_wide = drv.win_wide; + for (i = 0; i < BLE_DIAG_COLS; i++) + r->col[i] = (uint16_t)fm1_ble_col_rd(HW_LINK, BLE_DIAG_COL[i]); + r->clock = fm1_ble_clock(HW_LINK); + fm1_ble_irq_regs(w); + r->ien = w[0]; + r->ipnd = w[1]; + r->g2en = w[2]; + r->g2pnd = w[3]; + r->stat = w[4]; + r->txtog = CB->txtog; + r->rxtog = CB->rxtog; + r->intframe = CB->intframe; + r->format = CB->format; + r->optcntl = CB->optcntl; + r->evtcount = CB->evtcount; + r->wincntl0 = CB->wincntl[0]; + for (i = 0; i < 2u; i++) { + r->rxstat[i] = CB->rxstat[i]; + r->rxahdr[i] = CB->rxahdr[i]; + r->rxdhdr[i] = CB->rxdhdr[i]; + r->txdhdr[i] = CB->txdhdr[i]; + r->txbufcntl[i] = CB->txbufcntl[i]; + r->rxbufcntl[i] = CB->rxbufcntl[i]; + } +} +#endif + +/* "rxsnap N: t=.. w=.. f=.. nx=.. lay=.. wait=.. tog=.. cntl0=.. cntl1=.. stat0=.. stat1=.. ahdr0=.. ahdr1=.. dhdr0=.. + * dhdr1=.. ifs=.. b0=xx xx xx xx b1=xx xx xx xx" (struct ble_diag_rxs: the advertising RX state an ISR saw) */ +static void bd_kxs(ble_diag_put put, const char *k, uint32_t v, uint32_t digits) +{ + put(" "); + put(k); + put("="); + bd_hex(put, v, digits); +} + +static void bd_rxsnap(ble_diag_put put, const char *name, uint32_t n, const struct ble_diag_rxs *x) +{ + uint32_t b, i; + put(name); + put(" "); + bd_dec(put, n); + put(": t="); + bd_dec(put, x->t_us); + put(" w="); + bd_dec(put, x->where); + put(" f="); + bd_dec(put, x->found); + put(" nx="); + bd_dec(put, x->rx_next); + put(" lay="); + bd_dec(put, x->layout); + put(" wait="); + bd_dec(put, x->wait_us); + bd_kxs(put, "tog", x->rxtog, 4); + bd_kxs(put, "cntl0", x->cntl[0], 2); + bd_kxs(put, "cntl1", x->cntl[1], 2); + bd_kxs(put, "stat0", x->stat[0], 4); + bd_kxs(put, "stat1", x->stat[1], 4); + bd_kxs(put, "ahdr0", x->ahdr[0], 4); + bd_kxs(put, "ahdr1", x->ahdr[1], 4); + bd_kxs(put, "dhdr0", x->dhdr[0], 4); + bd_kxs(put, "dhdr1", x->dhdr[1], 4); + bd_kxs(put, "ifs", x->ifscnt, 4); + for (b = 0; b < 2u; b++) { + put(b ? " b1=" : " b0="); + for (i = 0; i < 4u; i++) { + if (i) + put(" "); + bd_hex(put, x->b[b][i], 2); + } + } + put("\r\n"); +} + +/* RX while advertising: which rule found the packets (ble_hw_wl82.c hw_adv_find), the snapshots */ +static void bd_rxadv(ble_diag_put put, const struct ble_diag *d) +{ + uint32_t i, n = d->rxs_n < BLE_DIAG_RXS ? d->rxs_n : BLE_DIAG_RXS; + bd_kv(put, "rxf_cntl", d->rxf_cntl); + bd_kv(put, "rxf_cntl_other", d->rxf_cntl_other); + bd_kv(put, "rxf_tog_prev", d->rxf_tog_prev); + bd_kv(put, "rxf_tog_cur", d->rxf_tog_cur); + bd_kv(put, "rxf_wait", d->rxf_wait); + bd_kv(put, "rxf_late", d->rxf_late); + bd_kv(put, "rxf_none", d->rxf_none); + bd_kv(put, "rxl_cb", d->rxl_cb); + bd_kv(put, "rxl_buf", d->rxl_buf); + bd_kv(put, "rxl_none", d->rxl_none); + bd_kv(put, "rxh_synth", d->rxh_synth); + bd_kv(put, "rx_stat_zero", d->rx_stat_zero); + bd_kv(put, "rx_stat_bad_valid", d->rx_stat_bad_valid); + bd_kv(put, "rx_wait_us_max", d->rx_wait_us_max); + bd_kv(put, "rxsnaps", d->rxs_n); + if (d->rxs_first.found) + bd_rxsnap(put, "rxsnap_first", 0, &d->rxs_first); + for (i = d->rxs_n - n; i != d->rxs_n; i++) + bd_rxsnap(put, "rxsnap", i, &d->rxs[i & (BLE_DIAG_RXS - 1u)]); +} + +/* "txsnap N: t=.. evt=.. what=.. snap=.. b=.. n=.. tog=.. cntl0=.. cntl1=.. dhdr0=.. dhdr1=.. ifr=.. ptr0=.. ptr1=.. rxh=.." */ +static void bd_txsnap(ble_diag_put put, const char *name, uint32_t n, const struct ble_diag_txs *x) +{ + static const char *const WHAT[] = {"-", "-", "load", "ack"}; + put(name); + put(" "); + bd_dec(put, n); + put(": t="); + bd_dec(put, x->t_us); + put(" evt="); + bd_dec(put, x->evt); + put(" what="); + put(x->what < sizeof WHAT / sizeof WHAT[0] ? WHAT[x->what] : "?"); + bd_kxs(put, "snap", x->snap, 1); + put(" b="); + bd_dec(put, x->b); + put(" n="); + bd_dec(put, x->n); + bd_kxs(put, "tog", x->txtog, 4); + bd_kxs(put, "cntl0", x->cntl[0], 2); + bd_kxs(put, "cntl1", x->cntl[1], 2); + bd_kxs(put, "dhdr0", x->txdhdr[0], 4); + bd_kxs(put, "dhdr1", x->txdhdr[1], 4); + bd_kxs(put, "ifr", x->intframe, 4); + bd_kxs(put, "ptr0", x->txptr[0], 4); + bd_kxs(put, "ptr1", x->txptr[1], 4); + bd_kxs(put, "rxh", x->rxdhdr, 4); + put("\r\n"); +} + +/* TX in a connection (ble_hw_wl82.c hw_tx_service) and the connection RX rule against RXTOG */ +static void bd_tx(ble_diag_put put, const struct ble_diag *d) +{ + uint32_t i, n = d->txs_n < BLE_DIAG_TXS ? d->txs_n : BLE_DIAG_TXS; + bd_kv(put, "rxc_tog_past", d->rxc_tog_past); + bd_kv(put, "rxc_tog_at", d->rxc_tog_at); + bd_kv(put, "tx_eng_held", d->tx_eng_held); + bd_kv(put, "tx_ack_evt_max", d->tx_ack_evt_max); + bd_kv(put, "txsnaps", d->txs_n); + if (d->txs_first.what) + bd_txsnap(put, "txsnap_first", 0, &d->txs_first); + for (i = d->txs_n - n; i != d->txs_n; i++) + bd_txsnap(put, "txsnap", i, &d->txs[i & (BLE_DIAG_TXS - 1u)]); +} + +/* the host's protocol ring, oldest first: "pdu N: t=.. evt=.. rx|tx att|sig|smp|ll n=LEN: xx xx .." (at most the + * first 8 octets, opcode first; ble_diag.h ble_diag_pdu) */ +static void bd_pdus(ble_diag_put put, const struct ble_diag *d) +{ + static const char *const CH[5] = {"?", "att", "sig", "smp", "ll"}; + uint32_t i, k, n = d->pdu_n < BLE_DIAG_PDUS ? d->pdu_n : BLE_DIAG_PDUS; + bd_kv(put, "att_ntf", d->att_ntf_n); + bd_kv(put, "att_wcmd", d->att_wcmd_n); + bd_kv(put, "enc_req", d->enc_req_n); + bd_kv(put, "enc_on", d->enc_on_n); + bd_kv(put, "isr_max_us", d->isr_max_us); + bd_kv(put, "pdus", d->pdu_n); + for (i = d->pdu_n - n; i != d->pdu_n; i++) { + const struct ble_diag_pdu *x = &d->pdu[i & (BLE_DIAG_PDUS - 1u)]; + put("pdu "); + bd_dec(put, i); + put(": t="); + bd_dec(put, x->t_us); + put(" evt="); + bd_dec(put, x->evt); + put(x->ch & BDP_TX ? " tx " : " rx "); + put(CH[(x->ch & 0x7Fu) < 5u ? x->ch & 0x7Fu : 0u]); + put(" n="); + bd_dec(put, x->n); + put(":"); + for (k = 0; k < 8u && k < x->n; k++) { + put(" "); + bd_hex(put, x->b[k], 2); + } + put("\r\n"); + } +} + +/* BLE-MIDI in: the writes, the packets, the messages by kind, the last 4 packets and messages, oldest first */ +static void bd_midi(ble_diag_put put, const struct ble_diag *d) +{ + uint32_t i, k, n; + bd_kv(put, "mi_wcmd", d->mi_wcmd); + bd_kv(put, "mi_wreq", d->mi_wreq); + bd_kv(put, "mi_w_other", d->mi_w_other); + bd_kx(put, "mi_w_other_h", d->mi_w_other_h, 4); + bd_kv(put, "mi_pkts", d->mi_pkts); + bd_kv(put, "mi_bad_hdr", d->mi_bad_hdr); + bd_kv(put, "mi_note_on", d->mi_on); + bd_kv(put, "mi_note_off", d->mi_off); + bd_kv(put, "mi_cc", d->mi_cc); + bd_kv(put, "mi_clock", d->mi_clock); + bd_kv(put, "mi_sense", d->mi_sense); + bd_kv(put, "mi_other", d->mi_other); + n = d->mi_raw_n < 4u ? d->mi_raw_n : 4u; + for (i = d->mi_raw_n - n; i != d->mi_raw_n; i++) { + put("mi_raw n="); + bd_dec(put, d->mi_raw_len[i & 3u]); + put(":"); + for (k = 0; k < 12u && k < d->mi_raw_len[i & 3u]; k++) { + put(" "); + bd_hex(put, d->mi_raw[i & 3u][k], 2); + } + put("\r\n"); + } + n = d->mi_msg_n < 4u ? d->mi_msg_n : 4u; + for (i = d->mi_msg_n - n; i != d->mi_msg_n; i++) + bd_kx(put, "mi_msg", d->mi_msg[i & 3u], 8); /* cin | status << 8 | d1 << 16 | d2 << 24 */ +} + +#if BLE_CENTRAL +/* scanning (ble_dgs: the driver's and the link layer's counters; docs/BLE-STACK.md §9.1) */ +static void bd_scan(ble_diag_put put) +{ + const struct ble_diag_scan *s = &ble_dgs; + bd_kv(put, "scan_starts", s->starts); + bd_kv(put, "scan_stops", s->stops); + bd_kv(put, "scan_events", s->events); + bd_kv(put, "scan_rx_irqs", s->rx_irqs); + bd_kv(put, "scan_rxf_cntl", s->rxf_cntl); /* C2: RXBUFnCNTL bit0 marked the report */ + bd_kv(put, "scan_rxf_tog", s->rxf_tog); /* ... or only RXTOG moving past it did */ + bd_kv(put, "scan_rxf_none", s->rxf_none); + bd_kv(put, "scan_rx_bad_stat", s->rx_bad_stat); + bd_kv(put, "scan_rx_bad_len", s->rx_bad_len); + bd_kv(put, "scan_adv_ind", s->rep_adv_ind); + bd_kv(put, "scan_scan_rsp", s->rep_scan_rsp); /* C1: SCAN_RSPs mean the engine filled the SCAN_REQ's AdvA */ + bd_kv(put, "scan_other", s->rep_other); + bd_kv(put, "scan_ring_full", s->ring_full); + bd_kv(put, "scan_req_armed", s->req_armed); + bd_kv(put, "scan_req_fail", s->req_fail); + bd_kv(put, "scan_rsp_ok", s->rsp_ok); + bd_kv(put, "scan_upper_max", s->upper_max); + bd_kv(put, "scan_ch_next", s->ch); + bd_kv(put, "scan_last_ch", s->last_ch); + bd_kx(put, "scan_last_rssi", s->last_rssi, 4); + bd_kx(put, "scan_last_ahdr", s->last_ahdr, 4); + bd_kx(put, "scan_last_dhdr", s->last_dhdr, 4); + bd_kx(put, "scan_last_cntl", s->last_cntl, 2); + bd_kv(put, "scan_last_tog", s->last_tog); +} + +/* connecting out (ble_dgc; docs/BLE-DEVICES-DESIGN.md §4, HW §21.9 C3-C6): a step that stops shows where */ +static void bd_central(ble_diag_put put) +{ + const struct ble_diag_central *c = &ble_dgc; + bd_kv(put, "cen_connects", c->connects); + bd_kv(put, "cen_cancels", c->cancels); + bd_kv(put, "init_events", c->init_events); + bd_kv(put, "init_rx", c->init_rx); + bd_kv(put, "init_rx_target", c->init_rx_target); /* the target's ADV_IND heard while initiating */ + bd_kv(put, "init_rx_other", c->init_rx_other); + bd_kv(put, "init_rx_bad", c->init_rx_bad); + bd_kv(put, "init_rx_stale", c->init_rx_stale); /* a packet already in the air when initiating started: no hit */ + bd_kv(put, "init_rxf_cntl", c->init_rxf_cntl); + bd_kv(put, "init_rxf_tog", c->init_rxf_tog); + bd_kx(put, "init_last_ahdr", c->init_last_ahdr, 4); + bd_kx(put, "init_last_dhdr", c->init_last_dhdr, 4); + bd_kv(put, "init_last_ch", c->init_last_ch); + bd_kv(put, "init_chsel", c->init_chsel); + bd_kv(put, "master_starts", c->master_starts); + bd_kv(put, "c4_rx_to_evt_us", c->c4_rx_to_evt_us); /* C4: the event IRQ after the engine's CONNECT_IND */ + bd_kv(put, "c4_rx_to_evt_max", c->c4_rx_to_evt_max); + bd_kv(put, "m_setup_us", c->m_setup_us); /* the hit -> the anchor counter written (the last master) */ + bd_kv(put, "m_anchor_adj", c->m_anchor_adj); /* slots the first anchor was brought forward (last / max) */ + bd_kv(put, "m_anchor_adj_max", c->m_anchor_adj_max); + bd_kv(put, "m_anchor_late", c->m_anchor_late); /* too late for the transmit window even so */ + bd_kv(put, "m_events", c->m_events); + bd_kv(put, "m_events_rx", c->m_events_rx); /* C6: the peripheral answered our anchor packet */ + bd_kv(put, "m_first_rx_us", c->m_first_rx_us); /* C5: state 6 written -> its first packet */ + bd_kv(put, "m_first_rx_evt", c->m_first_rx_evt); + bd_kv(put, "m_first_evt", c->m_first_evt); + bd_kv(put, "m_estab_fails", c->m_estab_fails); /* C3: 0x3E right after a switch: no CONNECT_IND reached it */ + bd_kv(put, "m_sup_timeouts", c->m_sup_timeouts); + bd_kv(put, "m_closes", c->m_closes); + bd_kx(put, "m_close_reason", c->m_close_reason, 2); + bd_kv(put, "m_close_by", c->m_close_by); + bd_kv(put, "m_ver_rx", c->m_ver_rx); + bd_kv(put, "m_feat_rsp", c->m_feat_rsp); + bd_kv(put, "m_len_done", c->m_len_done); + bd_kv(put, "m_upd_tx", c->m_upd_tx); + bd_kv(put, "m_chm_tx", c->m_chm_tx); + bd_kv(put, "m_param_req_rx", c->m_param_req_rx); + bd_kv(put, "m_l2_upd_rx", c->m_l2_upd_rx); + bd_kv(put, "m_phy_req_rx", c->m_phy_req_rx); + bd_kv(put, "m_enc_req_tx", c->m_enc_req_tx); + bd_kv(put, "m_enc_rsp_rx", c->m_enc_rsp_rx); + bd_kv(put, "m_start_enc_rx", c->m_start_enc_rx); + bd_kv(put, "m_enc_on", c->m_enc_on); + bd_kv(put, "m_enc_rej", c->m_enc_rej); + bd_kx(put, "m_enc_rej_err", c->m_enc_rej_err, 2); + bd_kv(put, "m_held", c->m_held); /* its procedures held while our encryption started */ + bd_kv(put, "gc_starts", c->gc_starts); + bd_kv(put, "gc_state", c->gc_state); /* 1 MTU 2 service 3 services walked 4 chars 5 descs 6 CCCD 7 ready + * 8 failed */ + bd_kv(put, "gc_mtu", c->gc_mtu); + bd_kx(put, "gc_svc", (uint32_t)c->gc_svc_s << 16 | c->gc_svc_e, 8); + bd_kx(put, "gc_val", c->gc_val, 4); + bd_kx(put, "gc_cccd", c->gc_cccd, 4); + bd_kv(put, "gc_subscribed", c->gc_subscribed); + bd_kv(put, "gc_errs", c->gc_errs); + bd_kx(put, "gc_last_err", (uint32_t)c->gc_last_err_op << 24 | (uint32_t)c->gc_last_err_h << 8 | c->gc_last_err, 8); + bd_kv(put, "gc_auth_errs", c->gc_auth_errs); + bd_kv(put, "gc_retries", c->gc_retries); + bd_kv(put, "gc_ntf_rx", c->gc_ntf_rx); + bd_kv(put, "gc_ind_rx", c->gc_ind_rx); + bd_kv(put, "gc_wcmd_tx", c->gc_wcmd_tx); + bd_kv(put, "gc_timeouts", c->gc_timeouts); + bd_kv(put, "gc_no_midi", c->gc_no_midi); + bd_kv(put, "si_sec_req_rx", c->si_sec_req_rx); + bd_kv(put, "si_pair_req", c->si_pair_req); + bd_kv(put, "si_pair_rsp", c->si_pair_rsp); + bd_kv(put, "si_confirm_ok", c->si_confirm_ok); + bd_kv(put, "si_stk_enc", c->si_stk_enc); + bd_kv(put, "si_keys_rx", c->si_keys_rx); + bd_kv(put, "si_keys_tx", c->si_keys_tx); + bd_kv(put, "si_done", c->si_done); + bd_kv(put, "si_fail_rx", c->si_fail_rx); + bd_kv(put, "si_fail_tx", c->si_fail_tx); + bd_kx(put, "si_last_fail", c->si_last_fail, 2); + bd_kv(put, "si_ltk_enc", c->si_ltk_enc); + bd_kv(put, "si_fail_late", c->si_fail_late); + bd_kx(put, "si_rsp_io", c->si_rsp_io, 2); /* the responder's IO capability (04 KeyboardDisplay) */ + bd_kx(put, "si_rsp_auth", c->si_rsp_auth, 2); /* ... and AuthReq (bit 2 MITM, bit 3 SC) */ + bd_kv(put, "si_mitm_req", c->si_mitm_req); + bd_kv(put, "si_passkey", c->si_passkey); + bd_kv(put, "si_auth_done", c->si_auth_done); + bd_kv(put, "cen_need_mitm", c->cen_need_mitm); + bd_kv(put, "si_repair", c->si_repair); /* MITM pairing again on the encrypted link */ + bd_kv(put, "si_repair_fallback", c->si_repair_fallback); /* ... refused before a passkey: a new link */ + bd_kv(put, "m_pause_tx", c->m_pause_tx); /* LL_PAUSE_ENC_REQ (the new key on the same link) */ + bd_kv(put, "m_pause_rsp_rx", c->m_pause_rsp_rx); + bd_kv(put, "rc_phase", c->rc_phase); /* 0 off 1 wait 2 scan 3 initiate 4 a pick 5 linked 6 held */ + bd_kv(put, "rc_picks", c->picks); + bd_kv(put, "rc_tries", c->rc_tries); + bd_kv(put, "rc_scans", c->rc_scans); + bd_kv(put, "rc_rpa_seen", c->rc_rpa_seen); + bd_kv(put, "rc_rpa_ok", c->rc_rpa_ok); + bd_kv(put, "rc_ok", c->rc_ok); + bd_kv(put, "rc_fails", c->rc_fails); + bd_kv(put, "rc_retries", c->rc_retries); /* the link made again after a link failure (0x3E ...) */ + bd_kv(put, "rc_try", c->rc_try); /* the attempt's number, 1..6 */ + bd_kv(put, "rc_last_fail", c->rc_last_fail); /* BLE_CF_*: 1 lost 2 no MIDI 3 pairing 4 auth 5 GATT + * 6 needs a passkey 7 the bond refused (KEY) */ +} +#endif + +/* everything, in this order (docs/BLE-STACK.md §11 names the first fields to read); r: the engine's registers (r->valid 0: none) */ +static void ble_diag_print(ble_diag_put put, const struct ble_diag_regs *r) +{ + const struct ble_diag *d = &ble_dg; + uint32_t i, n; + put("ll_state "); + put(BD_LL[bll.state % 5u]); + put("\r\n"); + bd_kv(put, "ll_enabled", bll.enabled); + bd_kv(put, "ll_established", bll.state == LL_CONN && bll.established); + bd_kv(put, "ll_interval", bll.state == LL_CONN ? bll.interval : 0u); + bd_kv(put, "ll_lproc", bll.lproc); + bd_kv(put, "ll_rproc", bll.rproc); + bd_kv(put, "now_us", d->now_us); + if (r && r->valid) + bd_regs(put, r); + bd_kv(put, "adv_starts", d->adv_starts); + bd_kv(put, "adv_events", d->adv_events); + bd_kv(put, "adv_rx", d->adv_rx); + bd_kv(put, "scan_req", d->scan_req); + bd_kv(put, "adv_drop", d->adv_drop); + bd_kx(put, "adv_drop_stat", d->adv_drop_stat, 4); + bd_kx(put, "adv_drop_hdr", d->adv_drop_hdr, 4); + bd_kv(put, "busy_max", d->busy_max); + bd_kv(put, "busy_timeouts", d->busy_timeouts); + for (i = 0; i < BDS_COUNT; i++) { /* "stop_PATH stops busy max_us" */ + put("stop_"); + put(BD_STOP[i]); + put(" "); + bd_dec(put, d->stop_n[i]); + put(" "); + bd_dec(put, d->stop_busy[i]); + put(" "); + bd_dec(put, d->stop_us_max[i]); + put("\r\n"); + } + put("stop_last "); + put(BD_STOP[d->stop_last % BDS_COUNT]); + put("\r\n"); + bd_cind(put, d); + bd_conn(put, d); + bd_rxadv(put, d); + bd_tx(put, d); + bd_pdus(put, d); + bd_midi(put, d); +#if BLE_CENTRAL + bd_scan(put); + bd_central(put); +#endif + n = d->ev_n < BLE_DIAG_RING ? d->ev_n : BLE_DIAG_RING; + bd_kv(put, "events", d->ev_n); + for (i = d->ev_n - n; i != d->ev_n; i++) { /* "ev T_US NAME ARG", oldest first */ + uint32_t k = i & (BLE_DIAG_RING - 1u); + put("ev "); + bd_dec(put, d->ev[k].t_us); + put(" "); + put(d->ev[k].code < BDE_COUNT ? BD_EV[d->ev[k].code] : "?"); + put(" "); + if (d->ev[k].code == BDE_BUSY) { /* "busy PATH US" (hw_stop: path << 13 | us / 8) */ + put(BD_STOP[(d->ev[k].arg >> 13) % BDS_COUNT]); + put(" "); + bd_dec(put, (uint32_t)(d->ev[k].arg & 0x1FFFu) * 8u); + } else + bd_hex(put, d->ev[k].arg, 4); + put("\r\n"); + } +} + +/* `blell clear` (the BLE interrupts held): the counters and the ring from zero; the clock goes on */ +static void ble_diag_clear(void) +{ + uint8_t *p = (uint8_t *)&ble_dg; + uint32_t i; + for (i = 0; i < sizeof ble_dg; i++) + p[i] = 0; + ble_dg.magic = BLE_DIAG_MAGIC; + ble_dg.first_rx_evt = ble_dg.first_evt = 0xFFFFu; + p = (uint8_t *)&ble_dgs; + for (i = 0; i < sizeof ble_dgs; i++) + p[i] = 0; + ble_dgs.magic = BLE_DIAG_SCAN_MAGIC; +#if BLE_CENTRAL + p = (uint8_t *)&ble_dgc; + for (i = 0; i < sizeof ble_dgc; i++) + p[i] = 0; + ble_dgc.magic = BLE_DIAG_CENT_MAGIC; + ble_dgc.m_first_rx_evt = ble_dgc.m_first_evt = 0xFFFFu; +#endif +} + +#endif /* BLE_DIAG */ diff --git a/platform/ble/ble_diag.h b/platform/ble/ble_diag.h new file mode 100644 index 0000000..441f757 --- /dev/null +++ b/platform/ble/ble_diag.h @@ -0,0 +1,329 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* Link-layer diagnostics for the console's `blell` (docs/BLE-STACK.md §11): plain counters, the last CONNECT_IND, + * the last control and ATT opcodes, and a ring of the last 32 timestamped events. RAM only, a few hundred bytes. + * Written only from the BLE interrupts' context (ble_hw.h: the driver's ISRs, or the main loop with them held), so + * nothing here needs a lock; the console reads it (a value may be one event stale) and `blell clear` zeroes it with + * the BLE interrupts held. Recording never changes what the stack does. */ +#ifndef BLE_DIAG_H +#define BLE_DIAG_H +#include +#include "ble_cfg.h" + +/* BLE_DIAG: 1 keeps the counters, the rings and the console's `blell`; 0 compiles them out (builder item BLE_DIAG, + * FELUCCA_BLE_DIAG, docs/BLE-STACK.md §11). The host tests, which build this stack without felucca.c, keep it on. + * BLE_DG(statement) is a recording; with BLE_DIAG 0 it is nothing, and recording never changes what the stack does. */ +#ifndef BLE_DIAG +#ifdef FELUCCA_BLE_DIAG +#define BLE_DIAG FELUCCA_BLE_DIAG +#else +#define BLE_DIAG 1 +#endif +#endif +#if BLE_DIAG +#define BLE_DG(...) __VA_ARGS__ +#else +#define BLE_DG(...) ((void)0) +#endif + +#define BLE_DIAG_MAGIC 0x4C454C42u /* "BLEL": tests/ble_emu_test.py finds the block in a RAM dump by it */ +#define BLE_DIAG_RING 32u /* events kept (a power of two) */ +#define BLE_DIAG_LAST 8u /* opcodes kept (a power of two) */ +#define BLE_DIAG_RXS 8u /* RX snapshots kept while advertising (a power of two) */ +#define BLE_DIAG_TXS 8u /* TX decisions kept in a connection (a power of two) */ +#ifndef BLE_DIAG_PDUS +#define BLE_DIAG_PDUS 64u /* host PDUs kept (ATT, L2CAP signalling, SMP, LL encryption; a power of two) */ +#endif + +/* how an advertising-state RX was found (struct ble_diag_rxs.found; 0: nothing) */ +enum { BDF_NONE, BDF_CNTL, BDF_CNTL_OTHER, BDF_TOG_PREV, BDF_TOG_CUR }; +/* a TX snapshot's reason (struct ble_diag_txs.what; 1 was the obsolete "pol", kept free so load / ack keep their codes) */ +enum { BTX_NONE, BTX_LOAD = 2, BTX_ACK = 3 }; + +/* event codes of the ring (ble_diag.c prints their names) */ +enum { + BDE_NONE, BDE_ENABLE, BDE_ADV_START, BDE_ADV_STOP, BDE_ADV_DROP, BDE_CIND_RX, BDE_CIND_OK, BDE_CIND_REJ, + BDE_CONN_SET, BDE_FIRST_EVT, BDE_FIRST_RX, BDE_RX_BAD, BDE_RX_DESYNC, BDE_C3_ZERO, BDE_CTRL_RX, BDE_CTRL_TX, + BDE_INSTANT, BDE_CLOSE, BDE_BUSY, BDE_INIT_START, BDE_MASTER, BDE_INIT_HIT, BDE_COUNT +}; +/* why a CONNECT_IND was not taken (cind_rej_why) */ +enum { + BDR_OK, BDR_NOT_ADV, BDR_FORMAT, BDR_RXADD, BDR_ADVA, BDR_PARAMS, BDR_WINSIZE, BDR_WINOFF, BDR_HOP, BDR_CHM, + BDR_AA +}; +/* a protocol PDU's channel (struct ble_diag_pdu.ch, bits 0-6; bit 7: sent by us) */ +enum { BDP_ATT = 1, BDP_SIG = 2, BDP_SMP = 3, BDP_LL = 4, BDP_TX = 0x80 }; +/* the driver's link stops (ble_hw_wl82.c hw_stop; blell stop_*): advertising, scanning, initiating, a connection, the + * stop before a link is opened */ +enum { BDS_ADV, BDS_SCAN, BDS_INIT, BDS_CONN, BDS_OPEN, BDS_COUNT }; + +/* who closed a connection (close_by) */ +enum { BDC_LOCAL, BDC_PEER, BDC_SUPERVISION, BDC_ESTABLISH, BDC_PROC_TIMEOUT, BDC_PROTOCOL, BDC_TERM_UNACKED }; + +/* the driver's diagnostic clock: microseconds since the radio was first started (ble_hw.h; the link layer's timer too) */ +BLE_API uint32_t ble_hw_diag_now(void); + +#if BLE_DIAG +struct ble_diag { + uint32_t magic; + /* advertising (driver) */ + uint32_t adv_starts, adv_events, adv_rx, scan_req, adv_drop; + uint16_t adv_drop_stat, adv_drop_hdr; /* the last dropped one: RXSTAT, RXAHDR */ + uint16_t busy_max; /* the longest 0x28038 bit1 wait when a link stopped (us) */ + uint32_t busy_timeouts; /* ... that ran out (the engine still busy) */ + /* CONNECT_IND (driver + link layer) */ + uint32_t cind_rx, cind_ok, cind_rej; + uint8_t cind_rej_why, cind_hdr, cind_win_size, cind_hop, cind_sca, cind_chm[5]; + uint32_t cind_aa, cind_crc; + uint16_t cind_win_off, cind_interval, cind_latency, cind_timeout; + uint32_t cind_isr_us; /* RX IRQ entry -> state 7 written (us) */ + /* ble_host.c ble_sig_audio (the audio's slower interval): its calls, those with the audio streaming, the requests + * sent and those the full link queue held back; what it last saw (the interval, our request's state, slow) */ + uint32_t sa_calls, sa_on, sa_sent, sa_full; + uint16_t sa_iv; + uint8_t sa_fast, sa_slow; + uint32_t first_rx_us; /* state 7 written -> the first data PDU's RX IRQ (us) */ + uint16_t first_rx_evt, first_evt; /* their event counters (0xFFFF: none yet) */ + /* the connection (driver) */ + uint32_t evt_irqs, rx_irqs, conn_events, c3_zero, evt_same; + uint32_t rx_good, rx_crc_bad, rx_repeat, rx_empty, rx_nothing, rx_desync; + uint16_t rx_bad_stat, last_evt; + uint32_t tx_queued, tx_acked, tx_none; /* tx_none: a free buffer, nothing queued (the engine sends empty) */ + uint32_t clk_step_max; /* the largest step of the LL clock (TIMER4) between two reads in a + * connection (us); before 2026-10-08 the slot clock's, in slots */ + /* the link layer */ + uint32_t ctl_rx_n, ctl_tx_n, att_rx_n; + uint8_t ctl_rx[BLE_DIAG_LAST], ctl_tx[BLE_DIAG_LAST], att_rx[BLE_DIAG_LAST]; + uint32_t closes, sup_timeouts, estab_fails, peer_terms; + uint8_t close_reason, close_by; + uint16_t close_evt; /* the event counter at the last close */ + uint32_t close_since_rx_us, close_since_start_us; /* now - the last RX, now - CONNECT_IND, at that close */ + /* the event ring */ + uint32_t now_us, ev_n; + struct { uint32_t t_us; uint8_t code, pad; uint16_t arg; } ev[BLE_DIAG_RING]; + /* RX while advertising (the WL82 driver, ble_hw_wl82.c hw_adv_find): which rule found the packet. The engine's + * RX semantics are open (HW §3 RXTOG / RXBUFnCNTL [I], U7): the driver tries each rule and counts the one that + * matched, so a hardware run tells which is true */ + uint32_t rxf_cntl; /* RXBUFnCNTL bit0 = 1 on rx_next (the model's and our rule) */ + uint32_t rxf_cntl_other; /* ... on the other buffer */ + uint32_t rxf_tog_prev; /* content only (CNTL 0), in the buffer RXTOG has moved past */ + uint32_t rxf_tog_cur; /* content only, in the buffer RXTOG still points at */ + uint32_t rxf_wait; /* found only after the RX ISR polled RAM (the IRQ came early) */ + uint32_t rxf_late; /* found by the event ISR, not the RX ISR */ + uint32_t rxf_none; /* nothing by any rule, after the poll */ + uint32_t rxl_cb; /* layout: payload at RXPTR, header in RXAHDR/RXDHDR (the sheet) */ + uint32_t rxl_buf; /* layout: the 2 header bytes at RXPTR, the payload after them */ + uint32_t rxl_none; /* CNTL said filled but no PDU to our AdvA in either layout */ + uint32_t rxh_synth; /* RXAHDR held no 3 / 5: the header was rebuilt from the content */ + uint32_t rx_stat_zero; /* a PDU to us with RXSTAT 0 (never written): passed on */ + uint32_t rx_stat_bad_valid; /* a PDU to us with RXSTAT [3:0] not 0 / 1: dropped */ + uint32_t rx_wait_us_max; /* the longest RX ISR poll that found something (us) */ + uint32_t rxs_n; /* snapshots taken (rxs: the last 8; rxs_first: the first find) */ + struct ble_diag_rxs { /* the RX state as the ISR saw it, control block and RAM only */ + uint32_t t_us; + uint16_t rxtog, ifscnt, stat[2], ahdr[2], dhdr[2]; + uint8_t cntl[2], b[2][4]; /* RXBUFnCNTL; the first 4 bytes at RXPTRn */ + uint8_t where; /* 0 RX ISR entry, 1 RX ISR after the poll, 2 event ISR */ + uint8_t found; /* BDF_* */ + uint8_t rx_next, layout; /* layout: 0 none, 1 RXAHDR + RXPTR, 2 header at RXPTR */ + uint16_t wait_us; + } rxs[BLE_DIAG_RXS], rxs_first; + /* the connection's RX rule against RXTOG: a buffer RXBUFnCNTL said filled, RXTOG past it / still on it */ + uint32_t rxc_tog_past, rxc_tog_at; + /* TX in a connection (ble_hw_wl82.c hw_tx_service, HW §8.2: TXBUFnCNTL bit0 1 = empty, 0 = the engine's): + * service passes that found a buffer with bit0 0 and no PDU of ours in it (the engine's own, seen at the first + * event on the FM-1); the most events from loading a PDU to its bit0 reading 1 again (its acknowledgement) */ + uint32_t tx_eng_held, tx_ack_evt_max; + uint32_t txs_n; /* snapshots taken (txs: the last 8; txs_first: the first load) */ + struct ble_diag_txs { + uint32_t t_us; + uint16_t evt, txtog, txdhdr[2], intframe; + uint16_t txptr[2], rxdhdr; /* TXPTR0/1; the central's last RXDHDR (NESN bit2, SN bit3) */ + uint8_t cntl[2]; /* TXBUFnCNTL after the step */ + uint8_t what, b, n, snap; /* BTX_*, the buffer; n: bit b = a PDU of ours in buffer b; snap: the + * service's snapshot, bit0 TXTOG bit0, bit1 / bit2 TXBUF0 / 1CNTL bit0 */ + } txs[BLE_DIAG_TXS], txs_first; + /* the host's protocol, both ways (ble_diag_pdu): every ATT PDU but MIDI's (notifications 0x1B and Write Commands + * 0x52, only counted), every L2CAP signalling and SMP PDU, and the LL's encryption PDUs (ENC_REQ / RSP, START_ENC, + * PAUSE_ENC, and a reject or unknown answer about them). The PDU's first 8 octets (opcode first) as they went, + * the length, the event counter */ + uint32_t pdu_n, att_ntf_n, att_wcmd_n, enc_req_n, enc_on_n; + uint32_t isr_max_us; /* the longest BLE interrupt (RX or event, us; the WL82 driver) */ + struct ble_diag_pdu { + uint32_t t_us; + uint16_t evt; /* the driver's last event counter (ble_dg.last_evt) */ + uint8_t ch, n; /* BDP_* (| BDP_TX), the length (255: or more) */ + uint8_t b[8]; + } pdu[BLE_DIAG_PDUS]; + /* BLE-MIDI in (ble_att.c; the app's side, the ring into the router: midi_ble.c ble_mdg): Write Commands and + * Requests on the MIDI I/O value and on any other handle (the last one), packets decoded / with no valid header, + * the decoded messages by kind, the last 4 packets (their first 12 octets, the length) and the last 4 messages + * (USB-MIDI event packets) */ + uint32_t mi_wcmd, mi_wreq, mi_w_other, mi_pkts, mi_bad_hdr; + uint32_t mi_on, mi_off, mi_cc, mi_clock, mi_sense, mi_other; + uint16_t mi_w_other_h, mi_pad; + uint32_t mi_raw_n, mi_msg_n; + uint8_t mi_raw[4][12], mi_raw_len[4]; + uint32_t mi_msg[4]; + /* the link stops (hw_stop), per BDS_* path: stops, those that found the engine busy (0x28038 bit1), the longest + * wait (us), the last path */ + uint32_t stop_n[BDS_COUNT], stop_busy[BDS_COUNT]; + uint16_t stop_us_max[BDS_COUNT]; + uint8_t stop_last, stop_pad; +}; + +#define BLE_DIAG_MIDI_KIND(d, pkt) \ + do { \ + uint32_t st_ = ((pkt) >> 8) & 0xFFu; \ + if ((st_ & 0xF0u) == 0x90u && ((pkt) >> 24) & 0x7Fu) \ + (d).mi_on++; \ + else if ((st_ & 0xF0u) == 0x80u || (st_ & 0xF0u) == 0x90u) \ + (d).mi_off++; \ + else if ((st_ & 0xF0u) == 0xB0u) \ + (d).mi_cc++; \ + else if (st_ == 0xF8u) \ + (d).mi_clock++; \ + else if (st_ == 0xFEu) \ + (d).mi_sense++; \ + else \ + (d).mi_other++; \ + (d).mi_msg[(d).mi_msg_n++ & 3u] = (pkt); \ + } while (0) + +static struct ble_diag ble_dg = {.magic = BLE_DIAG_MAGIC, .first_rx_evt = 0xFFFFu, .first_evt = 0xFFFFu}; + +/* scanning (BLE_CENTRAL; docs/BLE-STACK.md §9.1, HW §21.2), a block of its own so ble_dg's layout (which + * tests/ble_emu_test.py reads) stays as it is. Driver: starts .. upper_max; link layer: rep_* .. ring_full */ +#define BLE_DIAG_SCAN_MAGIC 0x4E414353u /* "SCAN" */ +struct ble_diag_scan { + uint32_t magic; + uint32_t starts, stops, events, rx_irqs; /* scans started / stopped, event and RX interrupts while scanning */ + uint32_t rxf_cntl, rxf_tog, rxf_none; /* a report found by RXBUFnCNTL bit0 (the vendor's connection-path + * rule, HW §21.2) / by RXTOG moved past it (§8.1 advertising) / none + * (C2 settles which the engine does while scanning) */ + uint32_t rx_bad_stat, rx_bad_len; /* RXSTAT [3:0] != 1; a length outside 6..37 */ + uint32_t rep_adv_ind, rep_scan_rsp, rep_other, ring_full; /* reports by type into the ring; lost to a full ring */ + uint32_t req_armed, req_fail, rsp_ok; /* active scan: SCAN_REQs allowed (FORMAT bit8 0), failures, SCAN_RSPs */ + uint16_t upper_max, last_rssi; /* the backoff's largest upperLimit; the last report's RSSI word */ + uint16_t last_ahdr, last_dhdr; /* the last report's RXAHDR / RXDHDR */ + uint8_t ch, last_ch, last_cntl, last_tog; /* the channel programmed next; the last report's LASTCHMAP, the + * RXBUFnCNTL pair and RXTOG it was found with */ +}; +static struct ble_diag_scan ble_dgs = {.magic = BLE_DIAG_SCAN_MAGIC}; + +#if BLE_CENTRAL +/* connecting out (BLE_CENTRAL; docs/BLE-DEVICES-DESIGN.md §4, HW §21.3 / §21.4 / §21.9), a block of its own as + * ble_dgs: each step of the initiator, the master link, its procedures, the GATT client, the SMP initiator and the + * reconnection, so a hardware run shows where a connection stops. c3_..c6_ / c7: the fact sheet's §21.9 questions */ +#define BLE_DIAG_CENT_MAGIC 0x544E4543u /* "CENT" */ +struct ble_diag_central { + uint32_t magic; + /* the initiator (ble_ll_connect, the driver's state 3) */ + uint32_t connects, cancels, init_events; /* initiations started / cancelled; event IRQs in state 3 */ + uint32_t init_rx, init_rx_target, init_rx_other, init_rx_bad; /* RX IRQs in state 3: the target's ADV_IND / + * ADV_DIRECT_IND, another advertiser, nothing usable */ + uint32_t init_rxf_cntl, init_rxf_tog; /* how it was found: RXBUFnCNTL bit0 / RXTOG moved past it */ + uint32_t master_starts; /* the switch to state 6 (the event IRQ after the target's ADV_IND) */ + uint32_t c4_rx_to_evt_us, c4_rx_to_evt_max; /* C4: the target's RX IRQ -> the event IRQ that switched (last / + * max, us): the event IRQ's place after the engine's CONNECT_IND */ + uint16_t init_last_ahdr, init_last_dhdr; /* the last state-3 report's RXAHDR / RXDHDR */ + uint8_t init_chsel, init_last_ch, pad0[2]; /* the target's ChSel bit (0: CSA #1); the last report's channel */ + /* the master link (HW §21.4) */ + uint32_t m_events, m_events_rx; /* events closed / with a packet from the peripheral (C6: it answered + * our anchor packet inside WINCNTL2 30 us) */ + uint32_t m_first_rx_us; /* C5: state 6 written -> the peripheral's first packet (us) */ + uint16_t m_first_rx_evt, m_first_evt; /* C5: their event counters (0xFFFF: none yet) */ + uint32_t m_estab_fails, m_sup_timeouts, m_closes; /* C3: an establishment failure (0x3E) right after a switch + * means no CONNECT_IND reached the peripheral (or a wrong anchor) */ + uint8_t m_close_reason, m_close_by, pad1[2]; + /* the master's LL procedures */ + uint32_t m_ver_rx, m_feat_rsp, m_len_done, m_upd_tx, m_chm_tx, m_param_req_rx, m_phy_req_rx, m_l2_upd_rx; + uint32_t m_enc_req_tx, m_enc_rsp_rx, m_start_enc_rx, m_enc_on, m_enc_rej; + uint8_t m_enc_rej_err, m_held, pad2[2]; /* m_held: its control PDUs held while our encryption started */ + /* the GATT client (ble_gattc.c) */ + uint32_t gc_starts, gc_mtu, gc_subscribed, gc_errs, gc_auth_errs, gc_retries, gc_ntf_rx, gc_ind_rx, gc_wcmd_tx; + uint32_t gc_timeouts, gc_no_midi; + uint16_t gc_svc_s, gc_svc_e, gc_val, gc_cccd; /* the BLE-MIDI service's range, the MIDI I/O value, its CCCD */ + uint16_t gc_last_err_h; + uint8_t gc_state, gc_last_err_op, gc_last_err; + /* the SMP initiator (ble_smp.c) */ + uint8_t si_last_fail; /* the last Pairing Failed reason, either way */ + uint32_t si_sec_req_rx, si_pair_req, si_pair_rsp, si_confirm_ok, si_fail_rx, si_fail_tx, si_stk_enc; + uint32_t si_keys_rx, si_keys_tx, si_done, si_ltk_enc; /* their keys taken, ours sent (PDUs); bonds; links + * encrypted with a stored LTK */ + uint32_t si_mitm_req, si_passkey, si_auth_done; /* pairings asking MITM; passkeys shown; authenticated pairings */ + uint32_t si_fail_late, cen_need_mitm; /* a Pairing Failed after the pairing ended; refused again after + * Just Works (the link left to pair with a passkey) */ + uint8_t si_rsp_io, si_rsp_auth, pad4[2]; /* the last Pairing Response's IO capability and AuthReq */ + /* the reconnection to LAST and the picks (io/midi/ble_devices.c) */ + uint32_t rc_tries, rc_scans, rc_rpa_seen, rc_rpa_ok, rc_ok, rc_fails, picks; + uint8_t rc_phase, rc_last_fail, pad3[2]; + /* 2026-10-09 (blell-dev4): the first anchor made up for a late set-up, the master's re-pairing on the link, the + * link retries */ + uint32_t m_setup_us; /* the target's RX IRQ -> the anchor counter written (us, last) */ + uint8_t m_anchor_adj, m_anchor_adj_max, pad5[2]; /* slots the counter was shortened by (last / max) */ + uint32_t m_anchor_late; /* set-ups too late to reach the transmit window */ + uint32_t m_pause_tx, m_pause_rsp_rx; /* LL_PAUSE_ENC_REQ sent; the peripheral's LL_PAUSE_ENC_RSP */ + uint32_t si_repair, si_repair_fallback; /* re-pairings with MITM on the encrypted link; those the peer + * refused before any passkey (-> a new link with MITM) */ + uint32_t rc_retries; /* link attempts made again after a link failure (no pairing) */ + uint8_t rc_try, pad6[3]; /* the attempt's number (1..BLE_RC_TRIES) */ + uint32_t init_rx_stale; /* 2026-10-13: state-3 reports of a packet already in the air when + * initiating started (the stopped scan's): no hit (hw_init_stale) */ +}; +static struct ble_diag_central ble_dgc = {.magic = BLE_DIAG_CENT_MAGIC, .m_first_rx_evt = 0xFFFFu, + .m_first_evt = 0xFFFFu}; +#endif + +/* the engine's side, read when `blell` prints (the WL82 driver's ble_hw_diag_regs, the BLE interrupts held) */ +#define BLE_DIAG_COLS 9u /* columns 0-6, 14, 15 (ble_diag.c) */ +struct ble_diag_regs { + uint8_t valid, hw_state, rx_next, rx_sn, tx_n, win_wide; + uint16_t col[BLE_DIAG_COLS]; + uint32_t ien, ipnd, g2en, g2pnd, stat, clock; + uint16_t txtog, rxtog, intframe, format, optcntl, evtcount, wincntl0, rxstat[2], rxahdr[2], rxdhdr[2], txdhdr[2]; + uint8_t txbufcntl[2], rxbufcntl[2]; +}; + +static inline void ble_diag_ev(uint8_t code, uint32_t arg) +{ + uint32_t i = ble_dg.ev_n++ & (BLE_DIAG_RING - 1u); + ble_dg.now_us = ble_hw_diag_now(); + ble_dg.ev[i].t_us = ble_dg.now_us; + ble_dg.ev[i].code = code; + ble_dg.ev[i].arg = (uint16_t)arg; +} + +/* one protocol PDU (ch: BDP_*, | BDP_TX when ours), p: its payload from the opcode on, n octets */ +static inline void ble_diag_pdu(uint8_t ch, const uint8_t *p, uint32_t n) +{ + struct ble_diag_pdu *x; + uint32_t i; + if ((ch & 0x7Fu) == BDP_ATT && n && (p[0] == 0x1Bu || p[0] == 0x52u)) { + if (p[0] == 0x1Bu) + ble_dg.att_ntf_n++; + else + ble_dg.att_wcmd_n++; + return; + } + x = &ble_dg.pdu[ble_dg.pdu_n++ & (BLE_DIAG_PDUS - 1u)]; + ble_dg.now_us = ble_hw_diag_now(); + x->t_us = ble_dg.now_us; + x->evt = ble_dg.last_evt; + x->ch = ch; + x->n = (uint8_t)(n > 255u ? 255u : n); + for (i = 0; i < 8u; i++) + x->b[i] = i < n ? p[i] : 0u; +} + +static inline void ble_diag_last(uint8_t *ring, uint32_t *n, uint8_t v) +{ + ring[(*n)++ & (BLE_DIAG_LAST - 1u)] = v; +} + +#else /* !BLE_DIAG: the events and the opcode rings are nothing (the counters go through BLE_DG) */ +#define ble_diag_ev(code, arg) ((void)0) +#define ble_diag_pdu(ch, p, n) ((void)0) +#define BLE_DIAG_MIDI_KIND(d, pkt) ((void)0) +#endif + +#endif diff --git a/platform/ble/ble_gattc.c b/platform/ble/ble_gattc.c new file mode 100644 index 0000000..c95fc0c --- /dev/null +++ b/platform/ble/ble_gattc.c @@ -0,0 +1,341 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The ATT client of the central role (BLE_CENTRAL; Core Specification Vol 3 Part F / G), finding a peripheral's + * BLE-MIDI characteristic and turning its notifications on (MIDI Association, "Specification for MIDI over Bluetooth + * Low Energy" 1.0): + * 1. Exchange MTU (ours BLE_ATT_MTU_MAX; the smaller one is used both ways, ble_att_set_mtu); + * 2. Find By Type Value: the primary service with the BLE-MIDI UUID -> its handle range (a server that does not + * support it: Read By Group Type over all primary services instead); + * 3. Read By Type 0x2803 in that range -> the MIDI I/O characteristic (its 128-bit UUID) and where it ends (the next + * declaration, or the service's end); + * 4. Find Information after its value -> its Client Characteristic Configuration descriptor (0x2902); + * 5. Write Request CCCD = 0x0001 (notifications) -> ready: notifications on the value are MIDI in (ble_att.c's + * decoder), MIDI out goes as Write Without Response (ble_att.c att_midi_out). + * One request outstanding, the 30 s transaction timeout. An Error Response asking for security (Insufficient + * Authentication 0x05, Insufficient Encryption 0x0F, Insufficient Encryption Key Size 0x0C) hands over to the host + * (ble_central.c: encrypt with the bond, else pair) and the same request is sent again once the link is encrypted. */ +#include "ble.h" +#include "ble_host.h" +#include "ble_ll.h" +#include "ble_util.h" +#include "ble_diag.h" + +enum { G_IDLE, G_MTU, G_SVC, G_SVC_GRP, G_CHR, G_DSC, G_CCCD, G_READY, G_FAIL }; +enum { GE_AUTHEN = 0x05, GE_NOT_SUPP = 0x06, GE_KEY_SIZE = 0x0C, GE_NOT_FOUND = 0x0A, GE_ENC = 0x0F }; + +/* the MIDI I/O characteristic 7772E5DB-3868-4112-A1A9-F2669D106BF3, least significant octet first */ +static const uint8_t GC_UUID_MIDI_IO[16] = {0xF3, 0x6B, 0x10, 0x9D, 0x66, 0xF2, 0xA9, 0xA1, + 0x12, 0x41, 0x68, 0x38, 0xDB, 0xE5, 0x72, 0x77}; + +/* (ble_central.c) */ +static void ble_central_gattc_ready(void); +static void ble_central_gattc_fail(uint8_t why, uint8_t code); +static int ble_central_gattc_auth(uint8_t code); + +static struct { + uint8_t st, wait_sec, due; /* G_*; a request waits for the link's security; one waits for room */ + uint8_t req[23], req_n; /* the request outstanding (sent again after security) */ + uint32_t t_req; /* when it went (the 30 s timeout) */ + uint16_t svc_s, svc_e, val, end, cccd, next; /* the service, the value, the characteristic's end, its CCCD, the + * next handle to look from */ +} bgc; + +static void gc_send(void) +{ + if (!ble_ll_send(L2CAP_CID_ATT, bgc.req, bgc.req_n)) { + bgc.due = 1; /* no room now: the next event */ + return; + } + bgc.due = 0; + bgc.t_req = ble_hw_time_us(); +} + +static void gc_req_range(uint8_t op, uint16_t s, uint16_t e, uint16_t type) +{ + bgc.req[0] = op; + ble_wr16(bgc.req + 1, s); + ble_wr16(bgc.req + 3, e); + bgc.req_n = 5; + if (type) { + ble_wr16(bgc.req + 5, type); + bgc.req_n = 7; + } + gc_send(); +} + +static void gc_fail(uint8_t why, uint8_t code) +{ + bgc.st = G_FAIL; + BLE_DG(ble_dgc.gc_state = G_FAIL); + ble_central_gattc_fail(why, code); +} + +static void gc_step(uint8_t st) +{ + bgc.st = st; + BLE_DG(ble_dgc.gc_state = st); +} + +static void gc_find_service(void) /* Find By Type Value: primary service = the BLE-MIDI UUID */ +{ + gc_step(G_SVC); + bgc.req[0] = 0x06; + ble_wr16(bgc.req + 1, 1); + ble_wr16(bgc.req + 3, 0xFFFF); + ble_wr16(bgc.req + 5, 0x2800); + ble_cpy(bgc.req + 7, BLE_UUID_MIDI_SVC, 16); + bgc.req_n = 23; + gc_send(); +} + +static void gc_chars(uint16_t from) +{ + gc_step(G_CHR); + gc_req_range(0x08, from, bgc.svc_e, 0x2803); +} + +static void gc_descs(uint16_t from) +{ + if (from > bgc.end) { + gc_fail(BLE_CF_NO_MIDI, 0); /* the MIDI I/O characteristic has no CCCD */ + return; + } + gc_step(G_DSC); + gc_req_range(0x04, from, bgc.end, 0); +} + +static void gc_subscribe(void) +{ + gc_step(G_CCCD); + bgc.req[0] = 0x12; /* Write Request */ + ble_wr16(bgc.req + 1, bgc.cccd); + bgc.req[3] = 0x01; /* notifications */ + bgc.req[4] = 0x00; + bgc.req_n = 5; + gc_send(); +} + +static void gc_service(uint16_t s, uint16_t e) +{ + bgc.svc_s = s; + bgc.svc_e = e; + BLE_DG(ble_dgc.gc_svc_s = s); + BLE_DG(ble_dgc.gc_svc_e = e); + bgc.val = 0; + gc_chars(s); +} + +/* Read By Type Response (0x2803 declarations): handle, properties, value handle, UUID */ +static void gc_chars_rsp(const uint8_t *p, uint16_t n) +{ + uint16_t i, el = p[1], last = 0; + if (el < 7u) + return; + for (i = 2; i + el <= n; i = (uint16_t)(i + el)) { + uint16_t decl = ble_rd16(p + i), v = ble_rd16(p + i + 3); + last = decl; + if (bgc.val && decl > bgc.val) { /* the declaration after ours: our characteristic ends before it */ + bgc.end = (uint16_t)(decl - 1u); + gc_descs((uint16_t)(bgc.val + 1u)); + return; + } + if (!bgc.val && el == 21u && ble_eq(p + i + 5, GC_UUID_MIDI_IO, 16) && (p[i + 2] & 0x10u)) { + bgc.val = v; /* (notify among its properties) */ + BLE_DG(ble_dgc.gc_val = v); + } + } + if (last >= bgc.svc_e || !last) { /* the service's end */ + if (!bgc.val) { + gc_fail(BLE_CF_NO_MIDI, 0); + return; + } + bgc.end = bgc.svc_e; + gc_descs((uint16_t)(bgc.val + 1u)); + return; + } + gc_chars((uint16_t)(last + 1u)); /* more declarations in the service */ +} + +/* Find Information Response: handle + UUID pairs (format 1: 16-bit, 2: 128-bit) */ +static void gc_descs_rsp(const uint8_t *p, uint16_t n) +{ + uint16_t i, el = p[1] == 1u ? 4u : 18u, last = 0; + for (i = 2; i + el <= n; i = (uint16_t)(i + el)) { + last = ble_rd16(p + i); + if (el == 4u && ble_rd16(p + i + 2) == 0x2902u) { + bgc.cccd = last; + BLE_DG(ble_dgc.gc_cccd = last); + gc_subscribe(); + return; + } + } + gc_descs((uint16_t)(last + 1u)); +} + +/* Read By Group Type Response (primary services; the fallback): handle, end, UUID */ +static void gc_groups_rsp(const uint8_t *p, uint16_t n) +{ + uint16_t i, el = p[1], last = 0; + for (i = 2; i + el <= n; i = (uint16_t)(i + el)) { + last = ble_rd16(p + i + 2); + if (el == 20u && ble_eq(p + i + 4, BLE_UUID_MIDI_SVC, 16)) { + gc_service(ble_rd16(p + i), last); + return; + } + } + if (!last || last == 0xFFFFu) { + gc_fail(BLE_CF_NO_MIDI, 0); + return; + } + gc_req_range(0x10, (uint16_t)(last + 1u), 0xFFFF, 0x2800); +} + +static void gc_error(const uint8_t *p) +{ + uint8_t code = p[4]; + BLE_DG(ble_dgc.gc_errs++); + BLE_DG(ble_dgc.gc_last_err_op = p[1]); + BLE_DG(ble_dgc.gc_last_err_h = ble_rd16(p + 2)); + BLE_DG(ble_dgc.gc_last_err = code); + if (code == GE_AUTHEN || code == GE_ENC || code == GE_KEY_SIZE) { + BLE_DG(ble_dgc.gc_auth_errs++); + if (ble_central_gattc_auth(code)) + bgc.wait_sec = 1; /* sent again once encrypted (ble_gattc_retry) */ + else + gc_fail(BLE_CF_AUTH, code); + return; + } + switch (bgc.st) { + case G_SVC: + if (code == GE_NOT_SUPP) { /* no Find By Type Value: walk the primary services */ + gc_step(G_SVC_GRP); + gc_req_range(0x10, 1, 0xFFFF, 0x2800); + } else + gc_fail(code == GE_NOT_FOUND ? BLE_CF_NO_MIDI : BLE_CF_GATT, code); + return; + case G_SVC_GRP: + gc_fail(code == GE_NOT_FOUND ? BLE_CF_NO_MIDI : BLE_CF_GATT, code); + return; + case G_CHR: + if (code == GE_NOT_FOUND && bgc.val) { /* no declaration after ours: it runs to the service's end */ + bgc.end = bgc.svc_e; + gc_descs((uint16_t)(bgc.val + 1u)); + } else + gc_fail(code == GE_NOT_FOUND ? BLE_CF_NO_MIDI : BLE_CF_GATT, code); + return; + case G_DSC: + gc_fail(code == GE_NOT_FOUND ? BLE_CF_NO_MIDI : BLE_CF_GATT, code); + return; + default: + gc_fail(BLE_CF_GATT, code); + return; + } +} + +BLE_API void ble_gattc_reset(void) +{ + ble_zero((uint8_t *)&bgc, sizeof bgc); +} + +/* a link as central is up: MTU first */ +BLE_API void ble_gattc_start(void) +{ + ble_gattc_reset(); + BLE_DG(ble_dgc.gc_starts++); + gc_step(G_MTU); + bgc.req[0] = 0x02; + ble_wr16(bgc.req + 1, BLE_ATT_MTU_MAX); + bgc.req_n = 3; + gc_send(); +} + +/* the link is encrypted now: the request that asked for it again */ +BLE_API void ble_gattc_retry(void) +{ + if (!bgc.wait_sec) + return; + bgc.wait_sec = 0; + BLE_DG(ble_dgc.gc_retries++); + gc_send(); +} + +BLE_API uint16_t ble_gattc_midi(void) { return bgc.st == G_READY ? bgc.val : 0u; } + +/* an ATT PDU from the peripheral's server: 1 taken (a response to us, a notification or an indication), 0 not ours + * (a request from its client to our server: ble_att.c) */ +BLE_API int ble_gattc_rx(const uint8_t *p, uint16_t n) +{ + uint8_t op = p[0]; + if (op == 0x1Bu || op == 0x1Du) { /* Handle Value Notification / Indication */ + if (op == 0x1Du) { + static const uint8_t conf = 0x1E; + ble_ll_send(L2CAP_CID_ATT, &conf, 1); + BLE_DG(ble_dgc.gc_ind_rx++); + } else + BLE_DG(ble_dgc.gc_ntf_rx++); + if (n >= 3u && bgc.st == G_READY && ble_rd16(p + 1) == bgc.val) + ble_att_midi_packet(p + 3, (uint16_t)(n - 3u)); + return 1; + } + if (op != 0x01u && (!(op & 1u) || op > 0x19u)) + return 0; /* requests and commands: the server's */ + if (bgc.st == G_IDLE || bgc.st == G_READY || bgc.st == G_FAIL || bgc.wait_sec) + return 1; /* (nothing of ours outstanding) */ + bgc.t_req = 0; + if (op == 0x01u) { + if (n == 5u && p[1] == bgc.req[0]) + gc_error(p); + return 1; + } + if (op != (uint8_t)(bgc.req[0] + 1u)) + return 1; /* (not the answer to ours) */ + switch (bgc.st) { + case G_MTU: + if (n == 3u) { + uint16_t m = ble_rd16(p + 1); + ble_att_set_mtu(m < 23u ? 23u : m); + BLE_DG(ble_dgc.gc_mtu = ble_att_mtu()); + } + gc_find_service(); + return 1; + case G_SVC: + if (n >= 5u) + gc_service(ble_rd16(p + 1), ble_rd16(p + 3)); + else + gc_fail(BLE_CF_GATT, 0); + return 1; + case G_SVC_GRP: + if (n >= 2u) + gc_groups_rsp(p, n); + return 1; + case G_CHR: + if (n >= 2u) + gc_chars_rsp(p, n); + return 1; + case G_DSC: + if (n >= 2u) + gc_descs_rsp(p, n); + return 1; + case G_CCCD: /* Write Response: subscribed */ + gc_step(G_READY); + BLE_DG(ble_dgc.gc_subscribed++); + ble_central_gattc_ready(); + return 1; + default: + return 1; + } +} + +/* each connection event: a request waiting for room; the 30 s timeout */ +BLE_API void ble_gattc_event(uint32_t now) +{ + if (bgc.st == G_IDLE || bgc.st == G_READY || bgc.st == G_FAIL || bgc.wait_sec) + return; + if (bgc.due) { + gc_send(); + return; + } + if (bgc.t_req && now - bgc.t_req > BLE_GATTC_TIMEOUT_US) { + BLE_DG(ble_dgc.gc_timeouts++); + gc_fail(BLE_CF_GATT, 0xFF); + } +} diff --git a/platform/ble/ble_host.c b/platform/ble/ble_host.c new file mode 100644 index 0000000..b0b01c9 --- /dev/null +++ b/platform/ble/ble_host.c @@ -0,0 +1,320 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The host below ATT (Core Specification Vol 3): + * - GAP: the advertisement (flags, the BLE-MIDI service UUID) and the scan response (the name), Part C 11; + * - L2CAP on LE: basic frames over the fixed channels, reassembled from the link layer's fragments; the LE + * signalling channel: our Connection Parameter Update Request and its response, Command Reject for every + * request we do not take (Part A 4); + * - SMP: ble_smp.c ("Pairing Not Supported", or legacy Just Works with BLE_SMP_LEGACY); the key slot the link + * layer's encryption asks (BLE_LL_ENC). + * Every ATT, signalling and SMP PDU in and out goes into blell's protocol ring (ble_diag.h ble_diag_pdu). */ +#include "ble.h" +#include "ble_host.h" +#include "ble_ll.h" +#include "ble_hw.h" +#include "ble_util.h" +#include "ble_diag.h" + +static struct { + uint8_t rx[4 + BLE_ATT_MTU_MAX]; /* one L2CAP frame being reassembled */ + uint16_t have, need; /* octets in rx / of the frame (header included) */ + uint16_t skip; /* octets of a frame too big for rx still to come */ + uint8_t sig_id, fast; /* our last signalling identifier; 0 / 1 asked / 2 retried / 3 done */ + uint8_t audio; /* Bluetooth audio streams: a faster interval refused (ble_ll.c) */ + uint8_t slow; /* audio streamed on this link: the fast interval to ask for again after */ + uint8_t asked; /* the slower interval asked for, at ask_us (asked again after a while) */ + uint32_t ask_us; +} bhs; + +/* the advertised name and the GAP Device Name: BLE_DEVICE_NAME, then " XXXX" = the last four hex digits of the device + * address (its two least significant octets, as an address is written: "Optimist A1B2" for ..:A1:B2; docs/ + * BLE-DEVICES-DESIGN.md §1) */ +#define BLE_GAP_NAME_MAX 29u +static struct { + char s[BLE_GAP_NAME_MAX]; + uint8_t n; +} bgap; + +static void gap_name(const uint8_t addr[6]) +{ + static const char base[] = BLE_DEVICE_NAME, HEX[] = "0123456789ABCDEF"; + uint32_t n = sizeof base - 1u; + if (n > BLE_GAP_NAME_MAX - (BLE_NAME_HEX ? 5u : 0u)) + n = BLE_GAP_NAME_MAX - (BLE_NAME_HEX ? 5u : 0u); + ble_cpy((uint8_t *)bgap.s, (const uint8_t *)base, n); +#if BLE_NAME_HEX + bgap.s[n++] = ' '; + bgap.s[n++] = HEX[addr[1] >> 4]; + bgap.s[n++] = HEX[addr[1] & 15u]; + bgap.s[n++] = HEX[addr[0] >> 4]; + bgap.s[n++] = HEX[addr[0] & 15u]; +#else + (void)addr, (void)HEX; +#endif + bgap.n = (uint8_t)n; +} + +BLE_API uint8_t ble_gap_name(const uint8_t **p) +{ + *p = (const uint8_t *)bgap.s; + return bgap.n; +} + +BLE_API void ble_init(const uint8_t addr[6], uint8_t addr_random) +{ + uint8_t ad[3 + 18], sr[31], n; + ad[0] = 2; /* flags: LE General Discoverable, BR/EDR not supported */ + ad[1] = 0x01; + ad[2] = 0x06; + ad[3] = 17; /* complete list of 128-bit service UUIDs: BLE-MIDI */ + ad[4] = 0x07; + ble_cpy(ad + 5, BLE_UUID_MIDI_SVC, 16); + gap_name(addr); + n = bgap.n; + sr[0] = (uint8_t)(n + 1u); + sr[1] = 0x09; /* complete local name */ + ble_cpy(sr + 2, (const uint8_t *)bgap.s, n); + ble_ll_init(addr, addr_random); + ble_ll_set_adv_data(ad, sizeof ad, sr, (uint8_t)(n + 2u)); + ble_att_reset(); +} + +BLE_API void ble_enable(int on) { ble_ll_enable(on); } +BLE_API int ble_connected(void) { return ble_ll_connected(); } + +/* ------------------------------------------------------------------------------------------- the link --- */ + +BLE_API void ble_host_connected(void) +{ + bhs.have = bhs.need = bhs.skip = 0; + bhs.fast = bhs.slow = bhs.asked = 0; + ble_att_reset(); + ble_smp_connected(); +#if BLE_CENTRAL + ble_central_connected(); /* (as master: the GATT client, the bond's encryption) */ +#endif + ble_app_state(); +} + +BLE_API void ble_host_disconnected(uint8_t reason) +{ + (void)reason; + bhs.have = bhs.need = bhs.skip = 0; + ble_att_reset(); + ble_smp_reset(); +#if BLE_CENTRAL + ble_central_disconnected(reason); +#endif + ble_app_state(); +} + +/* ------------------------------------------------------------------------------------- LE signalling --- */ + +static int sig_send(uint8_t code, uint8_t id, const uint8_t *d, uint16_t n) /* -> 0: the link's queue full, not sent */ +{ + uint8_t p[4 + 8]; + p[0] = code; + p[1] = id; + ble_wr16(p + 2, n); + ble_cpy(p + 4, d, n); + return ble_ll_send(L2CAP_CID_SIG, p, (uint16_t)(4u + n)); +} + +static int sig_conn_params(uint16_t lo, uint16_t hi, uint16_t timeout) /* -> 0: not sent (asked again later) */ +{ + uint8_t d[8]; + ble_wr16(d, lo); + ble_wr16(d + 2, hi); + ble_wr16(d + 4, BLE_CONN_LATENCY); + ble_wr16(d + 6, timeout); + if (!++bhs.sig_id) + bhs.sig_id = 1; + return sig_send(0x12, bhs.sig_id, d, 8); /* Connection Parameter Update Request */ +} + +BLE_API void ble_sig_want_fast(void) +{ + uint16_t iv = ble_ll_interval(); +#if BLE_CENTRAL + if (ble_ll_central()) + return; /* (as master the interval is ours: BLE_CENTRAL_INTERVAL) */ +#endif + if (bhs.fast || !iv) + return; + bhs.fast = 3; + if (iv < BLE_CONN_MIN || iv > BLE_CONN_MAX) { + bhs.fast = 1; + sig_conn_params(BLE_CONN_MIN, BLE_CONN_MAX, BLE_CONN_TIMEOUT); + } +} + +/* Bluetooth audio streams or stops (op_bt.c bt_poll, every main loop). While it streams the link layer refuses the + * central's faster interval (ble_host_audio, ble_ll.c: a Mac connects at 30 ms, then asks for 7.5 ms itself, LL + * CONNECTION_PARAM_REQ), and a link faster than BLE_CONN_AUDIO_MIN is asked for BLE_CONN_AUDIO_MIN..MAX, again every + * BLE_SIG_AUDIO_RETRY_US while it stays fast; once it stops, BLE_CONN_MIN..MAX again. Never over a request of ours under + * way; the link's queue full (MIDI clock, the screen mirror): not sent, asked at the next loop. As master the interval + * is ours: nothing (2026-10-25, on the FM-1 with a Mac: the request was never sent, the link at 7.5 ms, the audio short of + * air) */ +BLE_API int ble_host_audio(void) { return bhs.audio; } +BLE_API void ble_sig_audio(int on) +{ + uint16_t iv = ble_ll_interval(); + int sent; + on = on != 0; + bhs.audio = (uint8_t)on; + BLE_DG(ble_dg.sa_calls++, ble_dg.sa_on += (uint32_t)on, ble_dg.sa_iv = iv, ble_dg.sa_fast = bhs.fast, + ble_dg.sa_slow = bhs.slow); +#if BLE_CENTRAL + if (ble_ll_central()) + return; +#endif + if (!iv || bhs.fast == 1u || bhs.fast == 2u) + return; + if (on) { + bhs.slow = 1; + if ((iv >= BLE_CONN_AUDIO_MIN && ble_ll_timeout() >= BLE_CONN_AUDIO_TIMEOUT) || /* (a Mac connects at 30 ms + * with 720 ms: a gap of the audio's ends it; its own update to 2 s + * comes with the 7.5 ms we refuse: 2 s asked for, 2026-10-25) */ + (bhs.asked && ble_hw_time_us() - bhs.ask_us < BLE_SIG_AUDIO_RETRY_US)) + return; + sent = sig_conn_params(BLE_CONN_AUDIO_MIN, BLE_CONN_AUDIO_MAX, BLE_CONN_AUDIO_TIMEOUT); + BLE_DG(ble_dg.sa_sent += (uint32_t)sent, ble_dg.sa_full += (uint32_t)!sent); + if (!sent) + return; + bhs.asked = 1, bhs.ask_us = ble_hw_time_us(); + bhs.fast = 3; /* (ble_sig_want_fast's request not made over it) */ + return; + } + bhs.asked = 0; + if (!bhs.slow) + return; + if (iv >= BLE_CONN_MIN && iv <= BLE_CONN_MAX) { + bhs.slow = 0; + return; + } + sent = sig_conn_params(BLE_CONN_MIN, BLE_CONN_MAX, BLE_CONN_TIMEOUT); + BLE_DG(ble_dg.sa_sent += (uint32_t)sent, ble_dg.sa_full += (uint32_t)!sent); + if (sent) + bhs.slow = 0; +} + +static void sig_rx(const uint8_t *p, uint16_t n) +{ + uint8_t code, id, d[2] = {0, 0}; + if (n < 4u || (uint32_t)ble_rd16(p + 2) + 4u > n || !p[1]) + return; + code = p[0]; + id = p[1]; + switch (code) { + case 0x13: /* Connection Parameter Update Response */ + if (id != bhs.sig_id || n < 6u) + return; + if (ble_rd16(p + 4) && bhs.fast == 1 && BLE_CONN_RETRY_MIN > 0u) { + bhs.fast = 2; /* rejected: ask once more, slower */ + sig_conn_params(BLE_CONN_RETRY_MIN, BLE_CONN_RETRY_MAX, BLE_CONN_TIMEOUT); + } else + bhs.fast = 3; + return; + case 0x01: /* Command Reject (of ours) */ + if (id == bhs.sig_id) + bhs.fast = 3; + return; + case 0x07: case 0x15: case 0x16: case 0x18: case 0x1A: /* responses and indications: nothing to do */ + return; +#if BLE_CENTRAL + case 0x12: /* Connection Parameter Update Request: ours to answer as master */ + if (ble_ll_central()) { + d[0] = ble_central_sig(p + 4, (uint16_t)(n - 4u)); /* the result: 0 accepted, 1 rejected */ + sig_send(0x13, id, d, 2); + } else + sig_send(0x01, id, d, 2); + return; +#endif + default: /* anything else: Command Reject, "command not understood" */ + sig_send(0x01, id, d, 2); + return; + } +} + +/* ------------------------------------------------------------------------------------------ L2CAP RX --- */ + +static void l2cap_frame(const uint8_t *f, uint16_t n) +{ + uint16_t cid = ble_rd16(f + 2); + if (cid >= L2CAP_CID_ATT && cid <= L2CAP_CID_SMP) /* (blell's protocol ring) */ + ble_diag_pdu((uint8_t)(cid - 3u), f + 4, (uint32_t)(n - 4u)); + if (cid == L2CAP_CID_ATT) + ble_att_rx(f + 4, (uint16_t)(n - 4u)); + else if (cid == L2CAP_CID_SIG) + sig_rx(f + 4, (uint16_t)(n - 4u)); + else if (cid == L2CAP_CID_SMP) + ble_smp_rx(f + 4, (uint16_t)(n - 4u)); +} + +BLE_API void ble_host_rx(const uint8_t *p, uint8_t len, uint8_t start) +{ + uint32_t take; + if (start) { + bhs.have = bhs.need = bhs.skip = 0; /* (an unfinished frame before it is dropped) */ + if (len < 2u) + return; + bhs.need = (uint16_t)(ble_rd16(p) + 4u); + if (bhs.need > sizeof bhs.rx) { /* too big for us: let it pass */ + bhs.skip = (uint16_t)(bhs.need - ble_min(len, bhs.need)); + bhs.need = 0; + return; + } + } else if (bhs.skip) { + bhs.skip = (uint16_t)(bhs.skip - ble_min(len, bhs.skip)); + return; + } else if (!bhs.need) + return; /* a continuation without a start */ + take = ble_min(len, (uint32_t)(bhs.need - bhs.have)); + ble_cpy(bhs.rx + bhs.have, p, take); + bhs.have = (uint16_t)(bhs.have + take); + if (bhs.have >= 4u && bhs.have == bhs.need) { + bhs.need = 0; + l2cap_frame(bhs.rx, bhs.have); + bhs.have = 0; + } +} + +BLE_API void ble_host_event(void) +{ +#if BLE_CENTRAL + ble_central_event(); /* (as master: the GATT client's and SMP's timeouts) */ +#endif + ble_att_event(); +} + +#if BLE_LL_ENC +/* one key slot: the bond SMP made (ble_smp.c), or the one the firmware kept across a power-off (ble_host_set_key at + * start-up); in RAM here */ +static struct { + uint8_t valid, rand[8], ltk[16]; + uint16_t ediv; +} bhs_key; + +BLE_API void ble_host_set_key(const uint8_t rand[8], uint16_t ediv, const uint8_t ltk[16]) +{ + ble_cpy(bhs_key.rand, rand, 8); + ble_cpy(bhs_key.ltk, ltk, 16); + bhs_key.ediv = ediv; + bhs_key.valid = 1; +} + +#if !BLE_SMP_LEGACY +BLE_API void ble_host_encrypted(void) {} +#endif + +BLE_API int ble_host_ltk(const uint8_t rand[8], uint16_t ediv, uint8_t ltk[16]) +{ +#if BLE_SMP_LEGACY + if (ble_smp_stk(rand, ediv, ltk)) /* a pairing's short-term key first */ + return 1; +#endif + if (!bhs_key.valid || ediv != bhs_key.ediv || !ble_eq(rand, bhs_key.rand, 8)) + return 0; + ble_cpy(ltk, bhs_key.ltk, 16); + return 1; +} +#endif diff --git a/platform/ble/ble_host.h b/platform/ble/ble_host.h new file mode 100644 index 0000000..548006a --- /dev/null +++ b/platform/ble/ble_host.h @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* Inside the host: L2CAP (ble_host.c: fixed channels, LE signalling, SMP, GAP start-up) and the ATT server with + * its GATT database (ble_att.c). */ +#ifndef BLE_HOST_H +#define BLE_HOST_H +#include +#include "ble_cfg.h" + +enum { L2CAP_CID_ATT = 4, L2CAP_CID_SIG = 5, L2CAP_CID_SMP = 6 }; + +/* the BLE-MIDI service UUID 03B80E5A-EDE8-4B33-A751-6CE34EC4C700, least significant octet first */ +static const uint8_t BLE_UUID_MIDI_SVC[16] = {0x00, 0xC7, 0xC4, 0x4E, 0xE3, 0x6C, 0x51, 0xA7, + 0x33, 0x4B, 0xE8, 0xED, 0x5A, 0x0E, 0xB8, 0x03}; + +/* the frames ble_att.c may queue: a response must always find room, so notifications leave this much */ +#define BLE_ATT_RESERVE (BLE_ATT_MTU_MAX + 8u) + +/* ble_host.c: the GAP Device Name (also the advertised name), set by ble_init -> its length */ +BLE_API uint8_t ble_gap_name(const uint8_t **p); + +/* ble_att.c */ +BLE_API void ble_att_rx(const uint8_t *p, uint16_t n); /* an ATT PDU from the client */ +BLE_API void ble_att_reset(void); /* a new connection, or none */ +BLE_API void ble_att_event(void); /* each connection event: indications, MIDI out */ + +BLE_API void ble_att_set_mtu(uint16_t client_mtu); /* the other side's MTU (the smaller one is used) */ +BLE_API uint16_t ble_att_mtu(void); +BLE_API void ble_att_midi_packet(const uint8_t *v, uint16_t n); /* a BLE-MIDI packet in (a write, a notification) */ + +#if BLE_CENTRAL +/* ble_gattc.c: the ATT client of the central role (finds the BLE-MIDI characteristic, subscribes) */ +BLE_API void ble_gattc_reset(void); +BLE_API void ble_gattc_start(void); +BLE_API void ble_gattc_retry(void); /* the link is encrypted: the request that asked again */ +BLE_API int ble_gattc_rx(const uint8_t *p, uint16_t n); /* 1: a PDU for the client (responses, notifications) */ +BLE_API uint16_t ble_gattc_midi(void); /* the MIDI I/O value handle once subscribed, else 0 */ +BLE_API void ble_gattc_event(uint32_t now); +/* ble_central.c: the host's side of the central role */ +BLE_API void ble_central_connected(void); +BLE_API void ble_central_disconnected(uint8_t reason); +BLE_API void ble_central_event(void); +BLE_API uint8_t ble_central_sig(const uint8_t *d, uint16_t n); /* a Connection Parameter Update Request -> result */ +#if !BLE_CEN_PAIR +/* BLE_CENTRAL 3: the peripheral asked for security (0: its SMP Security Request; else the ATT error): the link is left */ +BLE_API void ble_central_no_pairing(uint8_t code); +#endif +#endif + +/* ble_host.c: ask the central for BLE_CONN_MIN..MAX (L2CAP Connection Parameter Update Request), once per + * connection, unless the interval in use is in that range already */ +BLE_API void ble_sig_want_fast(void); +/* ble_host.c: Bluetooth audio streams (1) or not (0): the slower interval BLE_CONN_AUDIO_MIN..MAX asked for meanwhile */ +BLE_API void ble_sig_audio(int on); +#if BLE_LL_ENC +/* the key the link layer may use (LTK least significant octet first, for Rand and EDIV) */ +BLE_API void ble_host_set_key(const uint8_t rand[8], uint16_t ediv, const uint8_t ltk[16]); +#endif + +/* ble_smp.c: an SMP PDU from the central; a new connection / none */ +BLE_API void ble_smp_rx(const uint8_t *p, uint16_t n); +BLE_API void ble_smp_connected(void); +BLE_API void ble_smp_reset(void); +#if BLE_SMP_LEGACY +/* the short-term key while a pairing waits for the encryption (EDIV 0, Rand 0): 1 given, 0 none */ +BLE_API int ble_smp_stk(const uint8_t rand[8], uint16_t ediv, uint8_t ltk[16]); +#endif + +#endif diff --git a/platform/ble/ble_hw.h b/platform/ble/ble_hw.h new file mode 100644 index 0000000..d76b1d9 --- /dev/null +++ b/platform/ble/ble_hw.h @@ -0,0 +1,160 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The baseband driver's interface: what the link layer (ble_ll.c) asks of the radio, and what the driver + * reports back. Designed for a link-controller engine that does the timing of each event in hardware: + * advertising on 37 / 38 / 39 with an automatic SCAN_RSP; anchors, the transmit window, CSA #1 hopping, the + * access-address match, CRC (software gives the CRC init), SN / NESN with acknowledgement and retransmission + * from two alternating TX buffers (and two RX buffers), the connection event counter and the instant compare. + * The link layer keeps the queues, the control procedures, the supervision timeout and the encryption. + * + * Context: every ble_ll_hw_* call comes from one context, the driver's BLE interrupts (the event IRQ and the + * RX IRQ at one priority, never nested in each other); every ble_hw_* call is made from inside one of them, + * except ble_hw_adv_start() at start-up (ble_enable() with the BLE IRQs not yet on, or masked). + * + * PDUs are passed as they are on air without access address and CRC: the 2-octet header (octet 0: type / LLID + * and flags, octet 1: length) followed by the payload. Multi-octet fields inside are least significant first. + * + * How this maps onto the AC791N engine (docs/BLE-HW-FACTS.md, sections in brackets; the driver's job): + * - one link (n = 0): its 324-byte control block and the TX / RX payload buffers in the baseband RAM block + * (3, 4); columns through the port at 0x2801C / 0x28020 (2.3); IRQ 45 = event, IRQ 29 = RX (8, 10); + * - ble_hw_adv_start: ADV_IND into TX buffer 0, SCAN_RSP into TX buffer 1 (the engine answers SCAN_REQ by + * itself), interval in 625 us slots in columns 1 / 15, state 2 (6). Our header octet 0 is the Core layout + * (TxAdd bit 6); TXAHDR wants TxAdd in bit 4: the driver moves it; + * - ble_ll_hw_connect_ind is called from the RX IRQ that holds the CONNECT_IND, and ble_hw_conn_start is + * called inside it: the same link goes from state 2 to 7 before the IRQ returns, with the window widening + * from interval and SCA, and the first anchor 1.25 ms + WinOffset after the CONNECT_IND (7). The link + * layer does nothing slow on that path (the host only resets its state); + * - ble_ll_hw_tx fills the free fixed TX buffer: TXDHDR = length << 8 | MD << 3 | LLID, keeping the engine's + * bit 2; our MD is header bit 4 (Core layout); INTFRAME bit 6 = MD; TXBUFnCNTL bit 0 cleared last (8.2). At the + * end of each connection RX IRQ, a buffer we loaded whose bit 0 reads 1 again (empty) is ble_ll_hw_tx_acked, + * then ble_ll_hw_tx for the next (8.2); + * - ble_ll_hw_rx: the header rebuilt from RXDHDRn (Core layout already), the payload from the RX buffer; packets + * with RXSTAT [3:0] != 1 are not passed on (8); + * - ble_ll_hw_event_end from IRQ 45 with column 3 - 1 as the counter (8); + * - ble_hw_conn_update / ble_hw_chmap_update: column 5 = instant at once; the new window, widening, interval + * (columns 1, 2, 4, 15) or the channel tables are written in the event IRQ of event instant - 1 (9); + * - the supervision timeout is software (7): the link layer's, from ble_hw_time_us; + * - ble_hw_addr: the stored BLE address (VM id 104, public in stock: TxAdd 0) (11). */ +#ifndef BLE_HW_H +#define BLE_HW_H +#include +#include "ble_cfg.h" + +/* ---- the link layer asks (the driver implements these) ---- */ + +struct ble_hw_adv { + const uint8_t *adv; /* ADV_IND PDU (header + AdvA + AdvData), 8..39 octets */ + uint8_t adv_len; + const uint8_t *scan_rsp; /* SCAN_RSP PDU (header + AdvA + ScanRspData): sent by the engine to a SCAN_REQ + * whose AdvA is ours */ + uint8_t scan_rsp_len; + uint16_t interval; /* advInterval x 0.625 ms (32..16384); the engine adds advDelay (0..10 ms) */ + uint8_t channels; /* bit 0: 37, bit 1: 38, bit 2: 39 */ +}; +/* start (or restart with new PDUs) connectable undirected advertising. A CONNECT_IND to our AdvA is handed + * to ble_ll_hw_connect_ind(); the driver keeps advertising until ble_hw_conn_start() or ble_hw_adv_stop(). */ +BLE_API void ble_hw_adv_start(const struct ble_hw_adv *a); +BLE_API void ble_hw_adv_stop(void); + +struct ble_hw_conn { + uint32_t aa; /* access address */ + uint32_t crc_init; /* 24 bits */ + uint8_t win_size; /* transmitWindowSize x 1.25 ms */ + uint16_t win_offset; /* transmitWindowOffset x 1.25 ms */ + uint16_t interval; /* connInterval x 1.25 ms (6..3200) */ + uint16_t latency; /* connPeripheralLatency: the link layer always passes 0 (listen every event) */ + uint16_t timeout; /* connSupervisionTimeout x 10 ms (for the driver's information) */ + uint8_t chm[5]; /* channel map, 37 bits */ + uint8_t hop; /* hopIncrement 5..16, Channel Selection Algorithm #1 */ + uint8_t sca; /* the central's sleep clock accuracy (0..7): widening the receive window */ +}; +/* called from inside ble_ll_hw_connect_ind(), before it returns: the engine leaves advertising and listens + * for the first packet in the transmit window 1.25 ms + win_offset after the end of the CONNECT_IND it + * received. Event counter 0 is that first event. */ +BLE_API void ble_hw_conn_start(const struct ble_hw_conn *c); +/* leave the connection now (the engine stops; no more ble_ll_hw_* calls for it) */ +BLE_API void ble_hw_conn_stop(void); + +/* (as master, HW §21.4: the same call; the driver writes the master's values at instant - 1) */ +struct ble_hw_conn_upd { + uint8_t win_size; + uint16_t win_offset; + uint16_t interval; + uint16_t latency; /* (0 again) */ + uint16_t timeout; + uint16_t instant; /* the event counter value from which the new parameters apply */ +}; +/* LL_CONNECTION_UPDATE_IND: the engine moves to the new parameters at the instant (the old interval ends at + * the instant's old anchor, then the transmit window starts win_offset later) */ +BLE_API void ble_hw_conn_update(const struct ble_hw_conn_upd *u); +/* LL_CHANNEL_MAP_IND: the new map from the event whose counter is instant on */ +BLE_API void ble_hw_chmap_update(const uint8_t chm[5], uint16_t instant); +/* the data length in use (LL_LENGTH_REQ / RSP): the largest payload either side sends from now on, 27..251 */ +BLE_API void ble_hw_set_lengths(uint8_t max_tx, uint8_t max_rx); +/* new data queued: a free TX buffer can be filled now (ble_ll_hw_tx), or at the next event */ +BLE_API void ble_hw_tx_kick(void); + +#if BLE_CENTRAL +/* scanning (HW §21.2): the same link in state 1, on 37 -> 38 -> 39 (software moves the channel in each event + * interrupt), the RX interrupt's reports handed to ble_ll_hw_adv_report(). One link only: advertising is stopped + * first (ble_hw_adv_stop) and started again after ble_hw_scan_stop (docs/BLE-DEVICES-DESIGN.md §1, docs/BLE-STACK.md §9.1). */ +struct ble_hw_scan { + uint16_t interval, window; /* x 0.625 ms; window + 4 <= interval */ + uint8_t active; /* 1: the engine sends SCAN_REQ on an ADV_IND (FORMAT bit8 0), with the Core's backoff */ + uint8_t own_rand; /* our address type (the SCAN_REQ's TxAdd) */ + const uint8_t *own; /* our address (the SCAN_REQ's ScanA), 6 octets */ +}; +BLE_API void ble_hw_scan_start(const struct ble_hw_scan *s); +BLE_API void ble_hw_scan_stop(void); +/* an advertising-channel PDU received while scanning (header 2 + AdvA + AdvData, CRC good), the engine's RSSI word + * (0: none) and the channel (37..39). RX interrupt: copy it and return */ +BLE_API void ble_ll_hw_adv_report(const uint8_t *pdu, uint8_t len, uint16_t rssi, uint8_t ch); + +/* initiating (HW §21.3): the same link in state 3 with our CONNECT_IND complete in both TX buffers before it starts; + * the engine sends it by itself T_IFS after an ADV_IND (or an ADV_DIRECT_IND to us) from the one target address + * (WHITELIST0 / TARGETADR, FILTERCNTL bits 0 / 4 / 8). The driver sees the target's ADV_IND in the RX interrupt and, + * in the event interrupt after it, turns the link into the master of the connection (state 6, the anchor counter + * 2 x WinOffset + 4 slots), then calls ble_ll_hw_master_start(); from there the link is a connection like a + * peripheral's (ble_ll_hw_rx / tx / tx_acked / event_end, ble_hw_conn_update, ...). Advertising is stopped first + * (one link, ble_hw_adv_stop / ble_hw_scan_stop) */ +struct ble_hw_init { + uint16_t interval, window; /* x 0.625 ms, as scanning */ + const uint8_t *cind; /* the CONNECT_IND PDU: header (type 5, TxAdd, RxAdd) + InitA + AdvA + LLData, 36 */ + struct ble_hw_conn conn; /* its LLData, as sent (the master's set-up) */ +}; +BLE_API void ble_hw_init_start(const struct ble_hw_init *i); +BLE_API void ble_hw_init_stop(void); +/* the event interrupt: the link is the master of the connection our CONNECT_IND made (event counter 0 is its first + * anchor). The link layer starts its connection state here */ +BLE_API void ble_ll_hw_master_start(void); +#endif + +/* the device address (least significant octet first): 0 public, 1 random static */ +BLE_API uint8_t ble_hw_addr(uint8_t addr[6]); +/* a free-running microsecond clock (wraps at 2^32) */ +BLE_API uint32_t ble_hw_time_us(void); +/* n random octets (the encryption's SKDs and IVs: BLE_LL_ENC only) */ +BLE_API void ble_hw_rand(uint8_t *out, uint8_t n); + +/* ---- the driver reports (the link layer implements these) ---- */ + +/* a CONNECT_IND to our AdvA (pdu: header + 34 octets). Returns 1 when the link layer took the connection + * (ble_hw_conn_start() was called), 0 when it was ignored (invalid parameters): advertising goes on. */ +BLE_API int ble_ll_hw_connect_ind(const uint8_t *pdu, uint8_t len); +/* a new data-channel PDU received in the current event: CRC good, not a retransmission (the engine's SN + * check), empty PDUs may be left out. pdu[0] carries LLID, NESN, SN, MD as received. */ +BLE_API void ble_ll_hw_rx(const uint8_t *pdu, uint8_t len); +/* a TX buffer is free: the link layer writes the next PDU into pdu (room for 2 + 255 octets: + * 251 and an encrypted PDU's MIC) and returns its + * length (2 + payload), or 0 when there is nothing to send (the engine sends an empty PDU). The link layer + * sets LLID and MD (more queued); the engine sets NESN and SN. The PDU is final: the engine retransmits it as + * it is until it is acknowledged. */ +BLE_API uint8_t ble_ll_hw_tx(uint8_t *pdu); +/* 1 when ble_ll_hw_tx() would return a PDU now (control or data queued); nothing is taken */ +BLE_API int ble_ll_hw_tx_pending(void); +/* the oldest PDU returned by ble_ll_hw_tx() and not yet reported was acknowledged by the central */ +BLE_API void ble_ll_hw_tx_acked(void); +/* a connection event closed: counter = its connEventCounter; rx_ok = at least one packet with a good CRC was + * received in it. Called for every event, also the ones where nothing was received. */ +BLE_API void ble_ll_hw_event_end(uint16_t counter, uint8_t rx_ok); + +#endif diff --git a/platform/ble/ble_hw_stub.c b/platform/ble/ble_hw_stub.c new file mode 100644 index 0000000..09a2887 --- /dev/null +++ b/platform/ble/ble_hw_stub.c @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* A stand-in for the baseband driver (ble_hw.h): it accepts every request and never calls back, so the stack links, + * sits idle in advertising and costs no time. FELUCCA_BLE_STUB=1 builds it instead of the real driver + * (ble_hw_wl82.c); FELUCCA_BLE_HW leaves both out for a build that brings its own. */ +#include "ble_hw.h" + +BLE_API void ble_hw_adv_start(const struct ble_hw_adv *a) { (void)a; } +BLE_API void ble_hw_adv_stop(void) {} +BLE_API void ble_hw_conn_start(const struct ble_hw_conn *c) { (void)c; } +BLE_API void ble_hw_conn_stop(void) {} +BLE_API void ble_hw_conn_update(const struct ble_hw_conn_upd *u) { (void)u; } +BLE_API void ble_hw_chmap_update(const uint8_t chm[5], uint16_t instant) +{ + (void)chm; + (void)instant; +} +BLE_API void ble_hw_set_lengths(uint8_t max_tx, uint8_t max_rx) +{ + (void)max_tx; + (void)max_rx; +} +BLE_API void ble_hw_tx_kick(void) {} +BLE_API uint8_t ble_hw_addr(uint8_t addr[6]) +{ + static const uint8_t a[6] = {0x01, 0x00, 0x00, 0x00, 0x00, 0xC0}; /* random static (top bits 11): a placeholder */ + uint32_t i; + for (i = 0; i < 6u; i++) + addr[i] = a[i]; + return 1; +} +BLE_API uint32_t ble_hw_time_us(void) { return 0; } +BLE_API uint32_t ble_hw_diag_now(void) { return 0; } +BLE_API void ble_hw_rand(uint8_t *out, uint8_t n) +{ + while (n--) + *out++ = 0; +} +#if BLE_CENTRAL +BLE_API void ble_hw_scan_start(const struct ble_hw_scan *s) { (void)s; } +BLE_API void ble_hw_scan_stop(void) {} +BLE_API void ble_hw_init_start(const struct ble_hw_init *i) { (void)i; } +BLE_API void ble_hw_init_stop(void) {} +#endif diff --git a/platform/ble/ble_hw_wl82.c b/platform/ble/ble_hw_wl82.c new file mode 100644 index 0000000..8db4cfd --- /dev/null +++ b/platform/ble/ble_hw_wl82.c @@ -0,0 +1,1219 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The baseband driver (ble_hw.h) on the AC791N / WL82 BLE engine, route C (docs/BLE-STACK.md §7, the interface §3; FELUCCA_BLE). + * + * Clean room: written from the hardware fact sheet docs/BLE-HW-FACTS.md (feat/ble-facts 41b7374, TX: §8.2 at a3b2f06; "HW §n" + * below), the Bluetooth Core Specification (Vol 6 Part B) and the answers the emulator's engine model gave from + * stock V15 running in it (fm1-emulator feat/ble-engine 6531e20; "model" below). No vendor code, IR or disassembly. + * The registers are reached through hal/fm1_ble.h; this file owns the baseband RAM block and the control block, + * plain SRAM the engine reads and writes by DMA (HW §3, §4). + * + * What it does: + * - one static baseband RAM block: the instance table, link 0's 324-byte control block, two RX and two TX + * buffers (each a 20-byte software header then the payload, the pointers at the payload: HW §4); + * - advertising (HW §6): ADV_IND in TX buffer 0, SCAN_RSP in TX buffer 1 (the engine answers SCAN_REQ by itself); + * - the CONNECT_IND in the RX interrupt, handed to the link layer, which calls ble_hw_conn_start() in it: state 2 + * to 7 before the interrupt returns (HW §7; the engine stops advertising by itself, model); + * - per event: RX delivery with the software SN check, the event counter, the instants (HW §8, §9); the TX + * service (acknowledgement and refill, HW §8.2) at the end of each connection RX interrupt; the supervision + * timeout is the link layer's (HW §7 step 15). + * + * Interrupts: IRQ 45 (event) and IRQ 29 (RX) at BLE_HW_IRQ_PRIO, below the audio (IRQ 11, 3) and the TIMER5 tick + * (4), as stock (HW §5.5 step 5, §10: priority 2). Both run at one priority, so they never nest in each other, the + * single context ble_hw.h asks for. The engine keeps the radio timing in hardware; software deadlines are long: + * state 7 before the transmit window (>= 1.25 ms after the CONNECT_IND), a TX refill and the instant writes within + * one interval (>= 7.5 ms). An audio half (the audio ISR, docs/BLE-STACK.md §7, "Interrupts") fits inside them, so + * the audio is never delayed by BLE; BLE waits for the audio instead. + * + * What the engine model settled (the agent that wrote it, from stock V15): a repeated SN is dropped by the engine + * (the default) but software checks SN as well, and EVTCOUNT still counts the repeat as a reception; TXBUFnCNTL + * bit0 going back to 1 is the acknowledgement; one packet pair per event by default; the first anchor is the + * CONNECT_IND's end + 1.25 ms + WinOffset; leaving advertising is column 2 going from state 2 to 7; the new + * interval is written in event instant - 1; the time base is the 24-bit link clock (columns 0 / 14); the engine + * fills the RX buffer RXTOG selects whatever RXBUFnCNTL bit0 says; IRQ 29 fires for empty PDUs too. + * What the FM-1 said instead (blell3, 9a90c7d, 2026-10-08): while advertising RXBUFnCNTL stays 00 and the packet is + * in the buffer RXTOG has moved past (hw_adv_find); in a connection RXBUFnCNTL bit0 = 1 does mark the filled buffer + * (470 packets, no desync); and the slot clock read through columns 0 / 14 steps backwards, so the link layer's timers + * run on TIMER4 (ble_hw_time_us). TX follows the vendor's contract, HW §8.2 (bit0 = 1 empty; see hw_tx_service). */ +#include "ble_hw.h" +#include "ble_vm.h" /* the stored trims rf_init takes (ble_vm.c) */ +#include "ble_diag.h" /* console blell: counters only, no behaviour */ +#include "fm1_ble.h" +#include "rf_share.h" /* the radio started once, shared with Bluetooth audio (bt/bt_inq.c) */ + +#ifndef BLE_HW_IRQ_PRIO +#define BLE_HW_IRQ_PRIO 2u /* below the audio (3) and TIMER5 (4): stock's (HW §10) */ +#endif +#define HW_LINK 0u /* one peripheral link: link 0 (HW §2.3, §3) */ +#define HW_RXBUF 264u /* RX payload room: advertising 263, connection 255 (HW §4) */ +#define HW_TXBUF 256u /* TX payload room: 251 + a 4-octet MIC */ +#define HW_SWHDR 20u /* the software header before each payload (HW §4) */ +#define HW_WIN_NORMAL 50u /* WINCNTL2, the normal receive window in us (HW §3 0x112, §6 step 1) */ + +/* ---- the control block (HW §3: offsets [M:s]/[M:d], meanings as tagged there) */ +struct ble_cb { + volatile uint16_t anchor; /* 0x000 bit15 set at connection, low bits dead time (4 on 1M) */ + volatile uint16_t bitoff; /* 0x002 */ + volatile uint16_t advidx; /* 0x004 [15:14] PDUs per advertising event, [13:0] their spacing in us */ + volatile uint16_t format; /* 0x006 bit2 advertising, bit3 local address programmed, bit8 ignore SCAN_REQ */ + volatile uint16_t optcntl; /* 0x008 bit4 local-address match disable */ + volatile uint16_t bdaddr[2]; /* 0x00A access address */ + volatile uint16_t txtog; /* 0x00E bit0 the engine's TX buffer (moved by it only) */ + volatile uint16_t rxtog; /* 0x010 bit0 the RX buffer filled next (engine) */ + volatile uint16_t txptr[2]; /* 0x012 TX payload offsets in the block */ + volatile uint16_t txahdr[2]; /* 0x016 advertising header: [3:0] type, bit4 TxAdd, bit5 RxAdd */ + volatile uint16_t txdhdr[2]; /* 0x01A [1:0] LLID, bit2 SN (engine's), bit3 MD, [15:8] length */ + volatile uint16_t rxptr[2]; /* 0x01E RX payload offsets */ + volatile uint16_t wincntl[2]; /* 0x022 receive window, us, low / high */ + volatile uint16_t rxahdr[2]; /* 0x026 received advertising header (Core layout) */ + volatile uint16_t rxdhdr[2]; /* 0x02A [1:0] LLID, bit2 NESN, bit3 SN, bit4 MD, [15:8] length */ + volatile uint16_t chmap[3]; /* 0x02E map bits 0-36, CHMAP2 [15:5] used channels */ + volatile uint16_t lastchmap; /* 0x034 */ + volatile uint16_t rxmaxbuf; /* 0x036 */ + volatile uint16_t rxstat[2]; /* 0x038 [3:0] = 1 good; bit8 the peer acknowledged our last */ + volatile uint16_t filtercntl; /* 0x03C */ + volatile uint16_t whitelist[3]; /* 0x03E */ + volatile uint16_t crcword[2]; /* 0x044 CRC init [15:0], [23:16] */ + volatile uint16_t widen[2]; /* 0x048 whole slots; 0x5000 | us mod 625 */ + volatile uint16_t targetadr[3]; /* 0x04C */ + volatile uint16_t localadr[3]; /* 0x052 */ + volatile uint16_t evtcount; /* 0x058 event counter of the last reception (engine) */ + volatile uint16_t rxbit; /* 0x05A */ + volatile uint16_t ifscnt; /* 0x05C */ + volatile uint16_t rfpriostat; /* 0x05E */ + volatile uint16_t rfpriocntl; /* 0x060 */ + volatile uint16_t intframe; /* 0x062 bits 1, 2 at init; [5:4] 01 connected; bit6 MD of the TX PDU */ + volatile uint8_t txbufcntl[2]; /* 0x064 bit0: 1 empty / finished, 0 handed to the engine (HW §8.2) */ + volatile uint8_t rxbufcntl[2]; /* 0x066 bit0: 1 filled by the engine, 0 armed */ + volatile uint8_t frq_idx0[40]; /* 0x068 */ + volatile uint8_t frq_idx1[40]; /* 0x090 used data channels packed, then 37-39 */ + volatile uint8_t frq_tbl0[40]; /* 0x0B8 MHz - 2402 of channel index i */ + volatile uint8_t frq_tbl1[40]; /* 0x0E0 */ + volatile uint16_t ext[5]; /* 0x108 */ + volatile uint16_t wincntl2; /* 0x112 */ + volatile uint16_t ext2[3]; /* 0x114 */ + volatile uint16_t unused[3]; /* 0x11A */ + volatile uint32_t tx_pwer; /* 0x120 level + 16 */ + volatile uint32_t rx_gain0; /* 0x124 */ + volatile uint32_t tx_set; /* 0x128 */ + volatile uint32_t rx_set; /* 0x12C */ + volatile uint32_t pll_comp; /* 0x130 */ + volatile uint32_t mdm_set; /* 0x134 */ + volatile uint16_t rssi[4]; /* 0x138 */ + volatile uint32_t anl_out; /* 0x140 */ +}; +_Static_assert(sizeof(struct ble_cb) == 324u, "HW §3: the control block is 324 bytes"); +_Static_assert(__builtin_offsetof(struct ble_cb, evtcount) == 0x58u, "HW §3 EVTCOUNT"); +_Static_assert(__builtin_offsetof(struct ble_cb, txbufcntl) == 0x64u, "HW §3 TXBUF0CNTL"); +_Static_assert(__builtin_offsetof(struct ble_cb, wincntl2) == 0x112u, "HW §3 WINCNTL2"); +_Static_assert(__builtin_offsetof(struct ble_cb, tx_pwer) == 0x120u, "HW §3 TX_PWER"); + +/* ---- the baseband RAM block (HW §4): everything the engine reaches, at 16-bit offsets from its base */ +struct ble_bb { + volatile uint16_t inst[8]; /* 0x000 instance table: 0x8000 | link n's control block offset */ + uint8_t sw[0x30]; /* 0x010 software area (unused) */ + struct ble_cb cb; /* 0x040 link 0 */ + struct { uint8_t buf[HW_SWHDR + HW_RXBUF]; } rx[2]; /* buf[18..19]: the PDU header for ble_ll_hw_rx */ + struct { uint8_t buf[HW_SWHDR + HW_TXBUF]; } tx[2]; /* buf[18..19]: the header ble_ll_hw_tx writes */ +}; +_Static_assert(__builtin_offsetof(struct ble_bb, cb) == 0x40u, "HW §4: link 0's block at +0x40, as stock"); +static struct ble_bb bb __attribute__((aligned(4))); + +#define BB_OFF(p) ((uint16_t)((uintptr_t)(p) - (uintptr_t)&bb)) /* an engine offset (HW §3: below 65,535) */ +#define CB (&bb.cb) + +enum { HW_OFF, HW_ADV, HW_CONN, HW_SCAN, HW_INIT }; +enum { UPD_CONN = 1, UPD_CHM = 2 }; + +static struct { + uint8_t state, gen; /* gen: moves on every state change (a callback may stop / restart the link) */ + uint8_t rx_next, rx_sn, rx_seen, rx_any; + uint8_t win_wide, upd, sca; + uint16_t interval, last_evt, wide_from, upd_instant, chm_instant; + struct ble_hw_conn_upd u; + uint8_t chm[5]; + struct ble_hw_adv adv; /* the advertising set (the link layer's PDUs stay where they are) */ + uint8_t t_conn; /* t_us was taken in a connection (clk_step_max) */ + uint8_t tx_rec[2]; /* a PDU of ours recorded in TX buffer b (handed over, not yet finished) */ + uint8_t tx_md[2]; /* its MD bit */ + uint16_t tx_at[2]; /* the event it was loaded in (tx_ack_evt_max) */ + uint32_t t_us; /* the last ble_hw_time_us */ +#if BLE_CENTRAL + uint8_t scan_ch, scan_active; /* scanning: the channel the next event programs (HW §21.2), SCAN_REQ on */ + uint8_t bo_count, bo_sent, bo_succ, bo_fail; /* the active-scan backoff (Core Vol 6 Part B 4.4.3.2) */ + uint16_t bo_upper; + uint32_t scan_evts; + /* initiating (state 3) and the master (state 6, HW §21.3 / §21.4) */ + uint8_t master; /* the connection is ours (state 6) */ + uint8_t init_hit, init_own_rand, init_peer_rand; /* the target's ADV_IND seen: switch at the next event IRQ */ + uint8_t init_own[6], init_peer[6]; + uint32_t init_t_hit; /* (diagnostics: its RX IRQ, ticks) */ + uint32_t init_t0; /* the engine listening for the target from here (ticks): ble_hw_init_start */ + struct ble_hw_conn ic; /* our CONNECT_IND's LLData */ +#endif +} drv; + +/* counters for the console and the emulator test (read-only for the rest of the firmware) */ +struct ble_hw_stats { + uint32_t events, rx, rx_repeat, rx_error, tx, acked, connects, late_instant, isr_max_ticks; +}; +static struct ble_hw_stats ble_hw_stat; + +/* ------------------------------------------------------------------------------- diagnostics (blell) --- */ + +static struct { + uint32_t base, us; /* TIMER4 ticks already counted, microseconds since the radio first started */ + uint32_t isr_t0, conn_t0; /* this ISR's entry, state 7 written (ticks) */ + uint8_t first_rx, c3_seen; /* per connection: first RX IRQ / first zero column 3 recorded */ +} hwd; + +/* microseconds since the first BLUETOOTH ON (ble_hw_wl82_start), from TIMER4 (24 MHz, wraps in 179 s: called at every + * BLE interrupt, at least every advertising interval while the radio runs) */ +BLE_API uint32_t ble_hw_diag_now(void) +{ + uint32_t d = (fm1_ticks() - hwd.base) / FM1_TICKS_PER_US; + hwd.base += d * FM1_TICKS_PER_US; + hwd.us += d; + return hwd.us; +} + +/* Stopping link 0 (HW §2.1 0x28038 bit1, §21.2 "Stop"): column 14 = 0, its interrupts off, then wait until the engine is + * idle before anything programs the link again. On the FM-1 (blell-dev3 / dev4, 2026-10-09) bit1 was still set 2,000 + * polls (~0.75 ms) after every stop of a scanning link: the scan window that was open goes on to its end [I], so the + * stops the main loop makes (advertising, scanning, initiating: ble_ll_scan, ble_ll_connect, ble_ll_enable) wait up to + * a whole scanning window; a connection's stop (its end, in the BLE interrupts) up to one event; a link opened right + * after a stop of ours finds it idle. Measured per path for `blell` (stop_*, busy_max in us, busy_timeouts). */ +#define HW_STOP_WAIT_US ((uint32_t)BLE_SCAN_WINDOW * 625u + 2500u) /* 40 ms: a scanning / initiating window */ +#define HW_STOP_CONN_US 3000u /* a connection event (the master's ended with its last packet) */ +#define HW_STOP_OPEN_US 200u /* hw_link_open: the stop before it waited already */ + +static void hw_stop(uint8_t path, uint32_t max_us) +{ + uint32_t us; + fm1_ble_bc.stop = 0x5D000000u | (uint32_t)path << 16; /* the breadcrumb: waiting (a watchdog reset keeps it) */ + us = fm1_ble_link_stop(HW_LINK, max_us); + fm1_ble_bc.stop = 0x5E000000u | (uint32_t)path << 16 | (us > 0xFFFFu ? 0xFFFFu : us); +#if BLE_DIAG + uint16_t u16 = (uint16_t)(us > 0xFFFFu ? 0xFFFFu : us); + ble_dg.stop_n[path]++; + ble_dg.stop_last = path; + if (us) + ble_dg.stop_busy[path]++; + if (u16 > ble_dg.stop_us_max[path]) + ble_dg.stop_us_max[path] = u16; + if (u16 > ble_dg.busy_max) + ble_dg.busy_max = u16; +#endif + if (us >= max_us) + BLE_DG(ble_dg.busy_timeouts++); + if (us >= 50u || us >= max_us) /* "busy " in the ring */ + ble_diag_ev(BDE_BUSY, (uint32_t)path << 13 | (us >> 3 > 0x1FFFu ? 0x1FFFu : us >> 3)); +} + +static void hw_cpy(uint8_t *d, const uint8_t *s, uint32_t n) +{ + while (n--) + *d++ = *s++; +} + +/* ------------------------------------------------------------------------------------------- time base --- */ + +/* The link layer's timers (supervision, the 40 s procedure timeout, the establishment rule): TIMER4 microseconds, + * monotonic (ble_hw_diag_now), not the engine's slot clock. On the FM-1 (blell3, 9a90c7d, 2026-10-08) the slot clock + * read through columns 0 / 14 (op 2) stepped BACKWARDS inside a connection: clk_step_max 16777215, and + * close_since_start_us 1,895,854,158 = (2^24 - k) x 625 mod 2^32 + the real time, i.e. a step back of k ~ 267 slots + * read as a jump of ~10,486 s forward, so the LL response timeout (0x22, 40 s) fired 0.2-2.1 s into every connection + * with a feature exchange pending. TIMER4 is read with a plain load (no column op), so the ISRs also issue three + * column reads fewer per call. The engine keeps its anchors on its own clock. clk_step_max now holds the largest step + * of this clock between two calls in a connection (us; a sanity check: about one interval). */ +BLE_API uint32_t ble_hw_time_us(void) +{ + uint32_t t = ble_hw_diag_now(); +#if BLE_DIAG + uint32_t step = t - drv.t_us; + if (drv.state == HW_CONN && drv.t_conn && step > ble_dg.clk_step_max) + ble_dg.clk_step_max = step; +#endif + drv.t_us = t; + drv.t_conn = drv.state == HW_CONN; + return t; +} + +BLE_API void ble_hw_rand(uint8_t *out, uint8_t n) +{ + while (n) { + uint32_t r = fm1_ble_rng32(), k; + for (k = 0; k < 4u && n; k++, n--, r >>= 8) + *out++ = (uint8_t)r; + } +} + +/* VM id 104 (HW §11): a provisioned BLE address, public. The VM can be read now (ble_vm.c, HW §14), but stock V15 + * writes no 104 and a hand-made one changed nothing (HW §14.5): always "absent", and the caller gets a fresh random + * static address (the firmware keeps it in its settings: midi_ble.c). */ +static int hw_vm_addr(uint8_t addr[6]) +{ + (void)addr; + return 0; +} + +BLE_API uint8_t ble_hw_addr(uint8_t addr[6]) +{ + uint32_t a, b; + if (hw_vm_addr(addr)) + return 0; + do { + a = fm1_ble_rng32(); + b = fm1_ble_rng32() & 0xFFFFu; + } while ((a == 0 && (b & 0x3FFFu) == 0) || (a == 0xFFFFFFFFu && (b & 0x3FFFu) == 0x3FFFu)); + b |= 0xC000u; /* random static: the top two bits 11, the rest not all 0 / 1 (Core Vol 6 + * Part B 1.3.2.1) */ + addr[0] = (uint8_t)a; + addr[1] = (uint8_t)(a >> 8); + addr[2] = (uint8_t)(a >> 16); + addr[3] = (uint8_t)(a >> 24); + addr[4] = (uint8_t)b; + addr[5] = (uint8_t)(b >> 8); + return 1; +} + +/* ------------------------------------------------------------------------------------- control block --- */ + +static void cb_rfprio(uint16_t p) /* "RFPRIO n" (HW §6, §7, §9): both words, as stock's dump shows */ +{ + CB->rfpriostat = p; + CB->rfpriocntl = p; +} + +/* the channel tables for map m (HW §6 end, §9): FRQ_IDX0/TBL0 every index, FRQ_IDX1/TBL1 the used data channels + * packed then 37-39 at their own places, CHMAP0/1/2 the map and the used count */ +static uint8_t hw_freq(uint32_t i) /* MHz - 2402 of channel index i (HW §3 0x0B8) */ +{ + if (i == 37u) + return 0; + if (i == 38u) + return 24u; + if (i == 39u) + return 78u; + return (uint8_t)(i <= 10u ? 2u * (i + 1u) : 2u * (i + 1u) + 2u); +} + +static void cb_channels(const uint8_t chm[5]) +{ + uint32_t i, used = 0; + for (i = 0; i < 40u; i++) { + CB->frq_idx0[i] = (uint8_t)i; + CB->frq_tbl0[i] = hw_freq(i); + } + for (i = 0; i < 37u; i++) + if (chm[i >> 3] >> (i & 7u) & 1u) { + CB->frq_idx1[used] = (uint8_t)i; + CB->frq_tbl1[used] = hw_freq(i); + used++; + } + for (i = used; i < 40u; i++) { + CB->frq_idx1[i] = (uint8_t)(i >= 37u ? i : 0u); + CB->frq_tbl1[i] = i >= 37u ? hw_freq(i) : 0u; + } + CB->chmap[0] = (uint16_t)(chm[0] | chm[1] << 8); + CB->chmap[1] = (uint16_t)(chm[2] | chm[3] << 8); + CB->chmap[2] = (uint16_t)((chm[4] & 0x1Fu) | used << 5); +} + +/* window widening, us (HW §7): 2 + 2 x floor(interval_us x (SCA ppm + 200) x (latency + 1) / 10^6), latency 0 */ +static uint32_t hw_widening(uint16_t interval, uint8_t sca) +{ + static const uint16_t PPM[8] = {500, 250, 150, 100, 75, 50, 30, 20}; /* Core Vol 6 Part B 2.3.3.1 */ + return 2u + 2u * ((uint32_t)interval * 1250u * (PPM[sca & 7u] + 200u) / 1000000u); +} + +static void cb_widen(uint32_t us) /* HW §7 step 10 */ +{ + CB->widen[0] = (uint16_t)(us / 625u); + CB->widen[1] = (uint16_t)(0x5000u | us % 625u); +} + +static void cb_window(uint32_t us) /* WINCNTL0/1 (HW §3, §7 step 13) */ +{ + CB->wincntl[0] = (uint16_t)us; + CB->wincntl[1] = (uint16_t)(us >> 16); +} + +/* a link opened (HW §5.5 end): every column 0, column 14 again, interrupts off; the block as stock initialises it */ +static void hw_link_open(void) +{ + static const uint8_t ALL[5] = {0xFF, 0xFF, 0xFF, 0xFF, 0x1F}; + uint32_t c; + uint8_t *p = (uint8_t *)&bb.sw; + fm1_ble_step(FM1_BLE_STEP_LINK_STOP); + hw_stop(BDS_OPEN, HW_STOP_OPEN_US); + fm1_ble_step(FM1_BLE_STEP_LINK_OPEN); + for (c = 0; c <= 16u; c++) + fm1_ble_col_wr(HW_LINK, c, 0); + fm1_ble_col_wr(HW_LINK, 14, 0); + for (c = 0; c < sizeof bb.sw; c++) + p[c] = 0; + { /* the control block from zero (plain stores: the link is stopped) */ + volatile uint8_t *q = (volatile uint8_t *)&bb.cb; + for (c = 0; c < sizeof bb.cb; c++) + q[c] = 0; + } + bb.inst[HW_LINK] = (uint16_t)(0x8000u | BB_OFF(CB)); /* HW §4 instance table */ + CB->anchor = 0; /* HW §5.5 list [M:s] */ + CB->bitoff = 0; + CB->advidx = 0xD388u; + CB->widen[0] = 0; + CB->widen[1] = 0x51E7u; + CB->bdaddr[0] = 0xBED6u; /* the advertising access address 0x8E89BED6 */ + CB->bdaddr[1] = 0x8E89u; + CB->crcword[0] = 0x5555u; + CB->crcword[1] = 0x0055u; + CB->optcntl = 0x28u; + CB->optcntl |= 0x200u; + CB->txptr[0] = BB_OFF(bb.tx[0].buf + HW_SWHDR); /* (stock: placeholder 1 until advertising) */ + CB->txptr[1] = BB_OFF(bb.tx[1].buf + HW_SWHDR); + CB->intframe |= 2u; + CB->intframe |= 4u; + CB->rxbufcntl[0] &= (uint8_t)~1u; + CB->rxbufcntl[1] &= (uint8_t)~1u; + CB->tx_pwer = 0x16u; /* level 6 + 16, as stock (U10: dBm unknown) */ + CB->tx_set = 0x16u; + CB->pll_comp = 0; /* TODO(hardware) HW §3 0x130: -(offset x 2^20) / 24,000 + * from VM 110 (format unknown, U3 / U14) */ + CB->rfpriocntl = 0x101u; + CB->rfpriostat = 1u; + CB->txtog = 0; + CB->rxtog = 0; + CB->txahdr[0] = CB->txahdr[1] = 0; + CB->txdhdr[0] = CB->txdhdr[1] = 1u; + CB->rxmaxbuf = 255u; + CB->ifscnt = 0x8295u; + CB->filtercntl = 0; + cb_channels(ALL); +} + +/* ---------------------------------------------------------------------------------------- advertising --- */ + +#define HW_RX_WIPE 40u /* bytes zeroed from 2 before RXPTR: header + the 34-octet CONNECT_IND + 4 */ + +/* an advertising RX buffer zeroed with its RXAHDR / RXDHDR / RXSTAT (hw_adv_find: a new packet from an old one) */ +static void hw_rx_wipe(uint32_t b) +{ + uint8_t *p = &bb.rx[b].buf[HW_SWHDR - 2u]; + uint32_t i; + for (i = 0; i < HW_RX_WIPE; i++) + p[i] = 0; + CB->rxahdr[b] = 0; + CB->rxdhdr[b] = 0; + CB->rxstat[b] = 0; +} + + +static void hw_adv_buffer(uint32_t b, const uint8_t *pdu, uint8_t len) /* HW §6 step 8 */ +{ + uint8_t n = (uint8_t)(len - 2u); + hw_cpy(bb.tx[b].buf + HW_SWHDR, pdu + 2, n); + CB->txahdr[b] = (uint16_t)((pdu[0] & 0x0Fu) | ((pdu[0] >> 6) & 3u) << 4); /* TxAdd / RxAdd: Core bits 6 / 7 -> 4 / 5 */ + CB->txdhdr[b] = (uint16_t)(n << 8); +} + +static void hw_adv_program(void) +{ + const struct ble_hw_adv *a = &drv.adv; + const uint8_t *adva = a->adv + 2; + hw_link_open(); + fm1_ble_step(FM1_BLE_STEP_ADV_PROG); + cb_rfprio(26u); /* HW §6 step 1 */ + CB->crcword[0] = 0x5555u; + CB->crcword[1] = 0x0055u; + cb_window(HW_WIN_NORMAL); + CB->wincntl2 = HW_WIN_NORMAL; + fm1_ble_col_wr(HW_LINK, 1, a->interval); /* step 2: interval, event enable */ + fm1_ble_col_wr(HW_LINK, 15, 0x8000u | (uint32_t)a->interval >> 16); + CB->filtercntl = 0; /* step 3: policy 0 */ + CB->advidx = (uint16_t)(3u << 14 | 1250u); /* step 4: 3 PDUs, 1,250 us apart */ + fm1_ble_col_wr(HW_LINK, 8, 0xC000u); /* step 5: advDelay on */ + /* step 6: 37 first, step 1, all three. Bits 6 / 7 come from the channel mask (U15): only stock's value for all + * three channels is known, so a.channels other than 7 still advertises on all three */ + fm1_ble_col_wr(HW_LINK, 6, 0x41A5u); + CB->rxptr[0] = BB_OFF(bb.rx[0].buf + HW_SWHDR); /* step 7: two RX buffers armed */ + CB->rxptr[1] = BB_OFF(bb.rx[1].buf + HW_SWHDR); + CB->rxbufcntl[0] &= (uint8_t)~1u; + CB->rxbufcntl[1] &= (uint8_t)~1u; + hw_rx_wipe(0); /* (ours: a new packet tells itself from an old one) */ + hw_rx_wipe(1); + drv.rx_next = 0; + hw_adv_buffer(0, a->adv, a->adv_len); /* step 8: ADV_IND, SCAN_RSP */ + hw_adv_buffer(1, a->scan_rsp, a->scan_rsp_len); + CB->txtog = 0; + CB->optcntl &= (uint16_t)~0x10u; /* step 9: local-address match on */ + CB->localadr[0] = (uint16_t)(adva[0] | adva[1] << 8); + CB->localadr[1] = (uint16_t)(adva[2] | adva[3] << 8); + CB->localadr[2] = (uint16_t)(adva[4] | adva[5] << 8); + CB->format = 0x000Cu; + fm1_ble_sync(); + fm1_ble_col_wr(HW_LINK, 2, 0x2000u); /* step 10: state 2 */ + fm1_ble_link_irqs_on(HW_LINK); /* step 11 */ + fm1_ble_col_wr(HW_LINK, 7, 0); /* step 12: start (column 0 = start slot - 1 = 0) */ + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0); + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0x8000u); + drv.state = HW_ADV; + drv.gen++; + fm1_ble_step(FM1_BLE_STEP_ADV_STARTED); + BLE_DG(ble_dg.adv_starts++); /* (no column read here: see below) */ + ble_diag_ev(BDE_ADV_START, a->interval); + /* 1f0ab85 read columns 2, 14, 15 (op 2) right here, the command port's next command straight after the start + * (column 14 = 0x8000): the first BLUETOOTH ON from the menu then hung the FM-1 until its watchdog reset it + * (2026-10-08, prev_stage 9, prev_rst 0x04), where 1cc6e04 without the reads advertised. Op 2 is known from + * static analysis only (HW §2.1, never traced), so the start path and the interrupts issue no column read that + * 1cc6e04 did not; `blell regs` reads them on request. */ +} + +BLE_API void ble_hw_adv_start(const struct ble_hw_adv *a) +{ + drv.adv = *a; + hw_adv_program(); +} + +BLE_API void ble_hw_adv_stop(void) +{ + hw_stop(drv.state == HW_CONN ? BDS_CONN : BDS_ADV, drv.state == HW_CONN ? HW_STOP_CONN_US : HW_STOP_WAIT_US); + ble_diag_ev(BDE_ADV_STOP, drv.state); + drv.state = HW_OFF; + drv.gen++; +} + +#if BLE_CENTRAL +#include "ble_hw_wl82_central.c" /* scanning, initiating, the master's set-up (HW §21) */ +#endif + +/* ----------------------------------------------------------------------------------------- connection --- */ + +/* called by the link layer from inside ble_ll_hw_connect_ind (the RX interrupt), HW §7 in the vendor's order */ +BLE_API void ble_hw_conn_start(const struct ble_hw_conn *c) +{ + uint16_t h0; + cb_rfprio(28u); /* 1 */ + CB->anchor = 0x8000u; + CB->txtog &= (uint16_t)~2u; + CB->rxtog = 0; + CB->bdaddr[0] = (uint16_t)c->aa; /* 2 */ + CB->bdaddr[1] = (uint16_t)(c->aa >> 16); + CB->crcword[0] = (uint16_t)c->crc_init; + CB->crcword[1] = (uint16_t)(c->crc_init >> 16 & 0xFFu); + CB->optcntl |= 4u; /* 3 */ + CB->optcntl &= (uint16_t)~0x200u; + CB->optcntl |= 0xC00u; + CB->optcntl |= 0x1000u; + CB->intframe = (uint16_t)((CB->intframe & ~0x30u) | 0x10u); /* 4 */ + CB->txbufcntl[0] |= 1u; /* 5: both TX buffers empty (bit0 = 1: the only 1-writes) */ + CB->txbufcntl[1] |= 1u; + CB->anchor = (uint16_t)((CB->anchor & 0x8000u) | 4u); /* 6: 1M dead time */ + fm1_ble_col_wr(HW_LINK, 5, 0); /* 7: no instant */ + fm1_ble_col_wr(HW_LINK, 4, c->win_offset ? 0x8000u | (2u * c->win_offset - 1u) : 0u); /* 8 */ + fm1_ble_col_wr(HW_LINK, 2, 7u << 12); /* 9: state 7, latency 0 (we listen every event) */ + cb_widen(hw_widening(c->interval, c->sca)); /* 10 */ + fm1_ble_col_wr(HW_LINK, 8, 0); /* 11: advDelay off */ + fm1_ble_col_wr(HW_LINK, 3, 0); /* 12 */ + CB->evtcount = 0; + cb_window((uint32_t)c->win_size * 1250u + 1250u); /* 13: the first receive window */ + CB->wincntl2 = HW_WIN_NORMAL; + fm1_ble_col_wr(HW_LINK, 1, 2u * c->interval); /* 14 */ + fm1_ble_col_wr(HW_LINK, 15, 0x8000u | (2u * c->interval) >> 16); + cb_channels(c->chm); /* 16 */ + fm1_ble_col_wr(HW_LINK, 6, 0x8000u | (uint32_t)c->hop << 8 | c->hop); + CB->txahdr[0] = CB->txahdr[1] = 0; /* 17: empty PDUs, opposite SN */ + h0 = (uint16_t)((CB->txtog & 1u) << 2 | 1u); + CB->txdhdr[0] = h0; + CB->txdhdr[1] = (uint16_t)(h0 ^ 4u); /* (§7 reads XOR 5: LLID 0 on one; §8.2: LLID 1 on both) */ + /* 18: the TX buffers stay the advertising ones; 19: no channel selection #2 (our ADV_IND has ChSel 0) */ + fm1_ble_sync(); + drv.state = HW_CONN; +#if BLE_CENTRAL + drv.master = 0; +#endif + drv.gen++; + drv.rx_next = 0; + drv.rx_sn = 0; + drv.rx_seen = drv.rx_any = 0; + drv.tx_rec[0] = drv.tx_rec[1] = 0; /* no PDU recorded in either buffer (HW §8.2 point 7) */ + drv.tx_md[0] = drv.tx_md[1] = 0; + drv.upd = 0; + drv.win_wide = 1; + drv.wide_from = 0; + drv.interval = c->interval; + drv.sca = c->sca; + drv.last_evt = 0xFFFFu; + ble_hw_stat.connects++; + hwd.conn_t0 = fm1_ticks(); /* (diagnostics: after the engine has state 7) */ + hwd.first_rx = hwd.c3_seen = 0; + BLE_DG(ble_dg.cind_isr_us = (hwd.conn_t0 - hwd.isr_t0) / FM1_TICKS_PER_US); + BLE_DG(ble_dg.first_rx_us = 0); + BLE_DG(ble_dg.first_rx_evt = ble_dg.first_evt = 0xFFFFu); + BLE_DG(ble_diag_ev(BDE_CONN_SET, ble_dg.cind_isr_us)); +} + +BLE_API void ble_hw_conn_stop(void) +{ + ble_hw_adv_stop(); /* column 14 = 0: the link stops (HW §2.3) */ +} + +BLE_API void ble_hw_conn_update(const struct ble_hw_conn_upd *u) +{ + drv.u = *u; + drv.upd_instant = u->instant; + drv.upd |= UPD_CONN; + fm1_ble_col_wr(HW_LINK, 5, u->instant); /* HW §9: column 5 = instant at once */ + cb_rfprio(30u); +} + +BLE_API void ble_hw_chmap_update(const uint8_t chm[5], uint16_t instant) +{ + hw_cpy(drv.chm, chm, 5); + drv.chm_instant = instant; + drv.upd |= UPD_CHM; + fm1_ble_col_wr(HW_LINK, 5, instant); + cb_rfprio(30u); +} + +/* the data length: RXMAXBUF stays 255 (HW §3), the TX buffers hold 255; nothing to program. Whether the engine + * times 251-octet PDUs is open (docs/BLE-STACK.md §12); stock never uses DLE (model) */ +BLE_API void ble_hw_set_lengths(uint8_t max_tx, uint8_t max_rx) +{ + (void)max_tx; + (void)max_rx; +} + +/* from the link layer, always inside one of our interrupts: the next connection RX interrupt loads it (HW §8.2: the + * service never runs from the event interrupt, and the RX interrupt's ends with it) */ +BLE_API void ble_hw_tx_kick(void) {} + +/* ------------------------------------------------------------------------------------ event servicing --- */ + +/* ---- TX: the vendor's contract, docs/BLE-HW-FACTS.md §8.2 (a3b2f06). TXBUFnCNTL bit0 is the buffer's "empty" flag: + * 1 = empty (software may fill it; a PDU software had put there is finished: acknowledged), 0 = handed to the engine. + * conn_start sets both to 1 (HW §7 step 5) and software never sets bit0 again; it clears bit0 as the last write of a + * load. The engine sends from the buffer TXTOG bit0 names and moves TXTOG itself; it sets bit0 back to 1 when it is + * done with the PDU. Software never writes TXTOG, never changes TXDHDR bit2 (the set-up value, the engine's), never + * moves a PDU between the buffers and never frees a buffer the engine holds; the only acknowledgement is bit0 back to 1 + * on a buffer we loaded. The service runs at the end of every connection RX interrupt, after the RX buffers (never + * from the event interrupt): a consistent snapshot of TXTOG bit0 and both bit0s, then the TXTOG buffer, then the other. + * Earlier drivers (5008663 .. 51792b7) had the polarity backwards (1 = loaded), hence blell4-9's stalls (§8.2 point 6). + * RAM only (blell txs_*). */ +#if BLE_DIAG +static void hw_tx_snap(uint8_t what, uint32_t b, uint32_t s) +{ + struct ble_diag_txs *x = &ble_dg.txs[ble_dg.txs_n++ & (BLE_DIAG_TXS - 1u)]; + x->t_us = ble_hw_diag_now(); + x->evt = drv.last_evt; + x->txtog = CB->txtog; + x->txdhdr[0] = CB->txdhdr[0]; + x->txdhdr[1] = CB->txdhdr[1]; + x->intframe = CB->intframe; + x->txptr[0] = CB->txptr[0]; + x->txptr[1] = CB->txptr[1]; + x->rxdhdr = CB->rxdhdr[(CB->rxtog & 1u) ^ 1u]; /* the central's last header: its NESN (bit2) / SN (bit3) */ + x->cntl[0] = CB->txbufcntl[0]; + x->cntl[1] = CB->txbufcntl[1]; + x->what = what; + x->b = (uint8_t)b; + x->n = (uint8_t)(drv.tx_rec[0] | drv.tx_rec[1] << 1); + x->snap = (uint8_t)s; + if (what == BTX_LOAD && !ble_dg.txs_first.what) + ble_dg.txs_first = *x; +} +#else +#define hw_tx_snap(what, b, s) ((void)(s)) +#endif + +/* bit0 TXTOG bit0, bit1 TXBUF0CNTL bit0, bit2 TXBUF1CNTL bit0 */ +static uint32_t hw_tx_read(void) +{ + return (CB->txtog & 1u) | (CB->txbufcntl[0] & 1u) << 1 | (CB->txbufcntl[1] & 1u) << 2; +} + +/* buffer b reads empty: our PDU in it is acknowledged; then the next PDU (control first: ble_ll_hw_tx) goes in. + * 0: the link went with the acknowledgement (our LL_TERMINATE_IND) */ +static int hw_tx_empty(uint32_t b, uint32_t s) +{ + uint8_t g = drv.gen, n, md, *pdu; + if (drv.tx_rec[b]) { + drv.tx_rec[b] = 0; +#if BLE_DIAG + uint16_t age = (uint16_t)(drv.last_evt - drv.tx_at[b]); + if (age != 0xFFFFu && age > ble_dg.tx_ack_evt_max) + ble_dg.tx_ack_evt_max = age; +#endif + hw_tx_snap(BTX_ACK, b, s); + ble_hw_stat.acked++; + BLE_DG(ble_dg.tx_acked++); + ble_ll_hw_tx_acked(); + if (drv.gen != g || drv.state != HW_CONN) + return 0; + } + pdu = &bb.tx[b].buf[HW_SWHDR - 2u]; + n = ble_ll_hw_tx(pdu); + if (!n) { + CB->intframe &= (uint16_t)~0x40u; /* nothing queued: bit0 stays 1, the engine sends empty */ + BLE_DG(ble_dg.tx_none++); + return 1; + } + md = (uint8_t)(pdu[0] >> 4 & 1u); /* the link layer's MD: another PDU still queued */ + CB->txahdr[b] = 0; + CB->txdhdr[b] = (uint16_t)((CB->txdhdr[b] & 4u) | (uint32_t)pdu[1] << 8 | (uint32_t)md << 3 | (pdu[0] & 3u)); + CB->intframe = (uint16_t)((CB->intframe & ~0x40u) | (uint32_t)md << 6); + RING_PUBLISH(); + fm1_ble_sync(); /* payload and header in SRAM before the hand-over */ + CB->txbufcntl[b] &= (uint8_t)~1u; /* the last write: the engine's now */ + drv.tx_rec[b] = 1; + drv.tx_md[b] = md; + drv.tx_at[b] = drv.last_evt; + ble_hw_stat.tx++; + BLE_DG(ble_dg.tx_queued++); + hw_tx_snap(BTX_LOAD, b, s); + return 1; +} + +/* buffer b is the engine's: untouched, except MD on our own PDU in it when more has been queued since */ +static void hw_tx_held(uint32_t b) +{ + if (!drv.tx_rec[b]) { + BLE_DG(ble_dg.tx_eng_held++); /* bit0 0 with nothing of ours (seen at the first event) */ + return; + } + if (!drv.tx_md[b] && ble_ll_hw_tx_pending()) { + drv.tx_md[b] = 1; + CB->txdhdr[b] = (uint16_t)(CB->txdhdr[b] | 8u); /* (bit2 and the rest as they are) */ + } +} + +static void hw_tx_service(void) +{ + uint32_t s1, s2, s, t, k; + if (drv.state != HW_CONN) + return; + s1 = hw_tx_read(); + s2 = hw_tx_read(); + s = ((s1 ^ s2) & 1u) ? s2 : s1; /* TXTOG moved between the reads: the second */ + t = s & 1u; + for (k = 0; k < 2u; k++) { + uint32_t b = t ^ k; + if (s >> (1u + b) & 1u) { + if (!hw_tx_empty(b, s)) + return; + } else + hw_tx_held(b); + } +} + +/* ---- RX while advertising. On the FM-1 (510e616, 2026-10-08) every RX IRQ while a Mac scanned and connected found + * RXBUFnCNTL bit0 = 0 on rx_next and on the other buffer (rx_irqs 14, rx_nothing 14): the engine's RX semantics are + * not the model's. HW §3 marks RXTOG and the CNTL direction [I] (U7), and where an advertising PDU's header and length + * go is not in the sheet. So the driver looks for the packet by several rules, in this order, and counts the one that + * found it (blell rxf_*): CNTL bit0 = 1 on rx_next (the model), on the other buffer, then the content alone: a + * SCAN_REQ / CONNECT_IND carries our AdvA at payload offset 6 (Core Vol 6 Part B 2.3.2), so a buffer holding our + * AdvA there (payload at RXPTR, the sheet's layout) or at offset 8 (the 2 header bytes at RXPTR) holds a packet to us. + * To tell a new packet from an old one without CNTL, every RX buffer's first 40 bytes and its RXAHDR / RXDHDR / + * RXSTAT are zeroed when armed. RAM only: no column read (op 2) on this path (see hw_adv_program's note). */ +#define HW_RX_POLL_US 600u /* RX ISR poll for a late fill: a CONNECT_IND is 352 us on air at 1M */ +#define HW_RX_SETTLE_US 400u /* a content-only find this soon after the IRQ waits for the packet's end */ + +struct hw_adv_pdu { + uint8_t *pdu; /* header (2) then payload, as ble_ll_hw_connect_ind takes it */ + uint8_t type, len, layout; +}; + +static int hw_any(const uint8_t *p, uint32_t n) +{ + while (n--) + if (*p++) + return 1; + return 0; +} + +/* a SCAN_REQ (3, 12 octets) or CONNECT_IND (5, 34) to our AdvA in buffer b, in either layout; 0: none */ +static int hw_adv_parse(uint32_t b, struct hw_adv_pdu *o) +{ + uint8_t *p = bb.rx[b].buf + HW_SWHDR; + const uint8_t *adva = drv.adv.adv + 2; + uint8_t t = (uint8_t)(CB->rxahdr[b] & 0x0Fu), n = (uint8_t)(CB->rxdhdr[b] >> 8); + if (hw_any(p, 6) && ble_eq(p + 6, adva, 6)) { /* layout 1: payload at RXPTR (HW §4, the model) */ + o->pdu = p - 2; + o->layout = 1; + if (t != 3u && t != 5u) { /* RXAHDR not written: the type from the length or the + * LLData (AA, CRCInit... never all 0) */ + t = n == 12u ? 3u : n == 34u ? 5u : hw_any(p + 12, 22) ? 5u : 3u; + /* RxAdd (bit7) = our TxAdd; TxAdd (bit6) unknown, 1 assumed (a central's random address) */ + o->pdu[0] = (uint8_t)(t | 0x40u | (drv.adv.adv[0] >> 6 & 1u) << 7); + } else + o->pdu[0] = (uint8_t)CB->rxahdr[b]; + o->type = t; + o->len = t == 3u ? 12u : 34u; + o->pdu[1] = o->len; + return 1; + } + t = (uint8_t)(p[0] & 0x0Fu); /* layout 2: the header bytes at RXPTR */ + if (((t == 3u && p[1] == 12u) || (t == 5u && p[1] == 34u)) && hw_any(p + 2, 6) && ble_eq(p + 8, adva, 6)) { + o->pdu = p; + o->layout = 2; + o->type = t; + o->len = p[1]; + return 1; + } + return 0; +} + +#if BLE_DIAG +static void hw_rx_snap(uint8_t where, uint8_t found, uint8_t layout, uint32_t wait_us) +{ + struct ble_diag_rxs *s = &ble_dg.rxs[ble_dg.rxs_n++ & (BLE_DIAG_RXS - 1u)]; + uint32_t b, i; + s->t_us = ble_hw_diag_now(); + s->rxtog = CB->rxtog; + s->ifscnt = CB->ifscnt; + for (b = 0; b < 2u; b++) { + s->stat[b] = CB->rxstat[b]; + s->ahdr[b] = CB->rxahdr[b]; + s->dhdr[b] = CB->rxdhdr[b]; + s->cntl[b] = CB->rxbufcntl[b]; + for (i = 0; i < 4u; i++) + s->b[b][i] = bb.rx[b].buf[HW_SWHDR + i]; + } + s->where = where; + s->found = found; + s->rx_next = drv.rx_next; + s->layout = layout; + s->wait_us = (uint16_t)(wait_us > 0xFFFFu ? 0xFFFFu : wait_us); + if (found && !ble_dg.rxs_first.found) + ble_dg.rxs_first = *s; +} +#else +#define hw_rx_snap(where, found, layout, wait_us) ((void)(layout)) /* (layout: hw_adv_parse runs as before) */ +#endif + +/* the buffer holding a new advertising-channel PDU, by the rules in this order (*found: BDF_*), else -1. Measured on + * the FM-1 (blell3, 9a90c7d: 54 of 54 finds, rxf_tog_prev 50 + rxf_late 5 by the event ISR's look, cntl 0, layout 0 = + * payload at RXPTR, header in RXAHDR / RXDHDR): the packet is in the buffer RXTOG has moved PAST, and RXBUFnCNTL stays + * 00 while advertising. So that rule goes first; CNTL on rx_next, CNTL on the other buffer and the content of RXTOG's + * own buffer stay as fallbacks, each counted (the emulator's model sets CNTL and also moves RXTOG past the buffer) */ +static int hw_adv_find(uint8_t *found) +{ + struct hw_adv_pdu o; + uint32_t n = drv.rx_next & 1u, prev = (CB->rxtog & 1u) ^ 1u; + if (hw_adv_parse(prev, &o)) { + *found = BDF_TOG_PREV; + return (int)prev; + } + if (CB->rxbufcntl[n] & 1u) { + *found = BDF_CNTL; + return (int)n; + } + if (CB->rxbufcntl[n ^ 1u] & 1u) { + *found = BDF_CNTL_OTHER; + return (int)(n ^ 1u); + } + if (hw_adv_parse(prev ^ 1u, &o)) { + *found = BDF_TOG_CUR; + return (int)(prev ^ 1u); + } + *found = BDF_NONE; + return -1; +} + +/* a CONNECT_IND (or a stored SCAN_REQ) while advertising, in buffer b (HW §7) */ +static void hw_rx_adv(uint32_t b, uint8_t found) +{ + struct hw_adv_pdu o; + uint16_t ah = CB->rxahdr[b], st = CB->rxstat[b]; + uint8_t s = (uint8_t)(st & 0xFu); + int ok = hw_adv_parse(b, &o); + switch (found) { + case BDF_CNTL: BLE_DG(ble_dg.rxf_cntl++); break; + case BDF_CNTL_OTHER: BLE_DG(ble_dg.rxf_cntl_other++); break; + case BDF_TOG_PREV: BLE_DG(ble_dg.rxf_tog_prev++); break; + default: BLE_DG(ble_dg.rxf_tog_cur++); break; + } + if (ok && o.layout == 2u) + BLE_DG(ble_dg.rxl_buf++); + else if (ok) + BLE_DG(ble_dg.rxl_cb++); + else + BLE_DG(ble_dg.rxl_none++); + if (ok && o.layout == 1u && (ah & 0x0Fu) != 3u && (ah & 0x0Fu) != 5u) + BLE_DG(ble_dg.rxh_synth++); + CB->rxbufcntl[b] &= (uint8_t)~1u; /* re-armed: conn_start below does not read RX */ + drv.rx_next = (uint8_t)(b ^ 1u); + BLE_DG(ble_dg.adv_rx++); + if (ok && s == 0u) + BLE_DG(ble_dg.rx_stat_zero++); /* RXSTAT never written: the content decides */ + else if (ok && s != 1u) + BLE_DG(ble_dg.rx_stat_bad_valid++); + if (!ok || (s != 0u && s != 1u) || o.type != 0x5u) { + if (ok && o.type == 0x3u && (s == 0u || s == 1u)) + BLE_DG(ble_dg.scan_req++); /* a stored SCAN_REQ: the engine answered it */ + else { + BLE_DG(ble_dg.adv_drop++); /* not passed on, and advertising not restarted */ + BLE_DG(ble_dg.adv_drop_stat = st); + BLE_DG(ble_dg.adv_drop_hdr = ah); + ble_diag_ev(BDE_ADV_DROP, (uint32_t)(st & 0xFFu) | (uint32_t)(ah & 0xFFu) << 8); + } + hw_rx_wipe(b); + return; + } + CB->rxahdr[b] = CB->rxdhdr[b] = CB->rxstat[b] = 0; /* (the payload is wiped when advertising re-arms) */ + if (!ble_ll_hw_connect_ind(o.pdu, (uint8_t)(o.len + 2u)) && drv.state == HW_ADV) + hw_adv_program(); /* not taken: the engine stopped advertising on it (model), so start again */ +} + +/* RX ISR, advertising: snapshot, look, and when nothing is there yet poll RAM a little (the IRQ may come at the + * access address, before the packet's end); a content-only find waits for the packet's end (HW_RX_SETTLE_US) */ +static void hw_rx_adv_isr(uint32_t t0) +{ + uint8_t g = drv.gen, f; + uint32_t k, w = 0; + int b = hw_adv_find(&f); + hw_rx_snap(0, f, 0, 0); + if (!(CB->rxbufcntl[drv.rx_next & 1u] & 1u)) + BLE_DG(ble_dg.rx_nothing++); /* (the old rule's verdict, kept for comparison) */ + while (b < 0 && (w = (fm1_ticks() - t0) / FM1_TICKS_PER_US) < HW_RX_POLL_US) + b = hw_adv_find(&f); + if (b < 0) { + BLE_DG(ble_dg.rxf_none++); + hw_rx_snap(1, BDF_NONE, 0, w); + return; + } + while (f >= BDF_TOG_PREV && !(CB->rxbufcntl[b] & 1u) && (fm1_ticks() - t0) / FM1_TICKS_PER_US < HW_RX_SETTLE_US) + ; /* content only: let the engine finish the packet */ + if (w) { + struct hw_adv_pdu o; + BLE_DG(ble_dg.rxf_wait++); +#if BLE_DIAG + if (w > ble_dg.rx_wait_us_max) + ble_dg.rx_wait_us_max = w; +#endif + hw_rx_snap(1, f, (uint8_t)(hw_adv_parse((uint32_t)b, &o) ? o.layout : 0u), w); + } + for (k = 0; k < 2u && b >= 0 && drv.state == HW_ADV && drv.gen == g; k++) { + hw_rx_adv((uint32_t)b, f); + if (drv.gen != g || drv.state != HW_ADV) + return; + b = hw_adv_find(&f); + } +} + +/* event ISR, advertising: a packet the RX ISR did not see (an IRQ missed, or filled after its poll) */ +static void hw_rx_adv_late(void) +{ + struct hw_adv_pdu o; + uint8_t g = drv.gen, f; + uint32_t k; + int b = hw_adv_find(&f); + if (b < 0) + return; + hw_rx_snap(2, f, (uint8_t)(hw_adv_parse((uint32_t)b, &o) ? o.layout : 0u), 0); + for (k = 0; k < 2u && b >= 0 && drv.state == HW_ADV && drv.gen == g; k++) { + BLE_DG(ble_dg.rxf_late++); + hw_rx_adv((uint32_t)b, f); + if (drv.gen != g || drv.state != HW_ADV) + return; + b = hw_adv_find(&f); + } +} + +/* new packets in the RX buffers, in the engine's order (HW §8 IRQ 29 steps 2-4) */ +static void hw_rx_service(void) +{ + uint8_t g = drv.gen; + if (drv.state == HW_ADV) { + RING_PUBLISH(); + hw_rx_adv_late(); /* (from the event ISR: the RX ISR takes its own) */ + return; + } + while (drv.state == HW_CONN && (CB->rxbufcntl[drv.rx_next] & 1u)) { + uint32_t b = drv.rx_next; + uint16_t dh, st; + RING_PUBLISH(); + dh = CB->rxdhdr[b]; + st = CB->rxstat[b]; + if ((CB->rxtog & 1u) != b) + BLE_DG(ble_dg.rxc_tog_past++); /* (diagnostics) RXTOG moved past the filled buffer */ + else + BLE_DG(ble_dg.rxc_tog_at++); + drv.rx_next ^= 1u; + drv.rx_seen = drv.rx_any = 1; + if (!hwd.first_rx) { /* (diagnostics) the first packet of this connection */ + hwd.first_rx = 1; + BLE_DG(ble_dg.first_rx_us = (fm1_ticks() - hwd.conn_t0) / FM1_TICKS_PER_US); + BLE_DG(ble_dg.first_rx_evt = CB->evtcount); +#if BLE_CENTRAL && BLE_DIAG + if (drv.master) { /* C5: the master's first anchor reached the peripheral */ + ble_dgc.m_first_rx_us = ble_dg.first_rx_us; + ble_dgc.m_first_rx_evt = CB->evtcount; + } +#endif + ble_diag_ev(BDE_FIRST_RX, st); + } + if ((st & 0xFu) != 1u) { + ble_hw_stat.rx_error++; /* HW §8 step 4: errored, length 0 */ + BLE_DG(ble_dg.rx_crc_bad++); + BLE_DG(ble_dg.rx_bad_stat = st); + BLE_DG(if (ble_dg.rx_crc_bad <= 4u) ble_diag_ev(BDE_RX_BAD, st)); + } else if ((dh >> 3 & 1u) != drv.rx_sn) { + ble_hw_stat.rx_repeat++; /* the central's retransmission: already delivered */ + BLE_DG(ble_dg.rx_repeat++); + } else { + uint8_t *pdu = &bb.rx[b].buf[HW_SWHDR - 2u]; + drv.rx_sn ^= 1u; + ble_hw_stat.rx++; + BLE_DG(ble_dg.rx_good++); + if (!(dh >> 8) && (dh & 3u) == 1u) + BLE_DG(ble_dg.rx_empty++); + pdu[0] = (uint8_t)(dh & 0x1Fu); + pdu[1] = (uint8_t)(dh >> 8); + if (pdu[1] || (pdu[0] & 3u) != 1u) /* empty PDUs are not passed on */ + ble_ll_hw_rx(pdu, (uint8_t)(pdu[1] + 2u)); + if (drv.gen != g) + return; + } + CB->rxbufcntl[b] &= (uint8_t)~1u; /* re-armed (HW §8 step 3) */ + } +} + +/* instant - 1: the new parameters into the engine (HW §9) */ +static void hw_instants(uint16_t counter) +{ + if ((drv.upd & UPD_CHM) && (int16_t)(drv.chm_instant - counter) <= 1) { + if ((int16_t)(drv.chm_instant - counter) < 1) + ble_hw_stat.late_instant++; + cb_channels(drv.chm); + drv.upd &= (uint8_t)~UPD_CHM; + ble_diag_ev(BDE_INSTANT, drv.chm_instant); + } + if ((drv.upd & UPD_CONN) && (int16_t)(drv.upd_instant - counter) <= 1) { + const struct ble_hw_conn_upd *u = &drv.u; + if ((int16_t)(drv.upd_instant - counter) < 1) + ble_hw_stat.late_instant++; +#if BLE_CENTRAL + if (drv.master) { /* HW §21.4: the master's values, no widening; the receive + * window back to 0 / 30 two events after the instant */ + fm1_ble_col_wr(HW_LINK, 4, u->win_offset ? 0x8000u | 2u * u->win_offset : 0u); + cb_window((uint32_t)u->win_size * 1250u + 625u); + CB->wincntl2 = HW_WIN_NORMAL; + fm1_ble_col_wr(HW_LINK, 2, 0x6000u); + fm1_ble_col_wr(HW_LINK, 1, 2u * u->interval); + fm1_ble_col_wr(HW_LINK, 15, 0x8000u | (2u * u->interval) >> 16); + drv.interval = u->interval; + drv.win_wide = 1; + drv.wide_from = (uint16_t)(drv.upd_instant + 2u); + drv.upd &= (uint8_t)~UPD_CONN; + ble_diag_ev(BDE_INSTANT, drv.upd_instant); + return; + } +#endif + cb_window((uint32_t)u->win_size * 1250u + 625u); + CB->wincntl2 = HW_WIN_NORMAL; + fm1_ble_col_wr(HW_LINK, 2, 7u << 12); /* latency 0 */ + cb_widen(hw_widening(u->interval, drv.sca)); + fm1_ble_col_wr(HW_LINK, 4, u->win_offset ? 0x8000u | (2u * u->win_offset - 1u) : 0u); + fm1_ble_col_wr(HW_LINK, 1, 2u * u->interval); + fm1_ble_col_wr(HW_LINK, 15, 0x8000u | (2u * u->interval) >> 16); + drv.interval = u->interval; + drv.win_wide = 1; + drv.wide_from = drv.upd_instant; + drv.upd &= (uint8_t)~UPD_CONN; + ble_diag_ev(BDE_INSTANT, drv.upd_instant); + } +} + +static void hw_event_service(void) +{ + uint16_t c3, counter; + uint8_t rx_ok; + if (drv.state != HW_CONN) + return; /* advertising: the engine does it all (HW §8 IRQ 45 step 2) */ + c3 = (uint16_t)fm1_ble_col_rd(HW_LINK, 3); + if (!c3) { + BLE_DG(ble_dg.c3_zero++); + if (!hwd.c3_seen) { + hwd.c3_seen = 1; + ble_diag_ev(BDE_C3_ZERO, 0); + } + return; /* no connection event opened yet (the advertising event + * the CONNECT_IND ended) */ + } + counter = (uint16_t)(c3 - 1u); /* HW §2.3 column 3: minus 1 [M:s] */ + if (counter == drv.last_evt) { + BLE_DG(ble_dg.evt_same++); + return; + } + if (drv.last_evt == 0xFFFFu) { + BLE_DG(ble_dg.first_evt = counter); + ble_diag_ev(BDE_FIRST_EVT, counter); + } + drv.last_evt = counter; + ble_hw_stat.events++; + BLE_DG(ble_dg.conn_events++); + BLE_DG(ble_dg.last_evt = counter); + /* a reception in this event: an RX interrupt, or EVTCOUNT (also moved by a repeat the engine dropped) */ + rx_ok = (uint8_t)(drv.rx_seen || (drv.rx_any && CB->evtcount == counter)); + drv.rx_seen = 0; + hw_instants(counter); +#if BLE_CENTRAL + if (drv.master) { +#if BLE_DIAG + ble_dgc.m_events++; + ble_dgc.m_events_rx += rx_ok; + if (ble_dgc.m_first_evt == 0xFFFFu) + ble_dgc.m_first_evt = counter; +#endif + if (drv.win_wide && rx_ok && (int16_t)(counter - drv.wide_from) >= 0 && !drv.upd) { + cb_window(0); /* HW §21.3 step 4 / §21.4: 0, and 30 us after our TX */ + CB->wincntl2 = 30u; + fm1_ble_col_wr(HW_LINK, 4, 0); + cb_rfprio(28u); + drv.win_wide = 0; + } + ble_ll_hw_event_end(counter, rx_ok); + return; + } +#endif + if (drv.win_wide && rx_ok && (int16_t)(counter - drv.wide_from) >= 0 && !drv.upd) { + cb_window(HW_WIN_NORMAL); /* in step: the normal window (WINCNTL2), the offset spent */ + fm1_ble_col_wr(HW_LINK, 4, 0); + cb_rfprio(28u); + drv.win_wide = 0; + } + ble_ll_hw_event_end(counter, rx_ok); +} + +static void hw_isr_end(uint32_t t0) +{ + uint32_t d = fm1_ticks() - t0; + if (d > ble_hw_stat.isr_max_ticks) + ble_hw_stat.isr_max_ticks = d; +#if BLE_DIAG /* (blell: with enc_on, what the software AES-CCM costs) */ + if (d / FM1_TICKS_PER_US > ble_dg.isr_max_us) + ble_dg.isr_max_us = d / FM1_TICKS_PER_US; +#endif +} + +void ble_wl82_rx_irq(void) /* IRQ 29, via isr_ble_rx (hal/fm1_ble.h) */ +{ + uint32_t t0 = fm1_ticks(); + uint8_t conn = drv.state == HW_CONN; /* a connection RX interrupt: the TX service at its end (HW §8.2 point 3) */ + hwd.isr_t0 = t0; + fm1_ble_crumb_irqs++; + fm1_ble_rx_ack(HW_LINK); + BLE_DG(ble_dg.rx_irqs++); +#if BLE_CENTRAL + if (drv.state == HW_SCAN) { + BLE_DG(ble_dgs.rx_irqs++); + RING_PUBLISH(); + hw_rx_scan(); + hw_isr_end(t0); + return; + } + if (drv.state == HW_INIT) { + RING_PUBLISH(); + hw_rx_init(); + hw_isr_end(t0); + return; + } +#endif + if (drv.state == HW_ADV) { + RING_PUBLISH(); + hw_rx_adv_isr(t0); + hw_isr_end(t0); + return; + } + if (drv.state != HW_OFF && !(CB->rxbufcntl[drv.rx_next] & 1u)) { + if (CB->rxbufcntl[drv.rx_next ^ 1u] & 1u) { /* the engine filled the other buffer: we wait on this one */ + BLE_DG(ble_dg.rx_desync++); + BLE_DG(if (ble_dg.rx_desync <= 4u) ble_diag_ev(BDE_RX_DESYNC, (uint32_t)CB->rxtog | (uint32_t)drv.rx_next << 4 | (uint32_t)drv.state << 8)); + } else + BLE_DG(ble_dg.rx_nothing++); + } + hw_rx_service(); + if (conn) + hw_tx_service(); /* after both RX buffers; never from the event IRQ */ + hw_isr_end(t0); +} + +void ble_wl82_event_irq(void) /* IRQ 45, via isr_ble_event */ +{ + uint32_t t0 = fm1_ticks(); + hwd.isr_t0 = t0; + fm1_ble_crumb_irqs++; + fm1_ble_event_ack(HW_LINK); + BLE_DG(ble_dg.evt_irqs++); + if (drv.state == HW_ADV) + BLE_DG(ble_dg.adv_events++); +#if BLE_CENTRAL + if (drv.state == HW_SCAN) { + if (fm1_ble_rx_pending(HW_LINK)) { /* this window's last report first */ + fm1_ble_rx_ack(HW_LINK); + RING_PUBLISH(); + hw_rx_scan(); + } + hw_scan_event(); + fm1_ble_event_tail(HW_LINK); + hw_isr_end(t0); + return; + } + if (drv.state == HW_INIT) { + if (fm1_ble_rx_pending(HW_LINK)) { /* the target's ADV_IND first: it decides */ + fm1_ble_rx_ack(HW_LINK); + RING_PUBLISH(); + hw_rx_init(); + } + hw_init_event(); /* (the master's set-up after a hit: HW §21.3) */ + fm1_ble_event_tail(HW_LINK); + hw_isr_end(t0); + return; + } +#endif + if (fm1_ble_rx_pending(HW_LINK)) { /* this event's packet first: it counts for rx_ok */ + fm1_ble_rx_ack(HW_LINK); + hw_rx_service(); + } else if (drv.state == HW_ADV) + hw_rx_adv_late(); /* RAM only: CNTL, then the content (hw_adv_find) */ + else if (drv.state != HW_OFF && (CB->rxbufcntl[drv.rx_next] & 1u)) + hw_rx_service(); + hw_event_service(); + fm1_ble_event_tail(HW_LINK); + hw_isr_end(t0); +} + +/* once at boot, before the interrupts are on (midi_ble.c): the two BLE vectors only, both masked at the interrupt + * controller until the radio starts. No BLE / RF register is touched. */ +static void ble_hw_wl82_attach(void) +{ +#if FELUCCA_DUAL && FELUCCA_DUALCFG + fm1_ble_irq_attach(dualcfg.flat ? 3u : BLE_HW_IRQ_PRIO); /* (dualcfg nest off: at the audio's priority) */ +#else + fm1_ble_irq_attach(BLE_HW_IRQ_PRIO); +#endif + fm1_ble_irqs_hold(1); +} + +/* the first time BLUETOOTH is ON (at boot when ON was saved, else when the menu switches it ON; midi_ble.c), and only + * with the stored trims (VM or Optimist's copy, ble_vm.c; HW §15.4): the radio, the baseband, the block. The two + * interrupts stay masked: the caller lets them go. */ +static void ble_hw_wl82_start(const struct ble_rf_trims *t) +{ + uint8_t *p = (uint8_t *)&bb.sw; + uint32_t i; + hwd.base = fm1_ticks(); /* (blell's clock: 0 at the first BLUETOOTH ON) */ + hwd.us = 0; + fm1_ble_step(FM1_BLE_STEP_RF_INIT); + (void)rfs_rf_up(t->x106, t->x107, t->x108, t->x187); /* (Bluetooth audio started the radio first: up already, + * not started again under its link; rf_share.h) */ + fm1_ble_step(FM1_BLE_STEP_BB_INIT); + for (i = 0; i < sizeof bb.inst / 2u; i++) + bb.inst[i] = 0; + for (i = 0; i < sizeof bb - sizeof bb.inst; i++) + p[i] = 0; + rfs_le_ble((uint32_t)(uintptr_t)&bb, sizeof bb); /* (BR/EDR's stand-in window, if any, replaced: no link in it) */ + drv.state = HW_OFF; +} diff --git a/platform/ble/ble_hw_wl82_central.c b/platform/ble/ble_hw_wl82_central.c new file mode 100644 index 0000000..d3d23f0 --- /dev/null +++ b/platform/ble/ble_hw_wl82_central.c @@ -0,0 +1,471 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The WL82 driver's central role (BLE_CENTRAL; docs/BLE-HW-FACTS.md §21), part of ble_hw_wl82.c (included there: it + * shares the control block, drv and the helpers): scanning (state 1, §21.2), initiating (state 3, §21.3) and the + * switch to the master of the connection (state 6, §21.3 / §21.4). The master's connection then runs on the + * peripheral's code (the RX rule of §8, the TX rule of §8.2, the event service) with the differences of §21.4 there + * (drv.master). Clean room: the fact sheet, the Core Specification; no vendor code. */ + +/* ------------------------------------------------------------------------------------------- scanning --- */ + +/* HW §21.2 in the vendor's order: one link (link 0) in state 1. The engine sends the SCAN_REQ by itself in T_IFS after + * an ADV_IND / ADV_SCAN_IND while FORMAT bit8 is clear (§21.1 [I, strong]); both TX buffers hold that SCAN_REQ with + * six zero octets where AdvA goes, which the engine must fill in (C1). Software moves the channel 37 -> 38 -> 39 in + * each event interrupt (the value written is for the next window, C12) and keeps the backoff. No column read (op 2) + * on this path, as on the advertising one. */ +#define HW_SCAN_WIN2 50u /* WINCNTL2 while scanning (HW §21.2 step 4) */ + +static void hw_scan_backoff_reset(void) +{ + drv.bo_upper = 1; + drv.bo_count = 1; + drv.bo_sent = drv.bo_succ = drv.bo_fail = 0; +} + +BLE_API void ble_hw_scan_start(const struct ble_hw_scan *s) +{ + uint32_t iv = s->interval, win = s->window, b, i; + hw_link_open(); + cb_rfprio(17u); /* 1 */ + fm1_ble_col_wr(HW_LINK, 8, 0); /* 2: advDelay off */ + if (win + 4u > iv) { /* 3: the vendor's adjustment */ + if (iv > 4u) + win = iv - 4u; + else + iv = 5u, win = 1u; + } + cb_window(win * 625u); /* 4 */ + CB->wincntl2 = HW_SCAN_WIN2; + fm1_ble_col_wr(HW_LINK, 1, iv & 0xFFFFu); + fm1_ble_col_wr(HW_LINK, 15, iv >> 16); /* bit15 = 0 for scanning (its meaning: C8) */ + CB->filtercntl &= (uint16_t)~8u; /* 5: filter policy 0 (no whitelist) */ + drv.scan_active = s->active ? 1u : 0u; + CB->format = (uint16_t)(drv.scan_active ? 0u : 0x100u); /* 6: bit8 0 = SCAN_REQ allowed */ + fm1_ble_col_wr(HW_LINK, 6, 0x2100u | 37u); /* 7: channel 37 first */ + CB->rxptr[0] = BB_OFF(bb.rx[0].buf + HW_SWHDR); /* 8: two RX buffers (264 octets of room) */ + CB->rxptr[1] = BB_OFF(bb.rx[1].buf + HW_SWHDR); + CB->rxbufcntl[0] &= (uint8_t)~1u; + CB->rxbufcntl[1] &= (uint8_t)~1u; + hw_rx_wipe(0); + hw_rx_wipe(1); + for (b = 0; b < 2u; b++) { /* 9: both TX buffers hold the SCAN_REQ */ + uint8_t *p = bb.tx[b].buf + HW_SWHDR; + for (i = 0; i < 6u; i++) { + p[i] = s->own[i]; /* ScanA */ + p[6u + i] = 0; /* AdvA: the engine's (C1) */ + } + CB->txahdr[b] = (uint16_t)(3u | (uint32_t)(s->own_rand & 1u) << 4); + CB->txdhdr[b] = (uint16_t)(12u << 8); + } + CB->txtog = 0; + fm1_ble_sync(); + fm1_ble_col_wr(HW_LINK, 2, 0x1000u); /* 10: state 1 */ + CB->optcntl &= (uint16_t)~0x200u; /* 11 */ + CB->optcntl |= 0xC00u; + hw_scan_backoff_reset(); /* 12 */ + drv.scan_ch = 37u; + drv.scan_evts = 0; + fm1_ble_sync(); + fm1_ble_link_irqs_on(HW_LINK); /* 13: the only open link: start at once */ + fm1_ble_col_wr(HW_LINK, 7, 0); + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0); + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0x8000u); + drv.state = HW_SCAN; + drv.gen++; + BLE_DG(ble_dgs.starts++); + BLE_DG(ble_dgs.ch = 37u); +} + +BLE_API void ble_hw_scan_stop(void) +{ + hw_stop(BDS_SCAN, HW_STOP_WAIT_US); /* HW §21.2 Stop: column 14 = 0, interrupts off, idle */ + BLE_DG(ble_dgs.stops++); + drv.state = HW_OFF; + drv.gen++; +} + +/* Core Vol 6 Part B 4.4.3.2 as the vendor keeps it (HW §21.2): each ADV_IND / ADV_SCAN_IND counts the backoff down; at + * 0 a SCAN_REQ went out (the engine answered that packet): if the one before got no SCAN_RSP, a failure (two in a row: + * upperLimit doubles, at most 256); the count is drawn again in 1..upperLimit. A SCAN_RSP is a success (two in a row: + * upperLimit halves). FORMAT bit8 = 0 only while the count is 1: the engine's SCAN_REQ armed for the next one. */ +static void hw_scan_backoff(uint8_t type) +{ + uint8_t r; + if (!drv.scan_active) + return; + if (type == 0x4u) { + if (drv.bo_sent) { + drv.bo_sent = 0; + drv.bo_fail = 0; + if (++drv.bo_succ >= 2u) { + drv.bo_succ = 0; + drv.bo_upper = (uint16_t)(drv.bo_upper > 1u ? drv.bo_upper / 2u : 1u); + } + BLE_DG(ble_dgs.rsp_ok++); + } + return; + } + if (type != 0x0u && type != 0x6u) + return; + if (--drv.bo_count == 0) { + if (drv.bo_sent) { + drv.bo_succ = 0; + BLE_DG(ble_dgs.req_fail++); + if (++drv.bo_fail >= 2u) { + drv.bo_fail = 0; + drv.bo_upper = (uint16_t)(drv.bo_upper < 256u ? drv.bo_upper * 2u : 256u); + } + } + drv.bo_sent = 1; + BLE_DG(ble_dgs.req_armed++); + ble_hw_rand(&r, 1); + drv.bo_count = (uint8_t)(1u + r % drv.bo_upper); /* (upper 256: 1..256 as 1..255 + 0 -> a uint8 of 1..255) */ + if (!drv.bo_count) + drv.bo_count = 1; +#if BLE_DIAG + if (drv.bo_upper > ble_dgs.upper_max) + ble_dgs.upper_max = drv.bo_upper; +#endif + } + CB->format = (uint16_t)((CB->format & ~0x100u) | (drv.bo_count == 1u ? 0u : 0x100u)); +} + +/* one report out of RX buffer b: header from RXAHDR / RXDHDR, status RXSTAT, RSSI2, the channel LASTCHMAP (HW §21.2) */ +static void hw_scan_take(uint32_t b) +{ + uint16_t ah = CB->rxahdr[b], dh = CB->rxdhdr[b], st = CB->rxstat[b], rssi = CB->rssi[2]; + uint8_t n = (uint8_t)(dh >> 8), type = (uint8_t)(ah & 0x0Fu), ch = (uint8_t)CB->lastchmap, *pdu; + CB->rxahdr[b] = CB->rxdhdr[b] = CB->rxstat[b] = 0; /* (a buffer found again by RXTOG alone is a new packet) */ + BLE_DG(ble_dgs.last_ahdr = ah); + BLE_DG(ble_dgs.last_dhdr = dh); + BLE_DG(ble_dgs.last_rssi = rssi); + BLE_DG(ble_dgs.last_ch = ch); + if ((st & 0xFu) != 1u) { + BLE_DG(ble_dgs.rx_bad_stat++); + return; + } + if (n < 6u || n > 37u) { + BLE_DG(ble_dgs.rx_bad_len++); + return; + } + if (type == 0x3u || type == 0x5u) + return; /* SCAN_REQ / CONNECT_IND: dropped in state 1 */ + pdu = &bb.rx[b].buf[HW_SWHDR - 2u]; + pdu[0] = (uint8_t)ah; /* Core layout: type, ChSel, TxAdd, RxAdd */ + pdu[1] = n; + hw_scan_backoff(type); + ble_ll_hw_adv_report(pdu, (uint8_t)(n + 2u), rssi, ch); +} + +/* the RX interrupt while scanning: the connection path of HW §8 (§21.2): RXTOG read until stable, the RXTOG buffer + * then the other, each if RXBUFnCNTL bit0 = 1, cleared after it. Whether the engine sets bit0 while scanning is C2; + * when neither has it, the buffer RXTOG moved past is taken if its header was written since it was last taken (the + * advertising rule the FM-1 showed, §8.1). Counted: blell scan rxf_cntl / rxf_tog / rxf_none. */ +static void hw_rx_scan(void) +{ + uint32_t t1, t2, k, took = 0, tries = 0; + uint8_t c0, c1; + do { + t1 = CB->rxtog & 1u; + c0 = CB->rxbufcntl[0]; + c1 = CB->rxbufcntl[1]; + t2 = CB->rxtog & 1u; + } while (t1 != t2 && ++tries < 4u); + BLE_DG(ble_dgs.last_cntl = (uint8_t)((c0 & 1u) | (c1 & 1u) << 1)); + BLE_DG(ble_dgs.last_tog = (uint8_t)t2); + for (k = 0; k < 2u; k++) { + uint32_t b = t2 ^ k; + if ((b ? c1 : c0) & 1u) { + BLE_DG(ble_dgs.rxf_cntl++); + hw_scan_take(b); + CB->rxbufcntl[b] &= (uint8_t)~1u; + took++; + } + } + if (!took && (CB->rxdhdr[t2 ^ 1u] || CB->rxstat[t2 ^ 1u])) { + BLE_DG(ble_dgs.rxf_tog++); + hw_scan_take(t2 ^ 1u); + took++; + } + if (!took) + BLE_DG(ble_dgs.rxf_none++); +} + +/* the event interrupt while scanning: the next window's channel (HW §21.2 "Each event"), RFPRIO 17, 26 every 6th */ +static void hw_scan_event(void) +{ + fm1_ble_col_wr(HW_LINK, 6, 0x2100u | drv.scan_ch); + drv.scan_ch = (uint8_t)(drv.scan_ch >= 39u ? 37u : drv.scan_ch + 1u); + cb_rfprio(++drv.scan_evts % 6u ? 17u : 26u); + BLE_DG(ble_dgs.events++); + BLE_DG(ble_dgs.ch = drv.scan_ch); +} + +/* ----------------------------------------------------------------------------------------------- initiating --- */ + +/* HW §21.3 in the vendor's order: link 0 in state 3, our CONNECT_IND complete in both TX buffers before the link + * starts; the one target in WHITELIST0 / TARGETADR with FILTERCNTL bit0 (entry valid), bit4 (CONNECT_IND only to it) + * and bit8 (its type); the engine sends the CONNECT_IND T_IFS after the target's ADV_IND by itself (C3) and leaves + * initiating (column 9 = 1). The windows and channels as scanning (the event interrupt moves the channel). No column + * read (op 2) on this path. */ +static void hw_adr(volatile uint16_t *r, const uint8_t a[6]) /* an address into three little-endian halves */ +{ + r[0] = (uint16_t)(a[0] | a[1] << 8); + r[1] = (uint16_t)(a[2] | a[3] << 8); + r[2] = (uint16_t)(a[4] | a[5] << 8); +} + +BLE_API void ble_hw_init_start(const struct ble_hw_init *in) +{ + const uint8_t *p = in->cind; + uint32_t iv = in->interval, win = in->window, b, i; + hw_cpy(drv.init_own, p + 2, 6); + hw_cpy(drv.init_peer, p + 8, 6); + drv.init_own_rand = (uint8_t)(p[0] >> 6 & 1u); + drv.init_peer_rand = (uint8_t)(p[0] >> 7 & 1u); + drv.ic = in->conn; + hw_link_open(); + cb_rfprio(26u); /* 1 */ + fm1_ble_col_wr(HW_LINK, 8, 0); /* 2: as scanning (§21.2 steps 3-4), column 6 = 37 */ + if (win + 4u > iv) { + if (iv > 4u) + win = iv - 4u; + else + iv = 5u, win = 1u; + } + cb_window(win * 625u); + CB->wincntl2 = HW_SCAN_WIN2; + fm1_ble_col_wr(HW_LINK, 1, iv & 0xFFFFu); + fm1_ble_col_wr(HW_LINK, 15, iv >> 16); + fm1_ble_col_wr(HW_LINK, 6, 0x2100u | 37u); + hw_adr(CB->localadr, drv.init_own); /* 3: our address, its match on */ + CB->format = 0x0008u; + CB->optcntl &= (uint16_t)~0x10u; + hw_adr(CB->whitelist, drv.init_peer); /* 4: the target */ + CB->filtercntl = (uint16_t)((CB->filtercntl & 0x7Eu) | 1u | (uint32_t)drv.init_peer_rand << 8); + CB->filtercntl |= 0x10u; + CB->optcntl &= (uint16_t)~0x08u; + hw_adr(CB->targetadr, drv.init_peer); + CB->rxptr[0] = BB_OFF(bb.rx[0].buf + HW_SWHDR); /* 5: two RX buffers */ + CB->rxptr[1] = BB_OFF(bb.rx[1].buf + HW_SWHDR); + CB->rxbufcntl[0] &= (uint8_t)~1u; + CB->rxbufcntl[1] &= (uint8_t)~1u; + hw_rx_wipe(0); + hw_rx_wipe(1); + for (b = 0; b < 2u; b++) { /* 6: both TX buffers the CONNECT_IND */ + uint8_t *q = bb.tx[b].buf + HW_SWHDR; + for (i = 0; i < 34u; i++) + q[i] = p[2 + i]; + CB->txahdr[b] = (uint16_t)(5u | (uint32_t)drv.init_own_rand << 4 | (uint32_t)drv.init_peer_rand << 5); + CB->txdhdr[b] = (uint16_t)(34u << 8); + } + CB->txtog = 0; + fm1_ble_sync(); + fm1_ble_col_wr(HW_LINK, 2, 0x3000u); /* 7: state 3 */ + drv.scan_ch = 37u; /* (the first event writes 37 again, as scanning) */ + drv.scan_evts = 0; + drv.init_hit = 0; + drv.master = 0; + fm1_ble_sync(); + fm1_ble_link_irqs_on(HW_LINK); /* 8: the only open link: start at once */ + fm1_ble_col_wr(HW_LINK, 7, 0); + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0); + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0x8000u); + fm1_ble_col_wr(HW_LINK, 9, 1); /* "init end": the engine leaves state 3 after it */ + drv.state = HW_INIT; + drv.gen++; + drv.init_t0 = fm1_ticks(); /* (after the start: a packet heard ends later than this) */ + BLE_DG(ble_dgc.init_last_ch = 37u); +} + +BLE_API void ble_hw_init_stop(void) +{ + hw_stop(BDS_INIT, HW_STOP_WAIT_US); /* as any link: column 14 = 0, interrupts off, idle */ + drv.state = HW_OFF; + drv.gen++; +} + +/* one state-3 report in buffer b: the target's ADV_IND (AdvA, TxAdd) or an ADV_DIRECT_IND from it to us (TargetA, + * RxAdd) marks the hit; the engine has sent our CONNECT_IND after it (§21.3 "Reception"); anything else is dropped. + * A report that ends sooner after ble_hw_init_start than its own airtime ((1 + 4 + 2 + n + 3) x 8 us at 1 Mb/s) was + * in the air before the engine listened for the target: the scan's packet that was being received when the pick + * stopped it. No CONNECT_IND follows it, so it is no hit: taken as one, the event IRQ at the window's end switched to + * the master with nothing sent (state 6 with no link, never left; the "mac" pick of tests/ble_emu_central_test.py + * when the pick landed during the Mac's ADV_IND: c4_rx_to_evt 37.9 ms, a whole window, where a real hit is 0.4 ms) */ +static int hw_init_stale(uint32_t n) +{ + return (fm1_ticks() - drv.init_t0) / FM1_TICKS_PER_US < (10u + n) * 8u; +} +static void hw_init_take(uint32_t b) +{ + uint16_t ah = CB->rxahdr[b], dh = CB->rxdhdr[b], st = CB->rxstat[b]; + const uint8_t *p = bb.rx[b].buf + HW_SWHDR; + uint8_t n = (uint8_t)(dh >> 8), type = (uint8_t)(ah & 0x0Fu); + CB->rxahdr[b] = CB->rxdhdr[b] = CB->rxstat[b] = 0; + BLE_DG(ble_dgc.init_last_ahdr = ah); + BLE_DG(ble_dgc.init_last_dhdr = dh); + if ((st & 0xFu) != 1u || n < 6u || n > 37u) { + BLE_DG(ble_dgc.init_rx_bad++); + return; + } + if (hw_init_stale(n)) { + BLE_DG(ble_dgc.init_rx_stale++); + return; + } + if ((type == 0x0u || (type == 0x1u && n == 12u && ble_eq(p + 6, drv.init_own, 6) && + (uint8_t)(ah >> 7 & 1u) == drv.init_own_rand)) && + ble_eq(p, drv.init_peer, 6) && (uint8_t)(ah >> 6 & 1u) == drv.init_peer_rand) { + if (!drv.init_hit) { + drv.init_hit = 1; + drv.init_t_hit = fm1_ticks(); + BLE_DG(ble_dgc.init_chsel = (uint8_t)(ah >> 5 & 1u)); + ble_diag_ev(BDE_INIT_HIT, ah); + } + BLE_DG(ble_dgc.init_rx_target++); + } else + BLE_DG(ble_dgc.init_rx_other++); +} + +/* the RX interrupt in state 3: the vendor reads the buffer other than RXTOG's without RXBUFnCNTL (the advertising + * path, §21.3); each buffer is taken by bit0 if the engine sets it, else by RXTOG having moved past a written header */ +static void hw_rx_init(void) +{ + uint32_t t = CB->rxtog & 1u, k, took = 0; + BLE_DG(ble_dgc.init_rx++); + for (k = 0; k < 2u; k++) + if (CB->rxbufcntl[k] & 1u) { + BLE_DG(ble_dgc.init_rxf_cntl++); + hw_init_take(k); + CB->rxbufcntl[k] &= (uint8_t)~1u; + took++; + } + if (!took && (CB->rxdhdr[t ^ 1u] || CB->rxstat[t ^ 1u])) { + BLE_DG(ble_dgc.init_rxf_tog++); + hw_init_take(t ^ 1u); + } +} + +/* The first anchor (HW §21.3 "First anchor", C5): the anchor counter runs 2 x WinOffset + 4 slots from its start, which + * puts the first master packet WinOffset x 1.25 ms + 2.5 ms after this set-up. The peripheral listens for it only in the + * transmit window, WinSize (2) x 1.25 ms long, 1.25 ms + WinOffset x 1.25 ms after the CONNECT_IND's end; the CONNECT_IND + * ends about 0.5 ms after the target's ADV_IND that the hit is (T_IFS + its 352 us), so the packet lands + * (set-up - hit) + 0.75 ms into the 2.5 ms window. On the FM-1 the event interrupt that runs this set-up came 0.2 and + * 0.5 ms after the hit in the connections that were made, 1.9 and 4.8 ms in the two that failed with 0x3E (blell-dev3, + * dev4: c4_rx_to_evt_*): the packet after the window, never heard. So the counter is shortened by the slots the set-up + * came late (whole slots past HW_ANCHOR_AIM_US), which keeps the packet 0.6..1.4 ms into the window; it never goes + * under HW_ANCHOR_MIN_SLOTS (later than that the window is gone: the link fails to be established, 0x3E, and the host + * tries again). Counted: m_anchor_adj (slots, last / max), m_anchor_late. */ +#define HW_ANCHOR_AIM_US 500u +#define HW_ANCHOR_MIN_SLOTS 3u + +static uint32_t hw_first_anchor(const struct ble_hw_conn *c) /* -> the anchor counter's column 0 value */ +{ + uint32_t n = 2u * c->win_offset + 4u, late = (fm1_ticks() - drv.init_t_hit) / FM1_TICKS_PER_US, adj = 0; + if (late > 625u) + adj = (late - HW_ANCHOR_AIM_US + 624u) / 625u; + if (adj + HW_ANCHOR_MIN_SLOTS > n) { + adj = n - HW_ANCHOR_MIN_SLOTS; + BLE_DG(ble_dgc.m_anchor_late++); + } +#if BLE_DIAG + ble_dgc.m_setup_us = late; + ble_dgc.m_anchor_adj = (uint8_t)adj; + if (adj > ble_dgc.m_anchor_adj_max) + ble_dgc.m_anchor_adj_max = (uint8_t)adj; +#endif + return n - adj - 1u; /* (the counter fires one slot after the value) */ +} + +/* the master's set-up (§21.3 "Switch to master", the vendor's order), in the event interrupt after the hit */ +static void hw_master_setup(void) +{ + const struct ble_hw_conn *c = &drv.ic; + uint32_t a, k; + cb_rfprio(28u); /* 1: as the slave's (§7) */ + CB->anchor = 0x8000u; + CB->txtog &= (uint16_t)~2u; + CB->rxtog = 0; + CB->bdaddr[0] = (uint16_t)c->aa; + CB->bdaddr[1] = (uint16_t)(c->aa >> 16); + CB->crcword[0] = (uint16_t)c->crc_init; + CB->crcword[1] = (uint16_t)(c->crc_init >> 16 & 0xFFu); + CB->optcntl |= 4u; + CB->optcntl &= (uint16_t)~0x200u; + CB->optcntl |= 0xC00u; + CB->optcntl |= 0x1000u; + CB->intframe = (uint16_t)((CB->intframe & ~0x30u) | 0x10u); + CB->txbufcntl[0] |= 1u; /* both TX buffers empty (the only 1-writes, §8.2) */ + CB->txbufcntl[1] |= 1u; + CB->anchor = (uint16_t)((CB->anchor & 0x8000u) | 4u); + fm1_ble_col_wr(HW_LINK, 5, 0); + fm1_ble_col_wr(HW_LINK, 4, 0); /* 2: master only */ + fm1_ble_col_wr(HW_LINK, 7, 0); + fm1_ble_col_wr(HW_LINK, 0, 0); + fm1_ble_col_wr(HW_LINK, 14, 0); + a = hw_first_anchor(c); /* 2 x WinOffset + 4 slots, less the set-up's lateness */ + for (k = 0; k < 2u; k++) { /* (written twice with the same value on 1M) */ + fm1_ble_col_wr(HW_LINK, 0, a & 0xFFFFu); + fm1_ble_col_wr(HW_LINK, 14, 0x8000u | a >> 16); + } + fm1_ble_col_wr(HW_LINK, 2, 0x6000u); /* state 6, latency 0 */ + fm1_ble_col_wr(HW_LINK, 8, 0); /* 3: the shared tail */ + fm1_ble_col_wr(HW_LINK, 3, 0); + CB->evtcount = 0; + cb_window((uint32_t)c->win_size * 1250u + 1250u); + CB->wincntl2 = HW_WIN_NORMAL; + fm1_ble_col_wr(HW_LINK, 1, 2u * c->interval); + fm1_ble_col_wr(HW_LINK, 15, 0x8000u | (2u * c->interval) >> 16); + cb_channels(c->chm); + fm1_ble_col_wr(HW_LINK, 6, 0x8000u | (uint32_t)c->hop << 8 | c->hop); + CB->txahdr[0] = CB->txahdr[1] = 0; + CB->txdhdr[CB->txtog & 1u] = 1u; /* the TXTOG buffer: LLID 1, bit2 0; the other bit2 1 */ + CB->txdhdr[(CB->txtog & 1u) ^ 1u] = 5u; + fm1_ble_sync(); + drv.state = HW_CONN; + drv.master = 1; + drv.gen++; + drv.rx_next = 0; + drv.rx_sn = 0; + drv.rx_seen = drv.rx_any = 0; + drv.tx_rec[0] = drv.tx_rec[1] = 0; /* no PDU recorded in either buffer */ + drv.tx_md[0] = drv.tx_md[1] = 0; + drv.upd = 0; + drv.win_wide = 1; /* the first window, until the first packet */ + drv.wide_from = 0; + drv.interval = c->interval; + drv.sca = c->sca; + drv.last_evt = 0xFFFFu; + ble_hw_stat.connects++; + hwd.conn_t0 = fm1_ticks(); + hwd.first_rx = hwd.c3_seen = 0; +#if BLE_DIAG + { + uint32_t us = (hwd.conn_t0 - drv.init_t_hit) / FM1_TICKS_PER_US; + ble_dgc.c4_rx_to_evt_us = us; + if (us > ble_dgc.c4_rx_to_evt_max) + ble_dgc.c4_rx_to_evt_max = us; + ble_dgc.master_starts++; + ble_dgc.m_first_rx_evt = ble_dgc.m_first_evt = 0xFFFFu; + ble_dgc.m_first_rx_us = 0; + } +#endif + ble_ll_hw_master_start(); +} + +/* the event interrupt in state 3: after the hit, the master; else the next window's channel, RFPRIO 26 (30 every 6th: + * §21.6) */ +static void hw_init_event(void) +{ + BLE_DG(ble_dgc.init_events++); + if (drv.init_hit) { + hw_master_setup(); + return; + } + fm1_ble_col_wr(HW_LINK, 6, 0x2100u | drv.scan_ch); + BLE_DG(ble_dgc.init_last_ch = drv.scan_ch); + drv.scan_ch = (uint8_t)(drv.scan_ch >= 39u ? 37u : drv.scan_ch + 1u); + cb_rfprio(++drv.scan_evts % 6u ? 26u : 30u); +} diff --git a/platform/ble/ble_ll.c b/platform/ble/ble_ll.c new file mode 100644 index 0000000..05c82a8 --- /dev/null +++ b/platform/ble/ble_ll.c @@ -0,0 +1,840 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The link layer, one connection, LE 1M (Core Specification Vol 6 Part B): the peripheral, and with BLE_CENTRAL the + * scanner, the initiator and the master of a connection (ble_ll_central.c). The baseband engine + * (ble_hw.h) does the per-event timing, hopping, acknowledgement and instants; this file does the rest: + * - advertising PDUs (ADV_IND, SCAN_RSP) and CONNECT_IND checks (4.4, 4.5.1, 2.3.3.1); + * - the TX queues (control PDUs first, then L2CAP frames cut to the data length in use) and RX hand-over; + * - the supervision timeout and the six-interval establishment rule (4.5.2), the 40 s procedure timeout (5.2); + * - the control procedures (5.1): connection update and channel map with instants, termination, feature + * exchange (also started by us), version exchange, ping, data length, PHY update (1M only), connection + * parameters request (accepted when valid), encryption start (BLE_LL_ENC, else refused); LL_UNKNOWN_RSP for + * the rest. */ +#include "ble_ll.h" +#include "ble_hw.h" +#include "ble_util.h" +#include "ble_prim.h" +#include "ble_diag.h" +#if BLE_LL_ENC +#include "ble_aes.h" +#endif + +#define LL_RING_MASK (BLE_LL_TX_RING - 1u) +#define LL_PROC_US 40000000u /* the LL response timeout: 40 s */ +enum { LL_OFF, LL_ADV, LL_CONN, LL_SCAN, LL_INIT }; +/* procedures waiting on the peer: ours (lproc) and the peer's (rproc); P_VER: our version exchange (as master) */ +enum { P_NONE, P_FEAT, P_LEN, P_TERM, P_UPD, P_PHY, P_ENC, P_VER }; + +#define LL_OUR_FEAT ((BLE_LL_ENC ? BLE_FEAT_ENC | BLE_FEAT_PING : 0u) | BLE_FEAT_CONN_PARAM | BLE_FEAT_EXT_REJECT | \ + BLE_FEAT_PERIPH_FEAT | (BLE_LL_MAX_OCTETS > 27u ? BLE_FEAT_DLE : 0u)) + +static struct { + uint8_t state, enabled, addr_rand; + uint8_t scan_want; /* BLE_CENTRAL: scan instead of advertising (ble_ll_scan) */ + uint8_t addr[6]; + uint8_t adv[2 + 37], adv_len, sr[2 + 37], sr_len; + /* the connection */ + uint16_t interval, timeout, last_evt; + uint8_t win_size, established, chm[5]; + uint16_t win_offset; + uint32_t t_start, t_rx; + uint8_t max_tx, max_rx; /* the data length in use (octets) */ + uint16_t peer_len[4]; /* the central's last MaxRxOctets, MaxRxTime, MaxTxOctets, MaxTxTime */ + uint8_t peer_feat, feat_known, ver_sent, len_done; + uint8_t peer[6], peer_rand; /* the peer's address and type: a central's InitA / TxAdd from its + * CONNECT_IND; as master, the AdvA we connected to */ + uint8_t central; /* BLE_CENTRAL: we are the master of this connection */ + uint8_t upd_pending, chm_pending; + struct ble_hw_conn_upd upd; + uint8_t new_chm[5]; + uint16_t chm_instant; + uint8_t lproc, rproc; + uint32_t lproc_t, rproc_t; + uint8_t term_rx, term_reason; + uint8_t handed, acked, term_seq, term_out; /* PDUs given to the engine / acknowledged; LL_TERMINATE_IND's + * number, and that it went out */ + /* TX: control PDUs, then L2CAP frames in a byte ring */ + uint8_t ctrl[BLE_LL_CTRL_Q][24], ctrl_len[BLE_LL_CTRL_Q], ctrl_rd, ctrl_n; + uint8_t ring[BLE_LL_TX_RING]; + uint32_t wr, rd, off; /* free-running ring indexes; off: octets of the head frame sent */ +#if BLE_LL_ENC + uint8_t enc_rx, enc_tx, tx_paused; + struct ble_ccm ccm_rx, ccm_tx; + uint8_t rxbuf[BLE_LL_MAX_OCTETS + 4u]; +#endif +} bll; + +/* ------------------------------------------------------------------------------------------ advertising --- */ + +BLE_API void ble_ll_init(const uint8_t addr[6], uint8_t addr_random) +{ + ble_zero((uint8_t *)&bll, sizeof bll); + ble_cpy(bll.addr, addr, 6); + bll.addr_rand = addr_random ? 1u : 0u; + ble_ll_set_adv_data(0, 0, 0, 0); +} + +static uint8_t ll_adv_pdu(uint8_t *pdu, uint8_t type, const uint8_t *d, uint8_t n) +{ + if (n > 31u) + n = 31u; + pdu[0] = (uint8_t)(type | bll.addr_rand << 6); /* TxAdd; ChSel 0: we only know Algorithm #1 */ + pdu[1] = (uint8_t)(6u + n); + ble_cpy(pdu + 2, bll.addr, 6); + ble_cpy(pdu + 8, d, n); + return (uint8_t)(8u + n); +} + +static void ll_adv_start(void) +{ + struct ble_hw_adv a; + a.adv = bll.adv; + a.adv_len = bll.adv_len; + a.scan_rsp = bll.sr; + a.scan_rsp_len = bll.sr_len; + a.interval = BLE_ADV_INTERVAL; + a.channels = BLE_ADV_CHANNELS; + bll.state = LL_ADV; + ble_hw_adv_start(&a); +} + +BLE_API void ble_ll_set_adv_data(const uint8_t *ad, uint8_t ad_len, const uint8_t *sr, uint8_t sr_len) +{ + bll.adv_len = ll_adv_pdu(bll.adv, 0x0u, ad, ad_len); /* ADV_IND */ + bll.sr_len = ll_adv_pdu(bll.sr, 0x4u, sr, sr_len); /* SCAN_RSP */ + if (bll.state == LL_ADV) + ll_adv_start(); +} + +BLE_API int ble_ll_connected(void) { return bll.state == LL_CONN; } +BLE_API uint16_t ble_ll_interval(void) { return bll.state == LL_CONN ? bll.interval : 0; } +BLE_API uint16_t ble_ll_timeout(void) { return bll.state == LL_CONN ? bll.timeout : 0; } +BLE_API uint8_t ble_ll_peer_features(void) { return bll.feat_known ? bll.peer_feat : 0; } +BLE_API uint8_t ble_ll_tx_octets(void) { return bll.state == LL_CONN ? bll.max_tx : 0; } +BLE_API uint16_t ble_ll_peer_len(uint32_t i) { return bll.state == LL_CONN ? bll.peer_len[i & 3u] : 0; } + +BLE_API uint8_t ble_ll_addrs(uint8_t own[6], uint8_t peer[6]) +{ + ble_cpy(own, bll.addr, 6); + ble_cpy(peer, bll.peer, 6); + return (uint8_t)(bll.addr_rand | bll.peer_rand << 1); +} + +#if BLE_LL_ENC +BLE_API int ble_ll_encrypted(void) { return bll.state == LL_CONN && bll.enc_tx; } +#else +BLE_API int ble_ll_encrypted(void) { return 0; } +#endif + +/* the LL's encryption PDUs in blell's protocol ring (ble_diag_pdu), both ways; LL_ENC_REQ as op, EDIV, Rand's low 5 */ +#if BLE_DIAG +static void ll_diag_enc(uint8_t tx, const uint8_t *p, uint8_t n) +{ + uint8_t op = p[0], v[8]; + if (!(op >= LL_ENC_REQ && op <= LL_UNKNOWN_RSP) && op != LL_PAUSE_ENC_REQ && op != LL_PAUSE_ENC_RSP && + op != LL_REJECT_IND && op != LL_REJECT_EXT_IND) + return; + if (op == LL_ENC_REQ && n >= 11u && !tx) { + v[0] = op; + v[1] = p[9]; + v[2] = p[10]; + ble_cpy(v + 3, p + 1, 5); + p = v; + n = 8u; + ble_dg.enc_req_n++; + } + ble_diag_pdu((uint8_t)(BDP_LL | (tx ? BDP_TX : 0u)), p, n); +} +#else +#define ll_diag_enc(tx, p, n) ((void)0) +#endif + +static void ll_idle(void); + +static void ll_close_by(uint8_t reason, uint8_t by) +{ +#if BLE_DIAG + uint32_t now = ble_hw_time_us(); +#else + (void)ble_hw_time_us(); /* (the link layer's clock still steps) */ +#endif + BLE_DG(ble_dg.closes++); + BLE_DG(ble_dg.close_reason = reason); + BLE_DG(ble_dg.close_by = by); + BLE_DG(ble_dg.close_evt = bll.last_evt); + BLE_DG(ble_dg.close_since_rx_us = now - bll.t_rx); + BLE_DG(ble_dg.close_since_start_us = now - bll.t_start); + if (by == BDC_SUPERVISION) + BLE_DG(ble_dg.sup_timeouts++); + else if (by == BDC_ESTABLISH) + BLE_DG(ble_dg.estab_fails++); + else if (by == BDC_PEER) + BLE_DG(ble_dg.peer_terms++); + ble_diag_ev(BDE_CLOSE, (uint32_t)reason | (uint32_t)by << 8); +#if BLE_CENTRAL && BLE_DIAG + if (bll.central) { /* (the master's endings, C3) */ + ble_dgc.m_closes++; + ble_dgc.m_close_reason = reason; + ble_dgc.m_close_by = by; + ble_dgc.m_estab_fails += by == BDC_ESTABLISH; + ble_dgc.m_sup_timeouts += by == BDC_SUPERVISION; + } +#endif + ble_hw_conn_stop(); + bll.state = LL_OFF; + ble_host_disconnected(reason); + ll_idle(); +} + +static void ll_close(uint8_t reason) { ll_close_by(reason, BDC_PROTOCOL); } + +#if BLE_CENTRAL +static void ll_scan_start(void); /* (ble_ll_central.c) */ +#endif + +/* no link: scan (BLE_CENTRAL, the DEVICES list open), else advertise when enabled, else nothing */ +static void ll_idle(void) +{ +#if BLE_CENTRAL + if (bll.enabled && bll.scan_want) { + ll_scan_start(); + return; + } +#endif + if (bll.enabled) + ll_adv_start(); +} + +BLE_API void ble_ll_enable(int on) +{ + bll.enabled = on ? 1u : 0u; + ble_diag_ev(BDE_ENABLE, (uint32_t)bll.enabled | (uint32_t)bll.state << 8); + if (on && bll.state == LL_OFF) + ll_idle(); + else if (!on && bll.state == LL_ADV) { + ble_hw_adv_stop(); + bll.state = LL_OFF; +#if BLE_CENTRAL + } else if (!on && bll.state == LL_SCAN) { + ble_hw_scan_stop(); + bll.state = LL_OFF; + } else if (!on && bll.state == LL_INIT) { + ble_hw_init_stop(); + bll.state = LL_OFF; +#endif + } else if (!on && bll.state == LL_CONN) + ble_ll_disconnect(BLE_ERR_REMOTE_USER); +} + +/* timeout x 10 ms must exceed (1 + latency) x interval x 1.25 ms x 2 */ +static int ll_params_ok(uint32_t interval, uint32_t latency, uint32_t timeout) +{ + return interval >= 6u && interval <= 3200u && timeout >= 10u && timeout <= 3200u && latency <= 499u && + timeout * 4u > (1u + latency) * interval; +} + +/* why a CONNECT_IND is refused (BDR_*, 0: taken): the same tests ble_ll_hw_connect_ind always made, named for blell */ +static uint8_t ll_cind_check(const uint8_t *pdu, uint8_t len, const struct ble_hw_conn *c, struct ble_chmap *m) +{ + const uint8_t *p = pdu + 2; + if (bll.state != LL_ADV) + return BDR_NOT_ADV; + if (len < 2u + 34u || (pdu[0] & 0x0Fu) != 0x5u || pdu[1] != 34u) + return BDR_FORMAT; + if ((pdu[0] >> 7) != bll.addr_rand) + return BDR_RXADD; + if (!ble_eq(p + 6, bll.addr, 6)) + return BDR_ADVA; + if (!ll_params_ok(c->interval, c->latency, c->timeout)) + return BDR_PARAMS; + if (c->win_size < 1u || c->win_size > 8u || c->win_size >= c->interval) + return BDR_WINSIZE; + if (c->win_offset > c->interval) + return BDR_WINOFF; + if (c->hop < 5u || c->hop > 16u) + return BDR_HOP; + if (!ble_chmap_set(m, c->chm)) + return BDR_CHM; + if (c->aa == BLE_ADV_AA) + return BDR_AA; + return BDR_OK; +} + +#if BLE_DIAG +static void ll_cind_seen(uint8_t hdr, const struct ble_hw_conn *c) +{ + BLE_DG(ble_dg.cind_hdr = hdr); + BLE_DG(ble_dg.cind_aa = c->aa); + BLE_DG(ble_dg.cind_crc = c->crc_init); + BLE_DG(ble_dg.cind_win_size = c->win_size); + BLE_DG(ble_dg.cind_win_off = c->win_offset); + BLE_DG(ble_dg.cind_interval = c->interval); + BLE_DG(ble_dg.cind_latency = c->latency); + BLE_DG(ble_dg.cind_timeout = c->timeout); + BLE_DG(ble_cpy(ble_dg.cind_chm, c->chm, 5)); + BLE_DG(ble_dg.cind_hop = c->hop); + BLE_DG(ble_dg.cind_sca = c->sca); +} +#else +#define ll_cind_seen(hdr, c) ((void)0) +#endif + +/* a new connection (central: we are its master): everything after the advertising state starts at zero */ +static void ll_conn_begin(const struct ble_hw_conn *c, const uint8_t peer[6], uint8_t peer_rand, uint8_t central) +{ + ble_zero((uint8_t *)&bll.interval, (uint32_t)((uint8_t *)&bll.ring - (uint8_t *)&bll.interval)); + bll.wr = bll.rd = bll.off = 0; +#if BLE_LL_ENC + bll.enc_rx = bll.enc_tx = bll.tx_paused = 0; +#endif + ble_cpy(bll.chm, c->chm, 5); + ble_cpy(bll.peer, peer, 6); + bll.peer_rand = peer_rand; + bll.central = central; + bll.interval = c->interval; + bll.timeout = c->timeout; + bll.win_size = c->win_size; + bll.win_offset = c->win_offset; + bll.last_evt = 0xFFFFu; /* the first event is counter 0 */ + bll.max_tx = bll.max_rx = 27u; + ble_zero((uint8_t *)bll.peer_len, sizeof bll.peer_len); /* (its bytes: ble_zero takes a byte pointer) */ + bll.state = LL_CONN; + bll.t_start = bll.t_rx = ble_hw_time_us(); +} + +BLE_API int ble_ll_hw_connect_ind(const uint8_t *pdu, uint8_t len) +{ + const uint8_t *p = pdu + 2; + struct ble_hw_conn c; + struct ble_chmap m; + uint8_t why; + BLE_DG(ble_dg.cind_rx++); + ble_diag_ev(BDE_CIND_RX, (uint32_t)pdu[0] | (uint32_t)(len > 1u ? pdu[1] : 0u) << 8); + if (len < 2u + 34u) { + BLE_DG(ble_dg.cind_rej++); + BLE_DG(ble_dg.cind_rej_why = BDR_FORMAT); + ble_diag_ev(BDE_CIND_REJ, BDR_FORMAT); + return 0; + } + c.aa = ble_rd32(p + 12); + c.crc_init = ble_rd24(p + 16); + c.win_size = p[19]; + c.win_offset = ble_rd16(p + 20); + c.interval = ble_rd16(p + 22); + c.latency = ble_rd16(p + 24); + c.timeout = ble_rd16(p + 26); + ble_cpy(c.chm, p + 28, 5); + c.chm[4] &= 0x1Fu; + c.hop = p[33] & 0x1Fu; + c.sca = p[33] >> 5; + ll_cind_seen(pdu[0], &c); + why = ll_cind_check(pdu, len, &c, &m); + if (why != BDR_OK) { + BLE_DG(ble_dg.cind_rej++); + BLE_DG(ble_dg.cind_rej_why = why); + ble_diag_ev(BDE_CIND_REJ, why); + return 0; + } + BLE_DG(ble_dg.cind_ok++); + BLE_DG(ble_dg.cind_rej_why = BDR_OK); + ble_diag_ev(BDE_CIND_OK, c.interval); + ll_conn_begin(&c, p, (uint8_t)(pdu[0] >> 6 & 1u), 0); + c.latency = 0; /* we listen at every event */ + ble_hw_conn_start(&c); + ble_host_connected(); + return 1; +} + +/* ------------------------------------------------------------------------------------------- TX queues --- */ + +static int ll_ctrl(uint8_t op, const uint8_t *d, uint8_t n) +{ + uint8_t i; + if (bll.ctrl_n >= BLE_LL_CTRL_Q) + return 0; + i = (uint8_t)((bll.ctrl_rd + bll.ctrl_n) % BLE_LL_CTRL_Q); + bll.ctrl[i][0] = op; + ble_cpy(bll.ctrl[i] + 1, d, n); + bll.ctrl_len[i] = (uint8_t)(n + 1u); + bll.ctrl_n++; + ble_hw_tx_kick(); + return 1; +} + +static void ll_unknown(uint8_t op) { ll_ctrl(LL_UNKNOWN_RSP, &op, 1); } + +/* refuse the central's procedure op: LL_REJECT_EXT_IND when the central knows it, else LL_REJECT_IND */ +static void ll_reject(uint8_t op, uint8_t err) +{ + uint8_t d[2]; + d[0] = op; + d[1] = err; + if (bll.feat_known && (bll.peer_feat & BLE_FEAT_EXT_REJECT)) + ll_ctrl(LL_REJECT_EXT_IND, d, 2); + else + ll_ctrl(LL_REJECT_IND, d + 1, 1); +} + +BLE_API uint32_t ble_ll_tx_room(void) +{ + uint32_t used = bll.wr - bll.rd; + if (bll.state != LL_CONN || used + 4u >= BLE_LL_TX_RING) + return 0; + return BLE_LL_TX_RING - used - 4u; +} + +BLE_API int ble_ll_send(uint16_t cid, const uint8_t *p, uint16_t n) +{ + uint8_t h[4]; + uint32_t i; + if (n > ble_ll_tx_room() || bll.lproc == P_TERM) + return 0; + ble_wr16(h, n); + ble_wr16(h + 2, cid); + for (i = 0; i < 4u; i++) + bll.ring[(bll.wr + i) & LL_RING_MASK] = h[i]; + for (i = 0; i < n; i++) + bll.ring[(bll.wr + 4u + i) & LL_RING_MASK] = p[i]; + bll.wr += 4u + n; + if (cid >= 4u && cid <= 6u) /* (blell's protocol ring: ATT, signalling, SMP) */ + ble_diag_pdu((uint8_t)(BDP_TX | (cid - 3u)), p, n); + ble_hw_tx_kick(); + return 1; +} + +static uint32_t ll_head_len(void) /* the head frame's octets, header included */ +{ + return 4u + (bll.ring[bll.rd & LL_RING_MASK] | (uint32_t)bll.ring[(bll.rd + 1u) & LL_RING_MASK] << 8); +} + +static int ll_data_ready(void) +{ +#if BLE_LL_ENC + if (bll.tx_paused) + return 0; +#endif + return bll.rd != bll.wr; +} + +BLE_API uint8_t ble_ll_hw_tx(uint8_t *pdu) +{ + uint32_t n, i, room = bll.max_tx; /* (the data length counts the payload without the MIC) */ + if (bll.state != LL_CONN) + return 0; + if (bll.ctrl_n) { + n = bll.ctrl_len[bll.ctrl_rd]; + pdu[0] = 3u; + ble_cpy(pdu + 2, bll.ctrl[bll.ctrl_rd], n); + BLE_DG(ble_diag_last(ble_dg.ctl_tx, &ble_dg.ctl_tx_n, pdu[2])); + ll_diag_enc(1, pdu + 2, (uint8_t)n); + ble_diag_ev(BDE_CTRL_TX, pdu[2]); + if (pdu[2] == LL_TERMINATE_IND) { + bll.term_seq = (uint8_t)(bll.handed + 1u); + bll.term_out = 1; + } + bll.ctrl_rd = (uint8_t)((bll.ctrl_rd + 1u) % BLE_LL_CTRL_Q); + bll.ctrl_n--; + } else if (ll_data_ready()) { + uint32_t total = ll_head_len(); + n = ble_min(total - bll.off, room); + pdu[0] = bll.off ? 1u : 2u; + for (i = 0; i < n; i++) + pdu[2 + i] = bll.ring[(bll.rd + bll.off + i) & LL_RING_MASK]; + bll.off += n; + if (bll.off == total) { + bll.rd += total; + bll.off = 0; + } + } else + return 0; + if (bll.ctrl_n || ll_data_ready()) + pdu[0] |= 0x10u; /* MD: more queued */ + pdu[1] = (uint8_t)n; +#if BLE_LL_ENC + if (bll.enc_tx) { + ble_ccm_encrypt(&bll.ccm_tx, pdu[0], pdu + 2, (uint8_t)n); + pdu[1] = (uint8_t)(n + 4u); + } +#endif + bll.handed++; + return (uint8_t)(2u + pdu[1]); +} + +BLE_API int ble_ll_hw_tx_pending(void) +{ + return bll.state == LL_CONN && (bll.ctrl_n || ll_data_ready()); +} + +BLE_API void ble_ll_hw_tx_acked(void) +{ + if (bll.state != LL_CONN || bll.acked == bll.handed) + return; + bll.acked++; + if (bll.term_out && bll.acked == bll.term_seq) + ll_close_by(BLE_ERR_LOCAL_HOST, BDC_LOCAL); +} + +BLE_API void ble_ll_disconnect(uint8_t reason) +{ + if (bll.state != LL_CONN || bll.lproc == P_TERM) + return; + bll.ctrl_n = 0; /* (anything not yet sent goes) */ + bll.rd = bll.wr; + bll.off = 0; + bll.lproc = P_TERM; + bll.lproc_t = ble_hw_time_us(); + ll_ctrl(LL_TERMINATE_IND, &reason, 1); +} + +#if BLE_CENTRAL +#include "ble_ll_central.c" /* scanning, initiating, the master's procedures */ +#endif + +/* -------------------------------------------------------------------------------- control procedures --- */ + +static void ll_lengths(const uint8_t *d) /* the central's MaxRxOctets, MaxRxTime, MaxTxOctets, MaxTxTime */ +{ + uint32_t rx_o = ble_rd16(d), rx_t = ble_rd16(d + 2), tx_o = ble_rd16(d + 4), tx_t = ble_rd16(d + 6), i; + for (i = 0; i < 4u; i++) + bll.peer_len[i] = ble_rd16(d + 2u * i); /* (as received: the screen mirror's LINK report) */ + uint32_t rx_by_t = rx_t >= 328u ? rx_t / 8u - 14u : 27u, tx_by_t = tx_t >= 328u ? tx_t / 8u - 14u : 27u; + rx_o = ble_min(ble_min(rx_o < 27u ? 27u : rx_o, rx_by_t), BLE_LL_MAX_OCTETS); + tx_o = ble_min(ble_min(tx_o < 27u ? 27u : tx_o, tx_by_t), BLE_LL_MAX_OCTETS); + bll.max_tx = (uint8_t)rx_o; /* we send at most what the central receives */ + bll.max_rx = (uint8_t)tx_o; + bll.len_done = 1; + ble_hw_set_lengths(bll.max_tx, bll.max_rx); +} + +static void ll_our_lengths(uint8_t *d) +{ + ble_wr16(d, BLE_LL_MAX_OCTETS); + ble_wr16(d + 2, (BLE_LL_MAX_OCTETS + 14u) * 8u); + ble_wr16(d + 4, BLE_LL_MAX_OCTETS); + ble_wr16(d + 6, (BLE_LL_MAX_OCTETS + 14u) * 8u); +} + +static void ll_features(uint8_t op, uint8_t peer) +{ + uint8_t d[8]; + ble_zero(d, 8); + bll.peer_feat = peer; + bll.feat_known = 1; + d[0] = (uint8_t)(LL_OUR_FEAT & peer); /* octet 0: the features both support */ + if (op) + ll_ctrl(op, d, 8); +} + +static int ll_version_send(void) /* our LL_VERSION_IND, once per connection -> 1 queued now */ +{ + uint8_t d[5]; + if (bll.ver_sent) + return 0; + d[0] = BLE_LL_VERSION; + ble_wr16(d + 1, BLE_LL_COMPANY); + ble_wr16(d + 3, BLE_LL_SUBVERSION); + bll.ver_sent = (uint8_t)ll_ctrl(LL_VERSION_IND, d, 5); + return bll.ver_sent; +} + +/* 1 if the instant is still ahead of (or at) the current event: (instant - counter) mod 65536 < 32767 */ +static int ll_instant_ok(uint16_t instant) +{ + return (uint16_t)(instant - (uint16_t)(bll.last_evt + 1u)) < 32767u; +} + +/* a control PDU from the central (p: opcode and CtrData, n octets) */ +static void ll_rx_ctrl(const uint8_t *p, uint8_t n) +{ + static const uint8_t LEN[] = {12, 8, 2, 23, 13, 1, 1, 2, 9, 9, 1, 1, 6, 2, 9, 24, 24, 3, 1, 1, 9, 9, 3, 3, 5, 3}; + uint8_t op = p[0], d[24]; + if (!n) + return; + BLE_DG(ble_diag_last(ble_dg.ctl_rx, &ble_dg.ctl_rx_n, op)); + ll_diag_enc(0, p, n); + ble_diag_ev(BDE_CTRL_RX, op | (uint32_t)n << 8); + if (op >= sizeof LEN || n != LEN[op]) { /* unknown, or not its length */ + ll_unknown(op); + return; + } +#if BLE_CENTRAL + if (bll.central && llc_rx_ctrl(op, p, n)) /* the master's side of the procedures (ble_ll_central.c) */ + return; +#endif + switch (op) { + case LL_CONNECTION_UPDATE_IND: { + uint16_t instant = ble_rd16(p + 10); + if (!ll_instant_ok(instant)) { + ll_close(BLE_ERR_INSTANT_PASSED); + return; + } + bll.upd.win_size = p[1]; + bll.upd.win_offset = ble_rd16(p + 2); + bll.upd.interval = ble_rd16(p + 4); + bll.upd.latency = 0; + bll.upd.timeout = ble_rd16(p + 8); + bll.upd.instant = instant; + if (!ll_params_ok(bll.upd.interval, ble_rd16(p + 6), bll.upd.timeout)) { + ll_close(BLE_ERR_INVALID_LL_PARAMS); + return; + } + bll.upd_pending = 1; + ble_hw_conn_update(&bll.upd); + if (bll.rproc == P_UPD) + bll.rproc = P_NONE; + return; + } + case LL_CHANNEL_MAP_IND: { + struct ble_chmap m; + uint16_t instant = ble_rd16(p + 6); + if (!ll_instant_ok(instant)) { + ll_close(BLE_ERR_INSTANT_PASSED); + return; + } + ble_cpy(bll.new_chm, p + 1, 5); + bll.new_chm[4] &= 0x1Fu; + if (!ble_chmap_set(&m, bll.new_chm)) { + ll_close(BLE_ERR_INVALID_LL_PARAMS); + return; + } + bll.chm_instant = instant; + bll.chm_pending = 1; + ble_hw_chmap_update(bll.new_chm, instant); + return; + } + case LL_TERMINATE_IND: + bll.term_rx = 1; /* closed after this event: the engine acknowledges it */ + bll.term_reason = p[1]; + return; + case LL_FEATURE_REQ: + ll_features(LL_FEATURE_RSP, p[1]); + return; + case LL_FEATURE_RSP: + ll_features(0, p[1]); + if (bll.lproc == P_FEAT) + bll.lproc = P_NONE; + return; + case LL_VERSION_IND: + if (bll.lproc == P_VER) + bll.lproc = P_NONE; /* (the answer to ours, as master) */ + ll_version_send(); /* once per connection */ + return; + case LL_PING_REQ: + ll_ctrl(LL_PING_RSP, d, 0); + return; + case LL_LENGTH_REQ: + ll_lengths(p + 1); + ll_our_lengths(d); + ll_ctrl(LL_LENGTH_RSP, d, 8); + return; + case LL_LENGTH_RSP: + ll_lengths(p + 1); + if (bll.lproc == P_LEN) + bll.lproc = P_NONE; + return; + case LL_PHY_REQ: + d[0] = 1u; /* LE 1M only, both ways */ + d[1] = 1u; + ll_ctrl(LL_PHY_RSP, d, 2); + bll.rproc = P_PHY; + bll.rproc_t = ble_hw_time_us(); + return; + case LL_PHY_UPDATE_IND: + if (bll.rproc == P_PHY) + bll.rproc = P_NONE; + if ((p[1] | p[2]) & ~1u) /* anything but 1M (0: no change): we cannot follow */ + ll_close(BLE_ERR_UNSUPP_REMOTE); + return; + case LL_CONNECTION_PARAM_REQ: + if (!ll_params_ok(ble_rd16(p + 3), ble_rd16(p + 5), ble_rd16(p + 7)) || ble_rd16(p + 1) > ble_rd16(p + 3) || + ble_rd16(p + 1) < 6u) { + ll_reject(op, BLE_ERR_INVALID_LL_PARAMS); + return; + } + if (ble_host_audio() && ble_rd16(p + 3) < BLE_CONN_AUDIO_MIN) { /* (Bluetooth audio streams: a faster interval + * leaves it short of air, ble_host.c) */ + ll_reject(op, BLE_ERR_UNACCEPT_PARAMS); + return; + } + ll_ctrl(LL_CONNECTION_PARAM_RSP, p + 1, 23); /* accepted as asked */ + bll.rproc = P_UPD; + bll.rproc_t = ble_hw_time_us(); + return; + case LL_UNKNOWN_RSP: + case LL_REJECT_IND: + case LL_REJECT_EXT_IND: + if (bll.lproc == P_FEAT || bll.lproc == P_LEN) + bll.lproc = P_NONE; /* the central does not do it: carry on without */ + if (op == LL_UNKNOWN_RSP && p[1] == LL_PERIPHERAL_FEATURE_REQ) + bll.feat_known = 1; + if (op == LL_UNKNOWN_RSP && p[1] == LL_LENGTH_REQ) + bll.len_done = 1; + return; +#if BLE_LL_ENC + case LL_ENC_REQ: { + uint8_t ltk[16], skd[16], i; + bll.tx_paused = 1; + ble_hw_rand(d, 12); /* SKDs (8), IVs (4) */ + ll_ctrl(LL_ENC_RSP, d, 12); + if (!ble_host_ltk(p + 1, ble_rd16(p + 9), ltk)) { + bll.tx_paused = 0; + ll_reject(op, BLE_ERR_PIN_KEY_MISSING); + return; + } + for (i = 0; i < 8u; i++) { /* SKD = SKDs || SKDm, most significant octet first */ + skd[i] = d[7 - i]; + skd[8 + i] = p[11 + 7 - i]; + } + for (i = 0; i < 16u; i++) + bll.ccm_rx.key[i] = ltk[15 - i]; + ble_aes128(bll.ccm_rx.key, skd, bll.ccm_rx.key); + ble_cpy(bll.ccm_rx.iv, p + 19, 4); /* IV = IVm || IVs */ + ble_cpy(bll.ccm_rx.iv + 4, d + 8, 4); + bll.ccm_rx.ctr = 0; + bll.ccm_rx.ctr_hi = 0; + bll.ccm_tx = bll.ccm_rx; + bll.ccm_rx.dir = 1; + bll.ccm_tx.dir = 0; + ll_ctrl(LL_START_ENC_REQ, d, 0); + bll.enc_rx = 1; + bll.rproc = P_ENC; + bll.rproc_t = ble_hw_time_us(); + return; + } + case LL_START_ENC_RSP: + if (bll.rproc != P_ENC || !bll.enc_rx) + return; + bll.enc_tx = 1; + ll_ctrl(LL_START_ENC_RSP, d, 0); + bll.tx_paused = 0; + bll.rproc = P_NONE; + BLE_DG(ble_dg.enc_on_n++); + ble_host_encrypted(); /* (SMP: the key distribution may start) */ + return; +#else + case LL_ENC_REQ: + ll_reject(op, BLE_ERR_UNSUPP_REMOTE); + return; +#endif + default: /* peripheral-to-central PDUs, PAUSE_ENC, ... */ + ll_unknown(op); + return; + } +} + +BLE_API void ble_ll_hw_rx(const uint8_t *pdu, uint8_t len) +{ + uint8_t n, llid; + const uint8_t *p = pdu + 2; + if (bll.state != LL_CONN || len < 2u || pdu[1] > len - 2u) + return; + n = pdu[1]; + llid = pdu[0] & 3u; + bll.established = 1; +#if BLE_LL_ENC + if (bll.enc_rx && n) { + if (n > 4u + BLE_LL_MAX_OCTETS) + return; + ble_cpy(bll.rxbuf, p, n); + if (!ble_ccm_decrypt(&bll.ccm_rx, pdu[0], bll.rxbuf, n)) { + ll_close(BLE_ERR_MIC_FAILURE); + return; + } + p = bll.rxbuf; + n = (uint8_t)(n - 4u); + } +#endif + if (n > BLE_LL_MAX_OCTETS) + return; + if (llid == 3u) + ll_rx_ctrl(p, n); + else if (llid && n && bll.lproc != P_TERM) + ble_host_rx(p, n, llid == 2u); +} + +/* our own procedures, one at a time, once the link is up: the feature exchange, then the data length */ +static void ll_start_procs(uint32_t now) +{ + uint8_t d[8]; + if (bll.lproc != P_NONE || !bll.established) + return; +#if BLE_CENTRAL + if (bll.central) { + llc_start_procs(now); /* as master: version, features, encryption, data length */ + return; + } +#endif + if (BLE_LL_MAX_OCTETS > 27u && !bll.len_done && (!bll.feat_known || (bll.peer_feat & BLE_FEAT_DLE)) && + (uint16_t)(bll.last_evt + 1u) >= 6u) { + ll_our_lengths(d); /* long packets asked for first, before the feature exchange (the screen + * mirror over Bluetooth ran at 27 octets an event, 2026-10-23); a central + * without them answers LL_UNKNOWN_RSP: len_done */ + if (ll_ctrl(LL_LENGTH_REQ, d, 8)) { + bll.lproc = P_LEN; + bll.lproc_t = now; + } + } else if (!bll.feat_known && BLE_LL_PERIPH_FEAT && (uint16_t)(bll.last_evt + 1u) >= 6u) { + ble_zero(d, 8); + d[0] = (uint8_t)LL_OUR_FEAT; + if (ll_ctrl(LL_PERIPHERAL_FEATURE_REQ, d, 8)) { + bll.lproc = P_FEAT; + bll.lproc_t = now; + } + } else if (BLE_LL_MAX_OCTETS > 27u && bll.feat_known && !bll.len_done && (bll.peer_feat & BLE_FEAT_DLE)) { + ll_our_lengths(d); + if (ll_ctrl(LL_LENGTH_REQ, d, 8)) { + bll.lproc = P_LEN; + bll.lproc_t = now; + } + } +} + +BLE_API void ble_ll_hw_event_end(uint16_t counter, uint8_t rx_ok) +{ + uint32_t now = ble_hw_time_us(); + if (bll.state != LL_CONN) + return; + bll.last_evt = counter; + if (rx_ok) { + bll.t_rx = now; + bll.established = 1; + } + if (bll.term_rx) { + ll_close_by(bll.term_reason, BDC_PEER); + return; + } + if (bll.upd_pending && (uint16_t)(counter - bll.upd.instant) < 0x8000u) { + bll.upd_pending = 0; /* the instant's event is over: the new parameters hold */ + bll.interval = bll.upd.interval; + bll.timeout = bll.upd.timeout; + bll.t_rx = now; /* (the supervision timer starts again with them) */ + if (bll.lproc == P_UPD) + bll.lproc = P_NONE; /* (ours, as master: done at its instant) */ + } + if (bll.chm_pending && (uint16_t)(counter - bll.chm_instant) < 0x8000u) { + bll.chm_pending = 0; + ble_cpy(bll.chm, bll.new_chm, 5); + if (bll.lproc == P_UPD) + bll.lproc = P_NONE; + } + if (!bll.established) { /* six intervals after the transmit window, nothing heard */ + if (now - bll.t_start > (1u + bll.win_offset + bll.win_size + 6u * (uint32_t)bll.interval) * 1250u) { + ll_close_by(BLE_ERR_CONN_FAILED, BDC_ESTABLISH); + return; + } + } else if (now - bll.t_rx > (uint32_t)bll.timeout * 10000u) { + ll_close_by(BLE_ERR_CONN_TIMEOUT, BDC_SUPERVISION); + return; + } + if (bll.lproc == P_TERM && now - bll.lproc_t > (uint32_t)bll.timeout * 10000u) { + ll_close_by(BLE_ERR_LOCAL_HOST, BDC_TERM_UNACKED); /* our LL_TERMINATE_IND never acknowledged */ + return; + } + if ((bll.lproc != P_NONE && bll.lproc != P_TERM && now - bll.lproc_t > LL_PROC_US) || + (bll.rproc != P_NONE && now - bll.rproc_t > LL_PROC_US)) { + ll_close_by(BLE_ERR_LL_RSP_TIMEOUT, BDC_PROC_TIMEOUT); + return; + } + ll_start_procs(now); + if (bll.lproc != P_TERM) + ble_host_event(); +} diff --git a/platform/ble/ble_ll.h b/platform/ble/ble_ll.h new file mode 100644 index 0000000..fa79ad3 --- /dev/null +++ b/platform/ble/ble_ll.h @@ -0,0 +1,100 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The link layer (one connection, LE 1M; the peripheral, and with BLE_CENTRAL the master): its side towards the + * host. The driver side is ble_hw.h. Everything runs in the BLE interrupts' context (ble_hw.h): the host's + * callbacks below are called from there, and the host calls ble_ll_send() etc. from there too. */ +#ifndef BLE_LL_H +#define BLE_LL_H +#include +#include "ble_cfg.h" + +/* LL control opcodes (Core Vol 6 Part B 2.4.2) */ +enum { + LL_CONNECTION_UPDATE_IND = 0x00, LL_CHANNEL_MAP_IND = 0x01, LL_TERMINATE_IND = 0x02, LL_ENC_REQ = 0x03, + LL_ENC_RSP = 0x04, LL_START_ENC_REQ = 0x05, LL_START_ENC_RSP = 0x06, LL_UNKNOWN_RSP = 0x07, + LL_FEATURE_REQ = 0x08, LL_FEATURE_RSP = 0x09, LL_PAUSE_ENC_REQ = 0x0A, LL_PAUSE_ENC_RSP = 0x0B, + LL_VERSION_IND = 0x0C, LL_REJECT_IND = 0x0D, LL_PERIPHERAL_FEATURE_REQ = 0x0E, LL_CONNECTION_PARAM_REQ = 0x0F, + LL_CONNECTION_PARAM_RSP = 0x10, LL_REJECT_EXT_IND = 0x11, LL_PING_REQ = 0x12, LL_PING_RSP = 0x13, + LL_LENGTH_REQ = 0x14, LL_LENGTH_RSP = 0x15, LL_PHY_REQ = 0x16, LL_PHY_RSP = 0x17, LL_PHY_UPDATE_IND = 0x18, + LL_MIN_USED_CHANNELS_IND = 0x19 +}; +/* error codes (Core Vol 1 Part F) the link layer uses */ +enum { + BLE_ERR_UNKNOWN_CMD = 0x01, BLE_ERR_PIN_KEY_MISSING = 0x06, BLE_ERR_CONN_TIMEOUT = 0x08, + BLE_ERR_REMOTE_USER = 0x13, BLE_ERR_LOCAL_HOST = 0x16, BLE_ERR_UNSUPP_REMOTE = 0x1A, + BLE_ERR_INVALID_LL_PARAMS = 0x1E, BLE_ERR_LL_RSP_TIMEOUT = 0x22, BLE_ERR_INSTANT_PASSED = 0x28, + BLE_ERR_UNSPECIFIED = 0x1F, BLE_ERR_UNACCEPT_PARAMS = 0x3B, BLE_ERR_MIC_FAILURE = 0x3D, BLE_ERR_CONN_FAILED = 0x3E +}; +/* feature bits we may claim (FeatureSet, octet 0 bits) */ +#define BLE_FEAT_ENC (1u << 0) +#define BLE_FEAT_CONN_PARAM (1u << 1) +#define BLE_FEAT_EXT_REJECT (1u << 2) +#define BLE_FEAT_PERIPH_FEAT (1u << 3) +#define BLE_FEAT_PING (1u << 4) +#define BLE_FEAT_DLE (1u << 5) + +/* ---- the host asks ---- */ +BLE_API void ble_ll_init(const uint8_t addr[6], uint8_t addr_random); /* addr least significant octet first */ +/* the AD structures of the advertisement and of the scan response (each at most 31 octets) */ +BLE_API void ble_ll_set_adv_data(const uint8_t *ad, uint8_t ad_len, const uint8_t *sr, uint8_t sr_len); +/* advertise whenever not connected (1), or stop advertising and leave any connection (0) */ +BLE_API void ble_ll_enable(int on); +BLE_API int ble_ll_connected(void); +/* queue one L2CAP basic frame for channel cid (payload n octets): 1 queued, 0 no room (nothing queued) */ +BLE_API int ble_ll_send(uint16_t cid, const uint8_t *p, uint16_t n); +/* the payload octets a frame queued now could carry (0 when not connected) */ +BLE_API uint32_t ble_ll_tx_room(void); +/* leave the connection: LL_TERMINATE_IND with reason, then ble_host_disconnected(BLE_ERR_LOCAL_HOST) */ +BLE_API void ble_ll_disconnect(uint8_t reason); +BLE_API uint16_t ble_ll_interval(void); /* connInterval in use (x 1.25 ms), 0 when not connected */ +BLE_API uint16_t ble_ll_timeout(void); /* the supervision timeout in use (x 10 ms), 0 when not connected */ +BLE_API uint8_t ble_ll_peer_features(void); /* the central's FeatureSet octet 0 (0 until exchanged) */ +BLE_API uint8_t ble_ll_tx_octets(void); /* the data length we send (27 .. 251), 0 when not connected */ +BLE_API uint16_t ble_ll_peer_len(uint32_t i); /* the central's last LL_LENGTH values: 0 MaxRxOctets, 1 MaxRxTime (us), + * 2 MaxTxOctets, 3 MaxTxTime; 0 before one came */ +/* our address and the central's (its CONNECT_IND's InitA), least significant octet first; bit 0: ours is random, + * bit 1: the central's is random (TxAdd) */ +BLE_API uint8_t ble_ll_addrs(uint8_t own[6], uint8_t peer[6]); +BLE_API int ble_ll_encrypted(void); /* the link is encrypted both ways (0 without BLE_LL_ENC) */ +#if BLE_CENTRAL +/* scan instead of advertising while on (the DEVICES list is open), when enabled and not connected; a connection + * that ends while on goes back to scanning. Off: advertising again (when enabled). Called like ble_ll_enable */ +BLE_API void ble_ll_scan(int on); +BLE_API int ble_ll_scanning(void); +/* the main loop: the oldest raw report (pdu: room for 2 + 37) -> its length, 0 when none; *rssi its RSSI word */ +BLE_API uint8_t ble_ll_scan_take(uint8_t *pdu, uint16_t *rssi); +/* connect to a peripheral (its AdvA and TxAdd) as central: initiate until it advertises, then master of the link + * (ble_host_connected; ble_ll_central() 1). 0: not now (off or connected). Called like ble_ll_enable */ +BLE_API int ble_ll_connect(const uint8_t peer[6], uint8_t peer_rand); +BLE_API void ble_ll_connect_cancel(void); /* stop initiating: advertise (or scan) again */ +BLE_API int ble_ll_initiating(void); +BLE_API int ble_ll_central(void); /* connected, and we are the master */ +/* as master: a connection update to an interval in [imin, imax] (ours when it fits) / a channel map update, each at + * an instant (HW §21.4) -> 1 started now */ +BLE_API int ble_ll_conn_update(uint16_t imin, uint16_t imax, uint16_t timeout); +BLE_API int ble_ll_chmap_update(const uint8_t chm[5]); +#if BLE_CEN_PAIR +/* as master: start the encryption with this key (EDIV / Rand: 0 for a pairing's STK) */ +BLE_API void ble_ll_start_enc(const uint8_t ltk[16], const uint8_t rand[8], uint16_t ediv); +#endif +#endif + +/* ---- the link layer tells the host (ble_l2cap.c) ---- */ +BLE_API void ble_host_connected(void); +BLE_API void ble_host_disconnected(uint8_t reason); +BLE_API int ble_host_audio(void); /* Bluetooth audio streams: a central's faster interval refused */ +/* a data PDU's payload: start = 1 for the start of an L2CAP frame (LLID 10b), 0 for a continuation */ +BLE_API void ble_host_rx(const uint8_t *p, uint8_t len, uint8_t start); +/* once per connection event, after the link layer's own work: the host may queue frames */ +BLE_API void ble_host_event(void); +#if BLE_LL_ENC +/* the LTK (least significant octet first) for Rand and EDIV from LL_ENC_REQ: 1 found, 0 none */ +BLE_API int ble_host_ltk(const uint8_t rand[8], uint16_t ediv, uint8_t ltk[16]); +/* the encryption started (our LL_START_ENC_RSP queued: the link is encrypted both ways from here) */ +BLE_API void ble_host_encrypted(void); +#if BLE_CEN_PAIR +/* as master: the peripheral refused our LL_ENC_REQ (err: PIN or Key Missing 0x06 when it lost the bond) */ +BLE_API void ble_host_enc_failed(uint8_t err); +#endif +#endif + +#endif diff --git a/platform/ble/ble_ll_central.c b/platform/ble/ble_ll_central.c new file mode 100644 index 0000000..9bcba94 --- /dev/null +++ b/platform/ble/ble_ll_central.c @@ -0,0 +1,536 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The link layer's central role (BLE_CENTRAL; Core Specification Vol 6 Part B, docs/BLE-STACK.md §9.1, HW §21), + * part of ble_ll.c (included there: it shares bll and the TX queues): + * - scanning for the DEVICES list: the raw reports' ring between the RX interrupt and the main loop (4.4.3); + * - initiating: our CONNECT_IND built before the engine starts (2.3.3.1; the access address by 2.1.2, a random + * CRCInit, WinSize 2, WinOffset in [Interval / 2, Interval - 1], Hop 5..16, all 37 channels), the engine sends it + * to the one target (HW §21.3), the driver turns the link into the master (ble_ll_hw_master_start); + * - the master's side of the control procedures (5.1): we start the version exchange, the feature exchange, the + * encryption (LL_ENC_REQ with a bond's or a pairing's key) and the data length; we answer the peripheral's + * feature exchange, its connection parameters request (with an LL_CONNECTION_UPDATE_IND at an instant 8..11 + * events ahead, HW §21.4), its PHY request (no change: 1M only); connection and channel map updates we start + * (ble_ll_conn_update, ble_ll_chmap_update). The rest (TX / RX, acknowledgement, supervision, termination) is + * the peripheral's code: the engine's TX and RX rules are the same in states 6 and 7 (HW §21.4). */ + +/* (defined further down ble_ll.c) */ +static void ll_features(uint8_t op, uint8_t peer); +static void ll_lengths(const uint8_t *d); +static void ll_our_lengths(uint8_t *d); +static int ll_version_send(void); +static void ll_rx_ctrl(const uint8_t *p, uint8_t n); + +/* ------------------------------------------------------------------------------------------- scanning --- */ + +#define LL_REP_MAX (2u + 37u) +static struct { + uint8_t pdu[BLE_SCAN_RING][LL_REP_MAX], len[BLE_SCAN_RING]; + uint16_t rssi[BLE_SCAN_RING]; + volatile uint32_t w, r; /* free-running: w the RX interrupt's, r the main loop's */ +} bscan; + +static void ll_scan_start(void) +{ + struct ble_hw_scan s; + s.interval = BLE_SCAN_INTERVAL; + s.window = BLE_SCAN_WINDOW; + s.active = BLE_SCAN_ACTIVE; + s.own = bll.addr; + s.own_rand = bll.addr_rand; + bll.state = LL_SCAN; + ble_hw_scan_start(&s); +} + +BLE_API int ble_ll_scanning(void) { return bll.state == LL_SCAN; } + +/* RX interrupt: only ADV_IND and SCAN_RSP can make a list entry (ble_scan.c); the rest is dropped here */ +BLE_API void ble_ll_hw_adv_report(const uint8_t *pdu, uint8_t len, uint16_t rssi, uint8_t ch) +{ + uint32_t i, t = pdu[0] & 0x0Fu; + (void)ch; + if (bll.state != LL_SCAN || len < 8u || len > LL_REP_MAX) + return; + if (t != 0x0u && t != 0x4u) { + BLE_DG(ble_dgs.rep_other++); + return; + } + if (bscan.w - bscan.r >= BLE_SCAN_RING) { + BLE_DG(ble_dgs.ring_full++); + return; + } + if (t == 0x0u) + BLE_DG(ble_dgs.rep_adv_ind++); + else + BLE_DG(ble_dgs.rep_scan_rsp++); + i = bscan.w & (BLE_SCAN_RING - 1u); + ble_cpy(bscan.pdu[i], pdu, len); + bscan.len[i] = len; + bscan.rssi[i] = rssi; + BLE_BARRIER(); /* the slot before the index */ + bscan.w++; +} + +BLE_API uint8_t ble_ll_scan_take(uint8_t *pdu, uint16_t *rssi) +{ + uint32_t i; + uint8_t n; + if (bscan.r == bscan.w) + return 0; + BLE_BARRIER(); /* the index before the slot */ + i = bscan.r & (BLE_SCAN_RING - 1u); + n = bscan.len[i]; + ble_cpy(pdu, bscan.pdu[i], n); + *rssi = bscan.rssi[i]; + BLE_BARRIER(); + bscan.r++; + return n; +} + +BLE_API void ble_ll_scan(int on) +{ + bll.scan_want = on ? 1u : 0u; + if (on && bll.enabled && bll.state == LL_ADV) { + ble_hw_adv_stop(); /* one link: advertising stops, the scan takes the link */ + ll_scan_start(); + } else if (on && bll.enabled && bll.state == LL_OFF) + ll_scan_start(); + else if (!on && bll.state == LL_SCAN) { + ble_hw_scan_stop(); + bll.state = LL_OFF; + if (bll.enabled) + ll_adv_start(); + } /* (initiating or connected: only the wish is kept) */ +} + +/* ----------------------------------------------------------------------------------------- initiating --- */ + +static struct { + uint8_t cind[2 + 34]; /* our CONNECT_IND, as the engine sends it */ + struct ble_hw_conn c; /* its LLData */ + uint8_t peer[6], peer_rand; /* the target (its AdvA as heard: an RPA stays an RPA) */ + uint8_t upd_want; /* the peripheral asked for these: an update when we are free */ + uint16_t upd_interval, upd_timeout; +#if BLE_CEN_PAIR + uint8_t enc_want, ltk[16], rand[8], skdm[8], ivm[4]; /* ble_ll_start_enc: LL_ENC_REQ when we are free */ + uint16_t ediv; + uint8_t pausing; /* our LL_PAUSE_ENC_REQ is out (a new key on an encrypted link) */ + uint8_t held[27], held_n; /* the peripheral's control PDU held while our encryption starts */ +#endif +} llc; + +static uint32_t llc_rand32(void) +{ + uint8_t b[4]; + ble_hw_rand(b, 4); + return ble_rd32(b); +} + +BLE_API int ble_ll_initiating(void) { return bll.state == LL_INIT; } +BLE_API int ble_ll_central(void) { return bll.state == LL_CONN && bll.central; } + +/* our connection's parameters (HW §21.3, ble_cfg.h BLE_CENTRAL_*), and the CONNECT_IND that carries them */ +static void llc_cind(const uint8_t peer[6], uint8_t peer_rand) +{ + static const uint8_t ALL[5] = {0xFF, 0xFF, 0xFF, 0xFF, 0x1F}; + struct ble_hw_conn *c = &llc.c; + uint8_t *p = llc.cind; + uint32_t r, k, iv = BLE_CENTRAL_INTERVAL; + for (k = 1, c->aa = llc_rand32(); !ble_aa_valid(c->aa); k++) /* the Core's rules (2.1.2), in ble_prim.c */ + c->aa = llc_rand32() ^ k * 0x9E3779B1u; /* (stirred: a generator stuck on one value still ends) */ + c->crc_init = llc_rand32() & 0xFFFFFFu; /* random, as the Core asks (the vendor keeps 0x1983AE) */ + r = llc_rand32(); + c->win_size = BLE_CENTRAL_WINSIZE; + c->win_offset = (uint16_t)(iv / 2u + r % (iv - iv / 2u)); /* [Interval / 2, Interval - 1], as the vendor */ + c->interval = (uint16_t)iv; + c->latency = 0; + c->timeout = BLE_CENTRAL_TIMEOUT; + ble_cpy(c->chm, ALL, 5); + c->hop = (uint8_t)(5u + (r >> 8) % 12u); /* 5..16 */ + c->sca = BLE_CENTRAL_SCA; + p[0] = (uint8_t)(0x05u | bll.addr_rand << 6 | (peer_rand & 1u) << 7); /* CONNECT_IND, TxAdd, RxAdd, ChSel 0 */ + p[1] = 34; + ble_cpy(p + 2, bll.addr, 6); /* InitA */ + ble_cpy(p + 8, peer, 6); /* AdvA */ + p[14] = (uint8_t)c->aa, p[15] = (uint8_t)(c->aa >> 8), p[16] = (uint8_t)(c->aa >> 16), p[17] = (uint8_t)(c->aa >> 24); + p[18] = (uint8_t)c->crc_init, p[19] = (uint8_t)(c->crc_init >> 8), p[20] = (uint8_t)(c->crc_init >> 16); + p[21] = c->win_size; + ble_wr16(p + 22, c->win_offset); + ble_wr16(p + 24, c->interval); + ble_wr16(p + 26, c->latency); + ble_wr16(p + 28, c->timeout); + ble_cpy(p + 30, c->chm, 5); + p[35] = (uint8_t)(c->hop | c->sca << 5); +} + +/* start initiating to peer (its AdvA and TxAdd): advertising or scanning stops (one link). 0: not now (off, or a + * connection is up) */ +BLE_API int ble_ll_connect(const uint8_t peer[6], uint8_t peer_rand) +{ + struct ble_hw_init in; + if (!bll.enabled || bll.state == LL_CONN) + return 0; + if (bll.state == LL_ADV) + ble_hw_adv_stop(); + else if (bll.state == LL_SCAN) + ble_hw_scan_stop(); + else if (bll.state == LL_INIT) + ble_hw_init_stop(); + llc_cind(peer, peer_rand); + ble_cpy(llc.peer, peer, 6); + llc.peer_rand = (uint8_t)(peer_rand & 1u); + in.interval = BLE_INIT_INTERVAL; + in.window = BLE_INIT_WINDOW; + in.cind = llc.cind; + in.conn = llc.c; + bll.state = LL_INIT; + BLE_DG(ble_dgc.connects++); + ble_diag_ev(BDE_INIT_START, llc.c.win_offset); + ble_hw_init_start(&in); + return 1; +} + +/* stop initiating (the caller's timeout, NONE picked): advertising or the scan again */ +BLE_API void ble_ll_connect_cancel(void) +{ + if (bll.state != LL_INIT) + return; + ble_hw_init_stop(); + bll.state = LL_OFF; + BLE_DG(ble_dgc.cancels++); + ll_idle(); +} + +/* the driver: the engine sent our CONNECT_IND and the link is the master now (event counter 0 is the first anchor) */ +BLE_API void ble_ll_hw_master_start(void) +{ + if (bll.state != LL_INIT) + return; + ll_conn_begin(&llc.c, llc.peer, llc.peer_rand, 1); + llc.upd_want = 0; +#if BLE_CEN_PAIR + llc.enc_want = llc.pausing = llc.held_n = 0; +#endif + ble_diag_ev(BDE_MASTER, llc.c.interval); + ble_host_connected(); +} + +/* ------------------------------------------------------------------------------- the master's procedures --- */ + +/* an LL_CONNECTION_UPDATE_IND from us: WinSize 1, WinOffset = Interval / 2 and the instant 8..11 events ahead (the + * vendor's plain case, HW §21.4); the driver writes the master's values at instant - 1 */ +static int llc_update(uint16_t interval, uint16_t timeout, uint32_t now) +{ + uint8_t d[11]; + uint16_t instant = (uint16_t)(bll.last_evt + 8u + llc_rand32() % 4u); + if (bll.lproc != P_NONE || bll.upd_pending || bll.chm_pending) + return 0; + d[0] = 1; + ble_wr16(d + 1, interval / 2u); + ble_wr16(d + 3, interval); + ble_wr16(d + 5, 0); + ble_wr16(d + 7, timeout); + ble_wr16(d + 9, instant); + if (!ll_ctrl(LL_CONNECTION_UPDATE_IND, d, 11)) + return 0; + bll.upd.win_size = 1; + bll.upd.win_offset = (uint16_t)(interval / 2u); + bll.upd.interval = interval; + bll.upd.latency = 0; + bll.upd.timeout = timeout; + bll.upd.instant = instant; + bll.upd_pending = 1; + bll.lproc = P_UPD; /* (done at the instant: ble_ll_hw_event_end) */ + bll.lproc_t = now; + ble_hw_conn_update(&bll.upd); + BLE_DG(ble_dgc.m_upd_tx++); + return 1; +} + +/* as master: move to a new interval in [imin, imax] (ours when it fits) with this supervision timeout -> 1 started, + * 0 not valid or not now (another procedure: kept for later when it came from the peripheral) */ +BLE_API int ble_ll_conn_update(uint16_t imin, uint16_t imax, uint16_t timeout) +{ + uint16_t iv = (uint16_t)(BLE_CENTRAL_INTERVAL < imin ? imin : BLE_CENTRAL_INTERVAL > imax ? imax : BLE_CENTRAL_INTERVAL); + if (!ble_ll_central() || imin < 6u || imin > imax || !ll_params_ok(iv, 0, timeout)) + return 0; + if (llc_update(iv, timeout, ble_hw_time_us())) + return 1; + llc.upd_want = 1; /* busy: when the current procedure is over */ + llc.upd_interval = iv; + llc.upd_timeout = timeout; + return 0; +} + +/* as master: a new channel map from the event counter + 6..9 on (HW §21.4) -> 1 started */ +BLE_API int ble_ll_chmap_update(const uint8_t chm[5]) +{ + struct ble_chmap m; + uint8_t d[7]; + uint16_t instant = (uint16_t)(bll.last_evt + 7u + llc_rand32() % 4u); + if (!ble_ll_central() || bll.lproc != P_NONE || bll.upd_pending || bll.chm_pending) + return 0; + ble_cpy(d, chm, 5); + d[4] &= 0x1Fu; + if (!ble_chmap_set(&m, d)) + return 0; + ble_wr16(d + 5, instant); + if (!ll_ctrl(LL_CHANNEL_MAP_IND, d, 7)) + return 0; + ble_cpy(bll.new_chm, d, 5); + bll.chm_instant = instant; + bll.chm_pending = 1; + bll.lproc = P_UPD; + bll.lproc_t = ble_hw_time_us(); + ble_hw_chmap_update(bll.new_chm, instant); + BLE_DG(ble_dgc.m_chm_tx++); + return 1; +} + +#if BLE_CEN_PAIR +/* as master: encrypt the link with ltk (a bond's, EDIV / Rand as the peripheral handed them out; or a pairing's STK, + * EDIV 0 / Rand 0), at the first moment no other procedure of ours runs. On a link encrypted already (a pairing + * again, with MITM, on it) the encryption is paused first (5.1.3.2), then started with the new + * key. Done: + * ble_host_encrypted(); refused: ble_host_enc_failed() */ +BLE_API void ble_ll_start_enc(const uint8_t ltk[16], const uint8_t rand[8], uint16_t ediv) +{ + if (!ble_ll_central()) + return; + ble_cpy(llc.ltk, ltk, 16); + ble_cpy(llc.rand, rand, 8); + llc.ediv = ediv; + llc.enc_want = 1; +} + +static int llc_enc_req(uint32_t now) +{ + uint8_t d[22]; + ble_cpy(d, llc.rand, 8); + ble_wr16(d + 8, llc.ediv); + ble_hw_rand(llc.skdm, 8); + ble_hw_rand(llc.ivm, 4); + ble_cpy(d + 10, llc.skdm, 8); + ble_cpy(d + 18, llc.ivm, 4); + if (!ll_ctrl(LL_ENC_REQ, d, 22)) + return 0; + llc.enc_want = 0; + bll.enc_rx = bll.enc_tx = 0; + bll.tx_paused = 1; /* no data until the encryption runs (5.1.3.1) */ + bll.lproc = P_ENC; + bll.lproc_t = now; + BLE_DG(ble_dgc.m_enc_req_tx++); + return 1; +} + +/* the encryption pause (Core Vol 6 Part B 5.1.3.2), the master's side: our LL_PAUSE_ENC_REQ (encrypted), the + * peripheral's LL_PAUSE_ENC_RSP (encrypted), then ours unencrypted and both directions plain; the encryption start + * with the new key follows at once (LL_ENC_REQ). No data meanwhile */ +static int llc_pause_req(uint32_t now) +{ + if (!ll_ctrl(LL_PAUSE_ENC_REQ, llc.ivm, 0)) + return 0; + llc.enc_want = 0; + llc.pausing = 1; + bll.tx_paused = 1; + bll.lproc = P_ENC; + bll.lproc_t = now; + BLE_DG(ble_dgc.m_pause_tx++); + return 1; +} + +static void llc_enc_failed(uint8_t err); + +static void llc_pause_rsp(void) +{ + uint8_t d[1]; + llc.pausing = 0; + BLE_DG(ble_dgc.m_pause_rsp_rx++); + bll.enc_rx = bll.enc_tx = 0; /* (ours goes unencrypted, and all after it) */ + if (!ll_ctrl(LL_PAUSE_ENC_RSP, d, 0) || !llc_enc_req(ble_hw_time_us())) + llc_enc_failed(BLE_ERR_UNSPECIFIED); +} + +/* LL_ENC_RSP: SK = e(LTK, SKDs || SKDm), IV = IVm || IVs; directionBit 1 for what we send */ +static void llc_enc_rsp(const uint8_t *p) +{ + uint8_t skd[16], i; + for (i = 0; i < 8u; i++) { /* most significant octet first */ + skd[i] = p[1 + 7 - i]; + skd[8 + i] = llc.skdm[7 - i]; + } + for (i = 0; i < 16u; i++) + bll.ccm_tx.key[i] = llc.ltk[15 - i]; + ble_aes128(bll.ccm_tx.key, skd, bll.ccm_tx.key); + ble_cpy(bll.ccm_tx.iv, llc.ivm, 4); + ble_cpy(bll.ccm_tx.iv + 4, p + 9, 4); + bll.ccm_tx.ctr = 0; + bll.ccm_tx.ctr_hi = 0; + bll.ccm_rx = bll.ccm_tx; + bll.ccm_tx.dir = 1; + bll.ccm_rx.dir = 0; + BLE_DG(ble_dgc.m_enc_rsp_rx++); +} + +static void llc_enc_failed(uint8_t err) +{ + bll.lproc = P_NONE; + bll.tx_paused = 0; + if (llc.pausing) + llc.pausing = 0; /* (the pause refused: still encrypted with the old key) */ + else + bll.enc_rx = bll.enc_tx = 0; + BLE_DG(ble_dgc.m_enc_rej++); + BLE_DG(ble_dgc.m_enc_rej_err = err); + ble_host_enc_failed(err); +} +#endif + +/* our procedures as master, one at a time once the link is up: the version exchange, the feature exchange, the + * encryption the host asked for, an update the peripheral asked for, the data length */ +static void llc_start_procs(uint32_t now) +{ + uint8_t d[8]; +#if BLE_CEN_PAIR + if (llc.held_n) { /* the peripheral's procedure held during our encryption start */ + d[0] = llc.held_n; + llc.held_n = 0; + ll_rx_ctrl(llc.held, d[0]); + } +#endif + if (!bll.ver_sent) { + if (ll_version_send()) { + bll.lproc = P_VER; + bll.lproc_t = now; + } + return; + } + if (!bll.feat_known) { + ble_zero(d, 8); + d[0] = (uint8_t)LL_OUR_FEAT; + if (ll_ctrl(LL_FEATURE_REQ, d, 8)) { + bll.lproc = P_FEAT; + bll.lproc_t = now; + } + return; + } + if (BLE_LL_MAX_OCTETS > 27u && !bll.len_done && (bll.peer_feat & BLE_FEAT_DLE)) { + ll_our_lengths(d); /* (before the encryption: else the iPhone sends its own + * LL_LENGTH_REQ across our LL_ENC_REQ, blell-dev6) */ + if (ll_ctrl(LL_LENGTH_REQ, d, 8)) { + bll.lproc = P_LEN; + bll.lproc_t = now; + } + return; + } +#if BLE_CEN_PAIR + if (llc.enc_want) { + if (bll.enc_tx) + llc_pause_req(now); /* a new key on an encrypted link: paused first */ + else + llc_enc_req(now); + return; + } +#endif + if (llc.upd_want && llc_update(llc.upd_interval, llc.upd_timeout, now)) + llc.upd_want = 0; +} + +/* a control PDU from the peripheral that the master handles otherwise -> 1 handled (else ble_ll.c's own code). While + * our encryption starts (from our LL_ENC_REQ or LL_PAUSE_ENC_REQ to its LL_START_ENC_RSP) we send nothing but that + * procedure's PDUs (Core Vol 6 Part B 5.1.3.1): a procedure the peripheral starts meanwhile is held, answered once the + * link is encrypted (the iPhone left with MIC Failure 0x3D when our LL_LENGTH_RSP came then, blell-dev6) */ +static int llc_rx_ctrl(uint8_t op, const uint8_t *p, uint8_t n) +{ + uint8_t d[8]; +#if BLE_CEN_PAIR + if (bll.lproc == P_ENC && op != LL_ENC_RSP && op != LL_START_ENC_REQ && op != LL_START_ENC_RSP && + op != LL_PAUSE_ENC_RSP && op != LL_REJECT_IND && op != LL_REJECT_EXT_IND && op != LL_UNKNOWN_RSP && + op != LL_TERMINATE_IND && n <= sizeof llc.held) { + ble_cpy(llc.held, p, n); + llc.held_n = n; + BLE_DG(ble_dgc.m_held++); + return 1; + } +#else + (void)n; +#endif + switch (op) { + case LL_CONNECTION_UPDATE_IND: /* a master's PDUs: a peripheral never sends them */ + case LL_CHANNEL_MAP_IND: + case LL_ENC_REQ: + case LL_PHY_UPDATE_IND: + case LL_FEATURE_REQ: + ll_unknown(op); + return 1; + case LL_VERSION_IND: + BLE_DG(ble_dgc.m_ver_rx++); + return 0; + case LL_FEATURE_RSP: + BLE_DG(ble_dgc.m_feat_rsp++); + return 0; + case LL_LENGTH_RSP: + BLE_DG(ble_dgc.m_len_done++); + return 0; + case LL_PERIPHERAL_FEATURE_REQ: /* the peripheral starts the feature exchange */ + ll_features(LL_FEATURE_RSP, p[1]); + return 1; + case LL_PHY_REQ: /* 1M only: LL_PHY_UPDATE_IND with no change (5.1.10) */ + BLE_DG(ble_dgc.m_phy_req_rx++); + ble_zero(d, 4); + ll_ctrl(LL_PHY_UPDATE_IND, d, 4); + return 1; + case LL_CONNECTION_PARAM_REQ: /* answered with our LL_CONNECTION_UPDATE_IND (5.1.7.2) */ + BLE_DG(ble_dgc.m_param_req_rx++); + if (!ll_params_ok(ble_rd16(p + 3), ble_rd16(p + 5), ble_rd16(p + 7)) || ble_rd16(p + 1) > ble_rd16(p + 3) || + ble_rd16(p + 1) < 6u) { + ll_reject(op, BLE_ERR_INVALID_LL_PARAMS); + return 1; + } + ble_ll_conn_update(ble_rd16(p + 1), ble_rd16(p + 3), ble_rd16(p + 7)); + return 1; + case LL_CONNECTION_PARAM_RSP: /* (we never ask) */ + return 1; +#if BLE_CEN_PAIR + case LL_ENC_RSP: + if (bll.lproc == P_ENC) + llc_enc_rsp(p); + return 1; + case LL_PAUSE_ENC_RSP: /* (encrypted): ours plain, then the start with the new key */ + if (bll.lproc == P_ENC && llc.pausing) + llc_pause_rsp(); + return 1; + case LL_START_ENC_REQ: /* (sent plain; our answer and everything after: encrypted) */ + if (bll.lproc != P_ENC) + return 1; + BLE_DG(ble_dgc.m_start_enc_rx++); + bll.enc_rx = bll.enc_tx = 1; + ll_ctrl(LL_START_ENC_RSP, d, 0); + return 1; + case LL_START_ENC_RSP: + if (bll.lproc != P_ENC || !bll.enc_rx) + return 1; + bll.lproc = P_NONE; + bll.tx_paused = 0; + BLE_DG(ble_dg.enc_on_n++); + BLE_DG(ble_dgc.m_enc_on++); + ble_host_encrypted(); + return 1; + case LL_REJECT_IND: + if (bll.lproc != P_ENC) + return 0; + llc_enc_failed(p[1]); + return 1; + case LL_REJECT_EXT_IND: + if (bll.lproc != P_ENC || (p[1] != LL_ENC_REQ && p[1] != LL_PAUSE_ENC_REQ)) + return 0; + llc_enc_failed(p[2]); + return 1; + case LL_UNKNOWN_RSP: + if (bll.lproc != P_ENC || (p[1] != LL_ENC_REQ && p[1] != LL_PAUSE_ENC_REQ)) + return 0; + llc_enc_failed(BLE_ERR_UNSUPP_REMOTE); + return 1; +#endif + default: + return 0; + } +} diff --git a/platform/ble/ble_midi.c b/platform/ble/ble_midi.c new file mode 100644 index 0000000..af815c9 --- /dev/null +++ b/platform/ble/ble_midi.c @@ -0,0 +1,234 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* BLE-MIDI packets to and from USB-MIDI event packets (ble_midi.h). */ +#include "ble_midi.h" +#include "ble_cfg.h" + +#define NO_LO 0xFFu /* no timestamp octet written in this packet yet */ + +/* octets in a USB-MIDI event packet by CIN (0, 1: reserved, cable events) */ +static const uint8_t BM_CIN_LEN[16] = {0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1}; + +/* data octets after a status (channel messages and system common) */ +static uint8_t bm_data_len(uint8_t st) +{ + if (st < 0xF0u) + return (st & 0xE0u) == 0xC0u ? 1u : 2u; /* Cx, Dx: one */ + return st == 0xF2u ? 2u : (st == 0xF1u || st == 0xF3u) ? 1u : 0u; +} + +BLE_API void ble_midi_enc_reset(struct ble_midi_enc *e) { e->sysex = 0; } + +BLE_API void ble_midi_enc_begin(struct ble_midi_enc *e, uint8_t *buf, uint16_t cap) +{ + e->buf = buf; + e->cap = cap; + e->len = 0; + e->lo = NO_LO; + e->rs = 0; +} + +BLE_API uint16_t ble_midi_enc_len(const struct ble_midi_enc *e) { return e->len > 1u ? e->len : 0; } + +/* the message's octets checked against its CIN; returns its kind: 'c' channel, 's' system common, 'r' real time, + * 'x' SysEx octets (start, continuation or end), 0 not a message */ +static char bm_kind(uint32_t cin, const uint8_t *b, uint32_t n, uint8_t open) +{ + uint32_t i, last = n - 1u; + if (cin >= 8u) + return cin == 0xFu ? (b[0] >= 0xF8u ? 'r' : b[0] == 0xF6u ? 's' : 0) + : ((b[0] >> 4) == cin && !((b[1] | (n > 2u ? b[2] : 0u)) & 0x80u) ? 'c' : 0); + if (cin == 2u || cin == 3u || (cin == 5u && b[0] != 0xF7u)) + return bm_data_len(b[0]) + 1u == n && b[0] >= 0xF1u && b[0] <= 0xF6u && b[0] != 0xF4u && b[0] != 0xF5u && + !(n > 1u && (b[1] & 0x80u)) && + !(n > 2u && (b[2] & 0x80u)) ? 's' : 0; + for (i = 0; i < n; i++) { /* SysEx: F0 only first, F7 only last (CIN 5..7), data else */ + if (b[i] == 0xF0u ? i != 0 : b[i] == 0xF7u ? (cin == 4u || i != last) : (b[i] & 0x80u) != 0) + return 0; + } + return b[0] == 0xF0u || open ? 'x' : 0; /* (a continuation needs an open SysEx) */ +} + +BLE_API int ble_midi_enc_add(struct ble_midi_enc *e, uint32_t pkt, uint32_t t_ms) +{ + uint8_t b[3], o[8], hi = (uint8_t)((t_ms >> 7) & 0x3Fu), lo = (uint8_t)(t_ms & 0x7Fu); + uint32_t cin = pkt & 15u, n = BM_CIN_LEN[cin], i, k = 0, ts = 0, fresh = e->len == 0; + char kind; + b[0] = (uint8_t)(pkt >> 8); + b[1] = (uint8_t)(pkt >> 16); + b[2] = (uint8_t)(pkt >> 24); + if (!n || !(kind = bm_kind(cin, b, n, e->sysex))) + return -1; + if (kind == 'c' && BLE_MIDI_RUNNING_STATUS && e->rs == b[0] && !fresh) { + o[k++] = (uint8_t)(0x80u | lo); /* running status: timestamp and data */ + ts = 1; + for (i = 1; i < n; i++) + o[k++] = b[i]; + } else { + for (i = 0; i < n; i++) { + if (b[i] & 0x80u) { /* every status octet (F0 and F7 too) after a timestamp */ + o[k++] = (uint8_t)(0x80u | lo); + ts = 1; + } + o[k++] = b[i]; + } + } + if (ts && !fresh) { /* the time must fit this packet's header */ + uint8_t up = (uint8_t)((e->hi + 1u) & 0x3Fu); + if (e->lo == NO_LO ? hi != e->hi : !((hi == e->hi && lo >= e->lo) || (hi == up && lo < e->lo))) + return 0; + } + if (e->len + fresh + k > e->cap) + return 0; + if (fresh) { + e->buf[e->len++] = (uint8_t)(0x80u | hi); + e->hi = hi; + } + for (i = 0; i < k; i++) + e->buf[e->len++] = o[i]; + if (ts) { + e->hi = hi; + e->lo = lo; + } + if (kind == 'x') { + e->sysex = b[n - 1u] != 0xF7u; + e->rs = 0; + } else if (kind != 'r') { + e->sysex = 0; /* (a status ends an unfinished SysEx) */ + e->rs = kind == 'c' ? b[0] : 0u; + } + return 1; +} + +/* ------------------------------------------------------------------------------------------------ decoder */ + +BLE_API void ble_midi_dec_reset(struct ble_midi_dec *d) +{ + d->rs = d->need = d->got = d->cur = d->sysex = d->sx_n = 0; +} + +static void bm_sx_put(struct ble_midi_dec *d, uint8_t b, uint16_t ts, ble_midi_sink sink, void *ctx) +{ + d->sx[d->sx_n++] = b; + if (b == 0xF7u) { /* the end: CIN 5 / 6 / 7 by the octets left */ + uint32_t pkt = 4u + d->sx_n, i; + for (i = 0; i < d->sx_n; i++) + pkt |= (uint32_t)d->sx[i] << (8u + 8u * i); + sink(ctx, pkt, ts); + d->sx_n = 0; + d->sysex = 0; + } else if (d->sx_n == 3u) { + sink(ctx, 4u | (uint32_t)d->sx[0] << 8 | (uint32_t)d->sx[1] << 16 | (uint32_t)d->sx[2] << 24, ts); + d->sx_n = 0; + } +} + +static void bm_emit(struct ble_midi_dec *d, uint16_t ts, ble_midi_sink sink, void *ctx) +{ + uint32_t st = d->cur, cin = st < 0xF0u ? st >> 4 : d->need == 2u ? 3u : d->need == 1u ? 2u : 5u; + sink(ctx, cin | st << 8 | (uint32_t)d->d[0] << 16 | (uint32_t)d->d[1] << 24, ts); + d->got = 0; + d->d[0] = d->d[1] = 0; + if (st >= 0xF0u) + d->cur = 0; /* system common: no running status */ +} + +static void bm_status(struct ble_midi_dec *d, uint8_t b, uint16_t ts, ble_midi_sink sink, void *ctx) +{ + if (b >= 0xF8u) { /* real time: anywhere, nothing else changes */ + sink(ctx, 0xFu | (uint32_t)b << 8, ts); + return; + } + if (d->sysex) { + if (b == 0xF7u) { + bm_sx_put(d, b, ts, sink, ctx); + return; + } + d->sysex = 0; /* any other status cuts the SysEx short: dropped */ + d->sx_n = 0; + } + d->got = 0; + d->d[0] = d->d[1] = 0; + if (b == 0xF0u) { + d->rs = d->cur = 0; + d->sysex = 1; + bm_sx_put(d, b, ts, sink, ctx); + return; + } + if (b == 0xF7u || b == 0xF4u || b == 0xF5u) { /* a lone F7, undefined system common */ + d->rs = d->cur = 0; + return; + } + d->cur = b; + d->need = bm_data_len(b); + d->rs = b < 0xF0u ? b : 0u; + if (!d->need) + bm_emit(d, ts, sink, ctx); /* F6 */ +} + +static void bm_data(struct ble_midi_dec *d, uint8_t b, uint16_t ts, ble_midi_sink sink, void *ctx) +{ + if (d->sysex) { + bm_sx_put(d, b, ts, sink, ctx); + return; + } + if (!d->cur) { + if (!d->rs) + return; /* a stray data octet */ + d->cur = d->rs; + d->need = bm_data_len(d->rs); + d->got = 0; + } + d->d[d->got++] = b; + if (d->got == d->need) + bm_emit(d, ts, sink, ctx); +} + +BLE_API int ble_midi_dec(struct ble_midi_dec *d, const uint8_t *p, uint16_t n, ble_midi_sink sink, void *ctx) +{ + uint32_t i, hi, lo = NO_LO, ts, after_ts = 0; + if (n < 1u || (p[0] & 0xC0u) != 0x80u) + return 0; + hi = p[0] & 0x3Fu; + ts = hi << 7; + for (i = 1; i < n; i++) { + uint8_t b = p[i]; + if (!(b & 0x80u)) { + bm_data(d, b, (uint16_t)ts, sink, ctx); + after_ts = 0; + } else if (!after_ts) { /* a timestamp octet */ + if (lo != NO_LO && (b & 0x7Fu) < lo) + hi = (hi + 1u) & 0x3Fu; + lo = b & 0x7Fu; + ts = hi << 7 | lo; + after_ts = 1; + } else { + bm_status(d, b, (uint16_t)ts, sink, ctx); + after_ts = 0; + } + } + if (!d->sysex) { /* only SysEx goes on in the next packet: a message cut */ + d->cur = 0; /* at the end is lost (running status is kept) */ + d->got = 0; + } + return 1; +} + +BLE_API uint16_t ble_midi_last_ts(const uint8_t *p, uint16_t n) +{ + uint32_t i, hi, lo = NO_LO, after_ts = 0; + if (!n) + return 0; + hi = p[0] & 0x3Fu; + for (i = 1; i < n; i++) { + if (!(p[i] & 0x80u)) + after_ts = 0; + else if (!after_ts) { + if (lo != NO_LO && (p[i] & 0x7Fu) < lo) + hi = (hi + 1u) & 0x3Fu; + lo = p[i] & 0x7Fu; + after_ts = 1; + } else + after_ts = 0; + } + return (uint16_t)(hi << 7 | (lo == NO_LO ? 0u : lo)); +} diff --git a/platform/ble/ble_midi.h b/platform/ble/ble_midi.h new file mode 100644 index 0000000..cc0ee49 --- /dev/null +++ b/platform/ble/ble_midi.h @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* BLE-MIDI packets (MIDI Association, "Specification for MIDI over Bluetooth Low Energy" 1.0) to and from + * USB-MIDI event packets, the firmware's router format: cin | status << 8 | data1 << 16 | data2 << 24 + * (cable 0; CIN 4 SysEx start / continue, 5 / 6 / 7 SysEx end with 1 / 2 / 3 octets or a single-octet + * system common, 2 / 3 system common, 8..E channel messages, F a single octet: real time). + * + * A packet: header 10hhhhhh (timestamp bits 12..7), then per message a timestamp octet 1lllllll (bits 6..0) + * and the message. Inside a packet a repeated status may be left out (running status), with or without its + * own timestamp octet; real-time messages may come anywhere, SysEx included, each after a timestamp octet. + * SysEx goes on over packets: a continuation packet holds the header and then data at once; the closing F7 + * has a timestamp octet before it. A low timestamp smaller than the one before it in the packet means the + * high part went one up. Timestamps: 13 bits of milliseconds. */ +#ifndef BLE_MIDI_H +#define BLE_MIDI_H +#include +#include "ble_cfg.h" + +/* ---- encoder: packs messages into one packet until it is full */ +struct ble_midi_enc { + uint8_t *buf; + uint16_t cap, len; + uint8_t hi, lo; /* the packet's high timestamp part, the last low part written */ + uint8_t rs; /* running status in this packet (0: none) */ + uint8_t sysex; /* a SysEx is open (it goes on in the next packet) */ +}; +/* a new packet in buf (cap octets: the ATT MTU - 3); an open SysEx stays open */ +BLE_API void ble_midi_enc_begin(struct ble_midi_enc *e, uint8_t *buf, uint16_t cap); +/* add one USB-MIDI event at t_ms (any millisecond count: 13 bits are kept). Returns 1 added, 0 no room or its + * time does not fit this packet (send it, begin a new one, add again), -1 not a message (dropped). Events must + * come in time order. */ +BLE_API int ble_midi_enc_add(struct ble_midi_enc *e, uint32_t pkt, uint32_t t_ms); +/* the packet's length, 0 if it holds nothing worth sending */ +BLE_API uint16_t ble_midi_enc_len(const struct ble_midi_enc *e); +/* forget an open SysEx (a new connection) */ +BLE_API void ble_midi_enc_reset(struct ble_midi_enc *e); + +/* ---- decoder: one packet at a time, state kept between packets (SysEx, running status) */ +typedef void (*ble_midi_sink)(void *ctx, uint32_t pkt, uint16_t ts); +struct ble_midi_dec { + uint8_t rs, need, got, d[2]; /* running status; the message being read: data octets wanted / read */ + uint8_t cur; /* its status (0: none) */ + uint8_t sysex, sx_n, sx[3]; /* inside SysEx; octets waiting for a USB-MIDI packet */ +}; +BLE_API void ble_midi_dec_reset(struct ble_midi_dec *d); +/* decode one packet: every complete message goes to sink with its 13-bit timestamp. Returns 0 for a packet + * without a valid header (ignored), else 1. */ +BLE_API int ble_midi_dec(struct ble_midi_dec *d, const uint8_t *p, uint16_t n, ble_midi_sink sink, void *ctx); +/* the 13-bit timestamp of the last timestamp octet in a packet (the header's alone when there is none) */ +BLE_API uint16_t ble_midi_last_ts(const uint8_t *p, uint16_t n); + +#endif diff --git a/platform/ble/ble_prim.c b/platform/ble/ble_prim.c new file mode 100644 index 0000000..197c3c5 --- /dev/null +++ b/platform/ble/ble_prim.c @@ -0,0 +1,92 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* Link-layer primitives (ble_prim.h), bit-serial as the Core Specification draws them (Vol 6 Part B): small, and + * only on a path the baseband engine does not cover. */ +#include "ble_prim.h" + +BLE_API uint32_t ble_crc24(uint32_t init, const uint8_t *p, uint32_t n) +{ + uint32_t reg = init & 0xFFFFFFu; + while (n--) { + uint32_t b = *p++, i; + for (i = 0; i < 8u; i++, b >>= 1) { /* each octet least significant bit first */ + uint32_t fb = ((reg >> 23) ^ b) & 1u; + reg = (reg << 1) & 0xFFFFFFu; + if (fb) + reg ^= 0x00065Bu; /* x^24 + x^10 + x^9 + x^6 + x^4 + x^3 + x + 1 */ + } + } + return reg; +} + +BLE_API void ble_crc24_air(uint32_t crc, uint8_t out[3]) +{ + uint32_t i, r = 0; + for (i = 0; i < 24u; i++) /* position 23 goes first: reverse the 24 bits */ + r |= ((crc >> i) & 1u) << (23u - i); + out[0] = (uint8_t)r; + out[1] = (uint8_t)(r >> 8); + out[2] = (uint8_t)(r >> 16); +} + +BLE_API void ble_whiten(uint8_t ch, uint8_t *p, uint32_t n) +{ + uint32_t reg = 1u, i; /* position 0 = 1, positions 1..6 = channel index MSB..LSB */ + for (i = 0; i < 6u; i++) + reg |= ((ch >> (5u - i)) & 1u) << (i + 1u); + while (n--) { + uint32_t b = *p, o = 0; + for (i = 0; i < 8u; i++) { + uint32_t r6 = (reg >> 6) & 1u; + o |= (((b >> i) & 1u) ^ r6) << i; + reg = (reg << 1) & 0x7Fu; + if (r6) + reg ^= 0x11u; /* x^7 + x^4 + 1: position 0 and position 4 take position 6 */ + } + *p++ = (uint8_t)o; + } +} + +BLE_API int ble_chmap_has(const uint8_t chm[5], uint8_t ch) +{ + return ch < 37u && (chm[ch >> 3] >> (ch & 7u)) & 1u; +} + +BLE_API int ble_chmap_set(struct ble_chmap *m, const uint8_t chm[5]) +{ + uint8_t ch; + m->n = 0; + for (ch = 0; ch < 37u; ch++) + if (ble_chmap_has(chm, ch)) + m->used[m->n++] = ch; + return m->n >= 2u; +} + +BLE_API uint8_t ble_csa1_next(uint8_t *last, uint8_t hop, const uint8_t chm[5], const struct ble_chmap *m) +{ + uint8_t un = (uint8_t)((*last + hop) % 37u); + *last = un; + if (ble_chmap_has(chm, un) || !m->n) + return un; + return m->used[un % m->n]; /* remapping index into the used channels, ascending */ +} + +BLE_API int ble_aa_valid(uint32_t aa) +{ + uint32_t i, run = 1, trans = 0, d = aa ^ BLE_ADV_AA; + if (aa == BLE_ADV_AA || !(d & (d - 1u))) /* not the advertising AA, nor one bit away from it */ + return 0; + if ((aa & 0xFFu) == (aa >> 8 & 0xFFu) && (aa & 0xFFu) == (aa >> 16 & 0xFFu) && (aa & 0xFFu) == aa >> 24) + return 0; /* four equal octets */ + for (i = 1; i < 32u; i++) { + if (((aa >> i) ^ (aa >> (i - 1u))) & 1u) { + trans++; + run = 1; + } else if (++run > 6u) + return 0; /* more than six equal bits in a row */ + } + if (trans > 24u) + return 0; + for (i = 27, trans = 0; i < 32u; i++) /* the six most significant bits: at least two transitions */ + trans += ((aa >> i) ^ (aa >> (i - 1u))) & 1u; + return trans >= 2u; +} diff --git a/platform/ble/ble_prim.h b/platform/ble/ble_prim.h new file mode 100644 index 0000000..6adbc75 --- /dev/null +++ b/platform/ble/ble_prim.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* Link-layer primitives from the Core Specification, Vol 6 Part B (LE 1M): + * CRC24 (3.1.1), data whitening (3.2), Channel Selection Algorithm #1 with the channel map (4.5.8.2), + * access-address rules (2.1.2). + * The FM-1's baseband does CRC, hopping and (as far as known) whitening itself: these are here for a driver + * whose engine leaves one of them to software, for checks, and for the tests' simulated central. */ +#ifndef BLE_PRIM_H +#define BLE_PRIM_H +#include +#include "ble_cfg.h" + +#define BLE_ADV_AA 0x8E89BED6u /* the advertising channels' access address */ +#define BLE_ADV_CRC_INIT 0x555555u + +/* CRC over a PDU (header and payload, as sent): the register after the last bit (bit 0 = position 0) */ +BLE_API uint32_t ble_crc24(uint32_t init, const uint8_t *p, uint32_t n); +/* the three CRC octets in the order they go on air (position 23 first, each octet least significant bit first) */ +BLE_API void ble_crc24_air(uint32_t crc, uint8_t out[3]); + +/* whitening (and de-whitening: the same) of n octets in place, for channel index ch (0..39) */ +BLE_API void ble_whiten(uint8_t ch, uint8_t *p, uint32_t n); + +/* the channel map: ChM as in CONNECT_IND / LL_CHANNEL_MAP_IND (37 bits, octet 0 bit 0 = channel 0) */ +struct ble_chmap { + uint8_t used[37]; /* the used channels, ascending */ + uint8_t n; /* how many (a valid map has at least 2) */ +}; +BLE_API int ble_chmap_set(struct ble_chmap *m, const uint8_t chm[5]); /* 1 valid (>= 2 used, bits 37..39 ignored) */ +BLE_API int ble_chmap_has(const uint8_t chm[5], uint8_t ch); +/* Algorithm #1: the next event's channel; *last is lastUnmappedChannel (0 before the first event) */ +BLE_API uint8_t ble_csa1_next(uint8_t *last, uint8_t hop, const uint8_t chm[5], const struct ble_chmap *m); + +/* 1 if aa is a valid data-channel access address for LE 1M (2.1.2) */ +BLE_API int ble_aa_valid(uint32_t aa); + +#endif diff --git a/platform/ble/ble_scan.c b/platform/ble/ble_scan.c new file mode 100644 index 0000000..d3634f8 --- /dev/null +++ b/platform/ble/ble_scan.c @@ -0,0 +1,244 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The AD parser and the found-devices table (ble_scan.h). Written from the Core Specification Supplement Part A + * (AD types 0x01, 0x06, 0x07, 0x08, 0x09) and Core Vol 6 Part B 2.3 (advertising PDUs). No vendor code. */ +#include "ble_scan.h" +#include "ble_host.h" /* BLE_UUID_MIDI_SVC */ +#include "ble_util.h" + +enum { SC_ADV_IND = 0, SC_SCAN_RSP = 4 }; + +BLE_API void ble_ad_parse(const uint8_t *ad, uint32_t n, struct ble_ad *out) +{ + uint32_t i = 0; + ble_zero((uint8_t *)out, sizeof *out); + while (i < n) { + uint32_t len = ad[i], k; + const uint8_t *d = ad + i + 2; + if (!len) + break; /* the significant part ends (the rest is padding) */ + if (i + 1u + len > n) { + out->bad = 1; + break; + } + switch (ad[i + 1]) { + case 0x01: + if (len >= 2u) { + out->flags = d[0]; + out->has_flags = 1; + } + break; + case 0x06: /* incomplete / complete list of 128-bit service UUIDs */ + case 0x07: + for (k = 0; k + 16u <= len - 1u; k += 16u) + if (ble_eq(d + k, BLE_UUID_MIDI_SVC, 16)) + out->midi = 1; + break; + case 0x08: + case 0x09: + if (out->name_type != 0x09u) { /* the complete name wins over a shortened one */ + out->name_type = ad[i + 1]; + out->name = d; + out->name_len = (uint8_t)(len - 1u); + } + break; + default: + break; + } + i += 1u + len; + } +} + +/* a name as the screen's Latin-1 font shows it: ASCII as it is, a two-octet UTF-8 Latin-1 character decoded, anything + * else '?'; at most BLE_NAME_MAX characters, terminated */ +static void sc_name(char *dst, const uint8_t *s, uint32_t n) +{ + uint32_t i = 0, o = 0; + while (i < n && o < BLE_NAME_MAX) { + uint8_t c = s[i++]; + if (c >= 0x20u && c < 0x7Fu) + dst[o++] = (char)c; + else if ((c == 0xC2u || c == 0xC3u) && i < n && (s[i] & 0xC0u) == 0x80u) { + uint8_t l = (uint8_t)((c & 3u) << 6 | (s[i++] & 0x3Fu)); + dst[o++] = (char)(l >= 0xA0u ? l : '?'); + } else if (c >= 0x20u || c == 0) { + if (c == 0) + break; /* (a padded name) */ + dst[o++] = '?'; + while (i < n && (s[i] & 0xC0u) == 0x80u) + i++; /* (the rest of that UTF-8 character) */ + } + } + dst[o] = 0; +} + +BLE_API void ble_scan_clear(struct ble_scan_tab *t) +{ + uint32_t gen = t->gen; + ble_zero((uint8_t *)t, sizeof *t); + t->gen = gen + 1u; +} + +static int sc_find(const struct ble_scan_tab *t, const uint8_t *a, uint8_t rnd) +{ + uint32_t i; + for (i = 0; i < BLE_SCAN_N; i++) + if (t->e[i].used && t->e[i].addr_rand == rnd && ble_eq(t->e[i].addr, a, 6)) + return (int)i; + return -1; +} + +/* a free slot, else the oldest unconfirmed one; a BLE-MIDI device may also take the slot of the listed device heard + * least recently when that one is not heard for 2 s. -1: none */ +static int sc_slot(const struct ble_scan_tab *t, int midi, uint32_t now_ms) +{ + uint32_t i; + int un = -1, old = -1; + for (i = 0; i < BLE_SCAN_N; i++) { + const struct ble_found *e = &t->e[i]; + if (!e->used) + return (int)i; + if (!e->midi && (un < 0 || e->seen_ms < t->e[un].seen_ms)) + un = (int)i; + if (e->midi && (old < 0 || e->seen_ms < t->e[old].seen_ms)) + old = (int)i; + } + if (un >= 0) + return un; + if (midi && old >= 0 && now_ms - t->e[old].seen_ms > 2000u) + return old; + return -1; +} + +static void sc_listed(struct ble_scan_tab *t, struct ble_found *e) +{ + e->midi = 1; + e->order = ++t->next_order; /* new ones go to the bottom of the list */ + t->gen++; +} + +BLE_API void ble_scan_add(struct ble_scan_tab *t, const uint8_t *pdu, uint32_t len, uint16_t rssi, uint32_t now_ms) +{ + struct ble_ad ad; + struct ble_found *e; + uint8_t type, rnd; + int i; + t->reports++; + if (len < 8u || pdu[1] < 6u || pdu[1] > 37u || len < 2u + pdu[1]) { + t->bad_ad++; + return; + } + type = (uint8_t)(pdu[0] & 0x0Fu); + rnd = (uint8_t)(pdu[0] >> 6 & 1u); /* TxAdd */ + if (type != SC_ADV_IND && type != SC_SCAN_RSP) { + t->ignored_type++; /* not connectable (or directed elsewhere): never a list entry */ + return; + } + ble_ad_parse(pdu + 8, pdu[1] - 6u, &ad); + if (ad.bad) + t->bad_ad++; + i = sc_find(t, pdu + 2, rnd); + if (i < 0) { + if (type != SC_ADV_IND) + return; /* a scan response is only news about an advertiser already seen */ + i = sc_slot(t, ad.midi, now_ms); + if (i < 0) { + t->dropped_full++; + return; + } + e = &t->e[i]; + if (e->used && e->midi) + t->gen++; /* (a listed one gave its place) */ + ble_zero((uint8_t *)e, sizeof *e); + e->used = 1; + e->addr_rand = rnd; + ble_cpy(e->addr, pdu + 2, 6); + } + e = &t->e[i]; + t->kept++; + e->seen_ms = now_ms; + if (rssi) + e->rssi = rssi; + if (e->hits < 255u) + e->hits++; + if (ad.name_type && (ad.name_type == 0x09u || e->name_type != 0x09u)) { + char nm[BLE_NAME_MAX + 1u]; + uint32_t k; + sc_name(nm, ad.name, ad.name_len); + for (k = 0; k <= BLE_NAME_MAX && nm[k] == e->name[k] && nm[k]; k++) + ; + if (nm[k] != e->name[k]) { + ble_cpy((uint8_t *)e->name, (const uint8_t *)nm, sizeof nm); + if (e->midi) + t->gen++; + } + e->name_type = ad.name_type; + } + e->kind = (uint8_t)(BLE_KIND_MIDI | (ble_eq((const uint8_t *)e->name, (const uint8_t *)"Optimist ", 9) || + ble_eq((const uint8_t *)e->name, (const uint8_t *)"FM-1 ", 5) ? + BLE_KIND_FM1 : 0u)); /* (our name; "FM-1 " is that of the builds before 2026-10-16) */ + if (ad.midi && !e->midi) + sc_listed(t, e); +} + +BLE_API void ble_scan_age(struct ble_scan_tab *t, uint32_t now_ms) +{ + uint32_t i; + for (i = 0; i < BLE_SCAN_N; i++) { + struct ble_found *e = &t->e[i]; + if (!e->used) + continue; + if (now_ms - e->seen_ms > (e->midi ? BLE_SCAN_AGE_MS : BLE_SCAN_AGE_UNCONF_MS)) { + if (e->midi) + t->gen++; + e->used = 0; + continue; + } + e->hits = (uint8_t)((e->hits + 1u) / 2u); + } +} + +BLE_API uint32_t ble_scan_list(const struct ble_scan_tab *t, uint8_t idx[BLE_SCAN_N]) +{ + uint32_t n = 0, i, k; + for (i = 0; i < BLE_SCAN_N; i++) + if (t->e[i].used && t->e[i].midi) { + for (k = n; k > 0 && t->e[idx[k - 1u]].order > t->e[i].order; k--) + idx[k] = idx[k - 1u]; /* (insertion by first-listed order) */ + idx[k] = (uint8_t)i; + n++; + } + return n; +} + +BLE_API uint32_t ble_scan_strength(uint16_t rssi) +{ + /* RSSI dBm = 21 - (RSSI2 & 63) - T[(RSSI2 >> 8) & 63] (HW §3 0x138) with T not transcribed: a bigger fine part + * or gain index is taken to mean a weaker signal [I] */ + return 255u - ((rssi & 63u) + (rssi >> 8 & 63u)); +} + +static uint32_t sc_metric(const struct ble_scan_tab *t, uint32_t i, int by_rssi) +{ + return by_rssi ? ble_scan_strength(t->e[i].rssi) : t->e[i].hits; +} + +BLE_API uint32_t ble_scan_bars(const struct ble_scan_tab *t, uint32_t i) +{ + uint8_t idx[BLE_SCAN_N]; + uint32_t n = ble_scan_list(t, idx), k, lo = 0xFFFFFFFFu, hi = 0, m; + int by_rssi = 1; + if (i >= BLE_SCAN_N || !t->e[i].used || !t->e[i].midi) + return 0; + for (k = 0; k < n; k++) + if (!t->e[idx[k]].rssi) + by_rssi = 0; /* any without an RSSI word: all by how often they were heard */ + for (k = 0; k < n; k++) { + m = sc_metric(t, idx[k], by_rssi); + lo = m < lo ? m : lo; + hi = m > hi ? m : hi; + } + if (hi == lo) + return 3; + m = sc_metric(t, i, by_rssi); + return 1u + (2u * (m - lo) + (hi - lo) / 2u) / (hi - lo); +} diff --git a/platform/ble/ble_scan.h b/platform/ble/ble_scan.h new file mode 100644 index 0000000..beefea9 --- /dev/null +++ b/platform/ble/ble_scan.h @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The scanner's software half (docs/BLE-DEVICES-DESIGN.md §2, docs/BLE-STACK.md §9.1; BLE-HW-FACTS.md §21.2): the AD structures of an + * advertising report parsed (Core Specification Supplement Part A: flags, the 128-bit service UUID lists, the + * shortened and complete local name), and the table of the devices found nearby, which the DEVICES list shows. + * + * Plain data, no radio: the link layer hands the raw reports over (ble_ll_scan_take, from the RX interrupt through a + * ring) and the main loop feeds them here. Only advertisers that are connectable (ADV_IND) and carry the BLE-MIDI + * service UUID (in the advertisement or in the scan response) are listed; an advertiser seen without it is kept + * "unconfirmed" until its scan response says, and is the first to go when the table is full. */ +#ifndef BLE_SCAN_H +#define BLE_SCAN_H +#include +#include "ble_cfg.h" + +#ifndef BLE_SCAN_N +#define BLE_SCAN_N 8u /* devices kept (listed or waiting for their scan response) */ +#endif +#ifndef BLE_SCAN_AGE_MS +#define BLE_SCAN_AGE_MS 10000u /* a listed device not heard for this long goes from the list */ +#endif +#ifndef BLE_SCAN_AGE_UNCONF_MS +#define BLE_SCAN_AGE_UNCONF_MS 3000u /* an unconfirmed one (no BLE-MIDI UUID seen yet) */ +#endif +#define BLE_NAME_MAX 16u /* a name kept (the store's too), cut longer ones */ + +/* what one report's AD structures say */ +struct ble_ad { + uint8_t flags, has_flags; /* AD type 0x01 */ + uint8_t midi; /* the BLE-MIDI service UUID in a 128-bit list (0x06 / 0x07) */ + uint8_t name_type; /* 0 none, 0x08 shortened, 0x09 complete */ + uint8_t name_len; + const uint8_t *name; /* inside the report (not terminated) */ + uint8_t bad; /* a structure ran past the end (the rest ignored) */ +}; + +enum { BLE_KIND_MIDI = 1, BLE_KIND_FM1 = 2 }; /* (the store's KIND values too) */ + +struct ble_found { + uint8_t used, midi, kind, addr_rand; + uint8_t addr[6]; /* AdvA, least significant octet first */ + uint8_t name_type; /* the best name heard: 0x09 over 0x08 */ + char name[BLE_NAME_MAX + 1u]; /* Latin-1, terminated */ + uint16_t rssi; /* the engine's last RSSI word (HW §3 RSSI2), 0: none */ + uint8_t hits; /* reports heard lately (halved every age pass): the signal without RSSI */ + uint32_t seen_ms, order; /* last heard; when first listed (the list's order) */ +}; + +struct ble_scan_tab { + struct ble_found e[BLE_SCAN_N]; + uint32_t next_order; + uint32_t gen; /* moves whenever what the list shows changes (the menu redraws) */ + uint32_t reports, kept, dropped_full, ignored_type, bad_ad; /* counters (blell) */ +}; + +BLE_API void ble_ad_parse(const uint8_t *ad, uint32_t n, struct ble_ad *out); +BLE_API void ble_scan_clear(struct ble_scan_tab *t); +/* one advertising-channel PDU (header 2 + AdvA 6 + AdvData), its RSSI word (0: none), heard at now_ms */ +BLE_API void ble_scan_add(struct ble_scan_tab *t, const uint8_t *pdu, uint32_t len, uint16_t rssi, uint32_t now_ms); +/* drop what was not heard for long; halve the hit counts (call every second or so) */ +BLE_API void ble_scan_age(struct ble_scan_tab *t, uint32_t now_ms); +/* the listed devices (BLE-MIDI ones) in the list's order: their indexes into t->e -> how many */ +BLE_API uint32_t ble_scan_list(const struct ble_scan_tab *t, uint8_t idx[BLE_SCAN_N]); +/* relative signal bars of t->e[i] among the listed ones: 3 the strongest .. 1 the weakest (0: not listed) */ +BLE_API uint32_t ble_scan_bars(const struct ble_scan_tab *t, uint32_t i); +/* a strength from the RSSI word (larger is stronger), with no gain table (HW §3 0x138, U9: [I]) */ +BLE_API uint32_t ble_scan_strength(uint16_t rssi); + +#endif diff --git a/platform/ble/ble_smp.c b/platform/ble/ble_smp.c new file mode 100644 index 0000000..6ca7240 --- /dev/null +++ b/platform/ble/ble_smp.c @@ -0,0 +1,354 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The Security Manager, peripheral (responder) side (Core Specification Vol 3 Part H); with BLE_CENTRAL 1 + * (BLE_CEN_PAIR) also the initiator, for the links we are the master of (ble_smp_init.c, included below). BLE_CENTRAL + * 3 pairs nothing as master: smp_cen_refuse. + * + * BLE_SMP_LEGACY=0: a Pairing Request gets Pairing Failed, Pairing Not Supported (3.5.5); nothing else is answered. + * BLE_SMP_LEGACY=1: LE legacy pairing with Just Works (2.3.5.2: we have no input and no output, TK = 0): + * Pairing Request -> our Pairing Response (NoInputNoOutput, no OOB, bonding if the central bonds, no MITM, no + * Secure Connections: so legacy pairing is used), then Mconfirm -> our Sconfirm = c1(TK, Srand, ...), Mrand + * (checked against Mconfirm) -> our Srand; STK = s1(TK, Srand, Mrand) cut to the key size. The central starts + * the LL encryption with the STK (EDIV 0, Rand 0: ble_host_ltk); once it runs, phase 3: we hand out our LTK, + * EDIV and Rand (Encryption Information, Master Identification) and, when the central asks for it, our identity + * (Identity Information: an IRK, Identity Address Information: our static address; we never use a private + * address, so the IRK only lets the central file us by identity: smp_own_irk), then take the central's keys: + * its IRK and identity address go to the firmware (ble_app_peer_id: what finds a device behind a resolvable + * private address, docs/BLE-DEVICES-DESIGN.md §4.3, docs/BLE-STACK.md §9.2); its LTK and CSRK are not kept (we find a returning + * central by EDIV / Rand). The bond is one key slot (ble_host_set_key) and goes to the firmware to keep across + * power-offs (ble_app_bond). + * BLE_SMP_SEC_REQ=1: a Security Request (bonding) at the start of every connection. + * Not done (as responder): the 30 s SMP timeout (a stalled pairing just waits for the next Pairing Request or the + * link's end), LE Secure Connections, passkey / OOB, signing. The initiator (ble_smp_init.c) also does legacy passkey + * entry, with us displaying, for a peripheral that needs an authenticated link. */ +#include "ble.h" +#include "ble_host.h" +#include "ble_ll.h" +#include "ble_hw.h" +#include "ble_util.h" +#include "ble_diag.h" +#if BLE_SMP_LEGACY +#include "ble_aes.h" +#endif + +enum { SMP_PAIR_REQ = 0x01, SMP_PAIR_RSP, SMP_CONFIRM, SMP_RANDOM, SMP_FAILED, SMP_ENC_INFO, SMP_MASTER_ID, + SMP_ID_INFO, SMP_ID_ADDR, SMP_SIGN_INFO, SMP_SEC_REQ }; +/* Pairing Failed reasons (3.5.5) */ +enum { SMP_E_AUTH_REQ = 0x03, SMP_E_CONFIRM = 0x04, SMP_E_NOT_SUPP = 0x05, SMP_E_KEY_SIZE = 0x06, SMP_E_CMD = 0x07, + SMP_E_UNSPEC = 0x08, SMP_E_INVALID = 0x0A }; + +static void smp_send(const uint8_t *p, uint16_t n) { ble_ll_send(L2CAP_CID_SMP, p, n); } + +static void smp_fail(uint8_t why) +{ + uint8_t f[2]; + f[0] = SMP_FAILED; + f[1] = why; + smp_send(f, 2); +} + +#if BLE_CENTRAL && !BLE_CEN_PAIR +/* BLE_CENTRAL 3: no pairing from the central role. On a link we are the master of, the peripheral's Security Request + * (it wants the link paired or encrypted) gets Pairing Failed, Pairing Not Supported (Vol 3 Part H 2.4.6, 3.5.5) and the + * host leaves the link ("FAILED: NEEDS PAIRING", ble_central_no_pairing); a responder's other PDUs cannot come, as no + * pairing of ours runs. -> 1: the link is ours (the PDU taken here), 0: the peripheral side's */ +static int smp_cen_refuse(const uint8_t *p, uint16_t n) +{ + if (!ble_ll_central()) + return 0; + if (n && p[0] == SMP_SEC_REQ) { + smp_fail(SMP_E_NOT_SUPP); + ble_central_no_pairing(0); + } + return 1; +} +#endif + +#if !BLE_SMP_LEGACY + +BLE_API void ble_smp_reset(void) {} +BLE_API void ble_smp_connected(void) {} + +BLE_API void ble_smp_rx(const uint8_t *p, uint16_t n) +{ +#if BLE_CENTRAL + if (smp_cen_refuse(p, n)) + return; +#endif + if (n && p[0] == SMP_PAIR_REQ) + smp_fail(SMP_E_NOT_SUPP); +} + +#else + +enum { S_IDLE, S_CONFIRM, S_RANDOM, S_ENC, S_KEYS }; +#define SMP_AUTH_BOND 0x01u /* AuthReq: Bonding_Flags = Bonding */ +#define SMP_AUTH_MITM 0x04u /* AuthReq: MITM protection asked */ +#define SMP_KD_ENC 0x01u /* key distribution: EncKey (LTK, EDIV, Rand) */ +#define SMP_KD_ID 0x02u /* IdKey (IRK, identity address) */ +#define SMP_KD_SIGN 0x04u /* SignKey (CSRK) */ + +static struct { + uint8_t st, key_size, bond, ours, theirs; /* S_*; the key size; bonding; our keys to send / theirs to come */ + uint8_t preq[7], pres[7]; /* the Pairing Request and Response as sent (c1) */ + uint8_t mconf[16], srand[16], stk[16]; + uint8_t irk[16], has_irk; /* the central's Identity Information, until its address comes */ +#if BLE_CEN_PAIR + uint8_t init; /* we are the initiator (the link's master: ble_smp_init.c) */ + uint8_t mrand[16]; /* our random; mconf holds the responder's confirm then */ + uint8_t tk[16]; /* the TK: 0 (Just Works) or the passkey (passkey entry) */ + uint8_t mitm, auth; /* MITM asked; the method is passkey entry */ + uint32_t t0; /* our last SMP command (the 30 s SMP timeout, 3.4) */ + struct ble_keys keys; /* the responder's keys as they come */ +#endif +} bsmp; +#if BLE_CEN_PAIR +/* the passkey on screen while a passkey pairing of ours waits for the peer's user (BLE_NO_PASSKEY: none). A variable + * of its own (a symbol): the emulator's virtual phone user reads it there (fm1-emulator FM1_BLE_PASSKEY_AT) */ +static uint32_t smp_passkey = BLE_NO_PASSKEY; +#endif + +BLE_API void ble_smp_reset(void) +{ + ble_zero((uint8_t *)&bsmp, sizeof bsmp); +#if BLE_CEN_PAIR + smp_passkey = BLE_NO_PASSKEY; +#endif +} + +BLE_API void ble_smp_connected(void) +{ + ble_smp_reset(); +#if BLE_CENTRAL + if (ble_ll_central()) + return; /* (as initiator: the host starts a pairing when one is needed; none + * at BLE_CENTRAL 3) */ +#endif +#if BLE_SMP_SEC_REQ + { + static const uint8_t req[2] = {SMP_SEC_REQ, SMP_AUTH_BOND}; + smp_send(req, 2); + } +#endif +} + +static void smp_cut(uint8_t k[16]) /* a key to the negotiated size: its most significant octets 0 */ +{ + ble_zero(k + bsmp.key_size, 16u - bsmp.key_size); +} + +static void smp_c1(const uint8_t r[16], uint8_t out[16]) +{ + static const uint8_t tk[16] = {0}; /* Just Works: TK = 0 */ + uint8_t own[6], peer[6], t = ble_ll_addrs(own, peer); +#if BLE_CEN_PAIR + if (bsmp.init) { /* the initiator's address is ours (ia), the responder's the peer's */ + ble_smp_c1(bsmp.tk, r, bsmp.preq, bsmp.pres, (uint8_t)(t & 1u), own, (uint8_t)(t >> 1 & 1u), peer, out); + return; + } +#endif + ble_smp_c1(tk, r, bsmp.preq, bsmp.pres, (uint8_t)(t >> 1 & 1u), peer, (uint8_t)(t & 1u), own, out); +} + +/* our IRK: the same at every pairing, in either role, made from our static address (no private address of ours + * exists, so it only names us). A peer that bonded us refuses a new IRK for the same identity address: macOS, + * "already paired, with a different irk ... Unpair first" (2026-10-18), and the FM-1 then asked for the passkey at + * every power-on */ +static void smp_own_irk(uint8_t irk[16]) +{ + static const uint8_t K[16] = {'O', 'p', 't', 'i', 'm', 'i', 's', 't', ' ', 'I', 'R', 'K', ' ', 'v', '1', 0}; + uint8_t own[6], peer[6], in[16]; + (void)ble_ll_addrs(own, peer); + ble_zero(in, 16); + ble_cpy(in, own, 6); + ble_aes128(K, in, irk); +} + +#if BLE_CEN_PAIR +#include "ble_smp_init.c" /* the initiator (the master of the link) */ +#endif + +static void smp_pair_req(const uint8_t *p) +{ + uint8_t *r = bsmp.pres; + ble_smp_reset(); + if (p[4] < 7u || p[4] > 16u) { + smp_fail(SMP_E_KEY_SIZE); + return; + } + bsmp.bond = (p[3] & 3u) == SMP_AUTH_BOND; + bsmp.key_size = p[4]; + ble_cpy(bsmp.preq, p, 7); + r[0] = SMP_PAIR_RSP; + r[1] = 0x03; /* IO capability: NoInputNoOutput */ + r[2] = 0x00; /* no OOB data */ + r[3] = bsmp.bond ? SMP_AUTH_BOND : 0u; /* no MITM, no Secure Connections, no keypress */ + r[4] = 16; /* our largest key size */ + r[5] = bsmp.bond ? (uint8_t)(p[5] & (SMP_KD_ENC | SMP_KD_ID | SMP_KD_SIGN)) : 0u; /* the central's: taken */ + r[6] = bsmp.bond ? (uint8_t)(p[6] & (SMP_KD_ENC | SMP_KD_ID)) : 0u; /* ours: LTK, identity */ + bsmp.theirs = r[5]; + bsmp.ours = r[6]; + smp_send(r, 7); + bsmp.st = S_CONFIRM; +} + +static void smp_confirm(const uint8_t *p) +{ + uint8_t c[17]; + ble_cpy(bsmp.mconf, p + 1, 16); + ble_hw_rand(bsmp.srand, 16); + c[0] = SMP_CONFIRM; + smp_c1(bsmp.srand, c + 1); + smp_send(c, 17); + bsmp.st = S_RANDOM; +} + +static void smp_random(const uint8_t *p) +{ + static const uint8_t tk[16] = {0}; + uint8_t c[17]; + smp_c1(p + 1, c + 1); + if (!ble_eq(c + 1, bsmp.mconf, 16)) { + bsmp.st = S_IDLE; + smp_fail(SMP_E_CONFIRM); + return; + } + c[0] = SMP_RANDOM; + ble_cpy(c + 1, bsmp.srand, 16); + smp_send(c, 17); + ble_smp_s1(tk, bsmp.srand, p + 1, bsmp.stk); /* STK = s1(TK, Srand, Mrand) */ + smp_cut(bsmp.stk); + bsmp.st = S_ENC; +} + +static void smp_done_if(void) +{ + if (bsmp.st == S_KEYS && !bsmp.theirs) + bsmp.st = S_IDLE; /* (the bond is kept already: smp_our_keys) */ +} + +/* phase 3, the link encrypted with the STK: our LTK, EDIV, Rand (made now), kept as the bond */ +static void smp_our_keys(void) +{ + uint8_t e[17], m[11]; + if (bsmp.ours & SMP_KD_ENC) { + e[0] = SMP_ENC_INFO; + ble_hw_rand(e + 1, 16); + smp_cut(e + 1); + m[0] = SMP_MASTER_ID; + ble_hw_rand(m + 1, 10); /* EDIV (2), Rand (8) */ + smp_send(e, 17); + smp_send(m, 11); + ble_host_set_key(m + 3, ble_rd16(m + 1), e + 1); + ble_app_bond(m + 3, ble_rd16(m + 1), e + 1); + } + if (bsmp.ours & SMP_KD_ID) { /* (Core Vol 3 Part H 3.6.4, 3.6.5) */ + uint8_t own[6], peer[6], t = ble_ll_addrs(own, peer); + e[0] = SMP_ID_INFO; + smp_own_irk(e + 1); + m[0] = SMP_ID_ADDR; + m[1] = (uint8_t)(t & 1u); /* 0 public, 1 random static */ + ble_cpy(m + 2, own, 6); + smp_send(e, 17); + smp_send(m, 8); + } + bsmp.ours = 0; +} + +BLE_API void ble_host_encrypted(void) +{ +#if BLE_CEN_PAIR + if (ble_ll_central()) { + smp_init_encrypted(); /* (a pairing's STK: the key distribution; a bond's LTK: done) */ + return; + } +#endif + if (bsmp.st != S_ENC) + return; /* (a returning central's LTK: nothing to do) */ + bsmp.st = S_KEYS; + smp_our_keys(); + smp_done_if(); +} + +/* the STK while a pairing waits for its encryption (the LL asks with EDIV 0, Rand 0) */ +BLE_API int ble_smp_stk(const uint8_t rand[8], uint16_t ediv, uint8_t ltk[16]) +{ + static const uint8_t zero[8] = {0}; + if (bsmp.st != S_ENC || ediv || !ble_eq(rand, zero, 8)) + return 0; + ble_cpy(ltk, bsmp.stk, 16); + return 1; +} + +static void smp_their_key(const uint8_t *p) +{ + uint8_t op = p[0]; + if (bsmp.st != S_KEYS) + return; + if (op == SMP_ID_INFO) { + ble_cpy(bsmp.irk, p + 1, 16); + bsmp.has_irk = 1; + } else if (op == SMP_ID_ADDR && bsmp.has_irk && (bsmp.theirs & SMP_KD_ID)) + ble_app_peer_id(bsmp.irk, p + 2, (uint8_t)(p[1] & 1u)); + if (op == SMP_MASTER_ID) + bsmp.theirs &= (uint8_t)~SMP_KD_ENC; /* (Encryption Information comes before it) */ + else if (op == SMP_ID_ADDR) + bsmp.theirs &= (uint8_t)~SMP_KD_ID; + else if (op == SMP_SIGN_INFO) + bsmp.theirs &= (uint8_t)~SMP_KD_SIGN; + smp_done_if(); +} + +/* the length of each command we take (0: not taken) */ +static const uint8_t SMP_LEN[12] = {0, 7, 0, 17, 17, 2, 17, 11, 17, 8, 17, 0}; + +BLE_API void ble_smp_rx(const uint8_t *p, uint16_t n) +{ + uint8_t op; + if (!n) + return; + op = p[0]; +#if BLE_CEN_PAIR + if (ble_ll_central()) { + smp_init_rx(p, n); /* we are the initiator (ble_smp_init.c) */ + return; + } +#elif BLE_CENTRAL + if (smp_cen_refuse(p, n)) + return; +#endif + if (op >= sizeof SMP_LEN || !SMP_LEN[op]) { + if (op != SMP_SEC_REQ && op != SMP_PAIR_RSP) + smp_fail(SMP_E_CMD); /* (Secure Connections' public key etc.: not supported) */ + return; + } + if (n != SMP_LEN[op]) { + bsmp.st = S_IDLE; + smp_fail(SMP_E_INVALID); + return; + } + switch (op) { + case SMP_PAIR_REQ: + smp_pair_req(p); + return; + case SMP_CONFIRM: + case SMP_RANDOM: + if (bsmp.st != (op == SMP_CONFIRM ? S_CONFIRM : S_RANDOM)) { + bsmp.st = S_IDLE; + smp_fail(SMP_E_UNSPEC); + return; + } + if (op == SMP_CONFIRM) + smp_confirm(p); + else + smp_random(p); + return; + case SMP_FAILED: + bsmp.st = S_IDLE; + return; + default: /* the central's keys (phase 3) */ + smp_their_key(p); + return; + } +} + +#endif diff --git a/platform/ble/ble_smp_init.c b/platform/ble/ble_smp_init.c new file mode 100644 index 0000000..45efefb --- /dev/null +++ b/platform/ble/ble_smp_init.c @@ -0,0 +1,309 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The Security Manager as initiator (BLE_CENTRAL 1, BLE_CEN_PAIR: we are the master of the link; Core Specification Vol 3 Part H), + * part of ble_smp.c (included there: it shares bsmp, smp_send, smp_c1, smp_cut). LE legacy pairing with bonding, and + * only when the peripheral asks (a Security Request, Insufficient Authentication / Encryption: ble_central.c). Our + * Pairing Request is always DisplayOnly, bonding + MITM (2.3.5.3, Table 2.8); the responder's IO capability picks: + * passkey entry a responder that can type (KeyboardOnly / KeyboardDisplay: a Mac, a phone) gets a passkey we show + * (0..999999, random, TK = the passkey); its user types it. The keys are authenticated (MITM + * protection, security mode 1 level 3, Vol 3 Part C 10.2.1). Asked in the first pairing, not after + * a Just Works one: macOS drops an alert that comes right after another (2026-10-18, the window + * vanished before the passkey could be typed); + * Just Works a responder that cannot type (another FM-1, most controllers): TK = 0, nothing on either screen + * of ours. Unless the host knows the peer needs MITM (mitm 1): then we refuse with Authentication + * Requirements (0x03) instead of a pairing it will refuse anyway. + * Neither side asks for Secure Connections, so legacy pairing is used: + * Pairing Request -> the responder's Pairing Response (a key size under 7 fails) -> our Mconfirm = c1(TK, Mrand, ...) + * -> its Sconfirm (with a passkey: once its user typed it) -> our Mrand -> its Srand, checked against Sconfirm -> + * STK = s1(TK, Srand, Mrand) cut to the key size -> the LL encryption with the STK started by us (EDIV 0, Rand 0) -> + * phase 3: the responder's keys first (its LTK, EDIV, Rand: the bond; its IRK and identity address: finding it again + * behind a resolvable private address), then ours (an LTK, EDIV and Rand we never use: a peripheral cannot start + * encryption; our IRK (smp_own_irk) and our static identity address) -> the keys to the firmware (ble_app_central_keys, with + * BLE_KEYS_AUTH after a passkey) and the host told (ble_central_*). + * The 30 s SMP timeout (3.4, from our last command: the user types within it) ends the link. A Pairing Failed either + * way ends the pairing (the host decides). Context: the BLE interrupts' (the passkey is read by the main loop). */ + +enum { I_RSP = 10, I_CONFIRM, I_RANDOM, I_ENC, I_KEYS }; +enum { IO_DISPLAY_ONLY = 0x00, IO_KEYBOARD_ONLY = 0x02, IO_KEYBOARD_DISPLAY = 0x04 }; + +/* (ble_central.c) */ +static void ble_central_paired(int ok, uint8_t reason, uint8_t auth); +static void ble_central_sec_req(uint8_t auth_req); +static void ble_central_encrypted(void); +static int ble_central_late_fail(uint8_t reason, int at); + +static int smp_init_busy(void) { return bsmp.init && bsmp.st >= I_RSP; } + +static void smp_init_send(const uint8_t *p, uint16_t n) +{ + smp_send(p, n); + bsmp.t0 = ble_hw_time_us(); /* (3.4: the timer restarts with each command queued) */ +} + +static void smp_init_fail(uint8_t why, int send) +{ + if (send) + smp_fail(why); + bsmp.st = S_IDLE; + smp_passkey = BLE_NO_PASSKEY; + BLE_DG(ble_dgc.si_last_fail = why); + if (send) + BLE_DG(ble_dgc.si_fail_tx++); + ble_central_paired(0, why, bsmp.auth); /* (auth: a passkey was shown) */ +} + +/* start a pairing as initiator (the host: a Security Request, an authentication error, a bond the peer lost); mitm: + * the peer needs an authenticated link (Just Works refused), else a passkey only if it can type */ +static void ble_smp_pair(int mitm) +{ + uint8_t *r = bsmp.preq; + if (smp_init_busy()) + return; + ble_smp_reset(); + bsmp.init = 1; + bsmp.mitm = (uint8_t)(mitm != 0); + r[0] = SMP_PAIR_REQ; + r[1] = IO_DISPLAY_ONLY; /* IO capability: a display (the FM-1's screen) */ + r[2] = 0x00; /* no OOB data */ + r[3] = SMP_AUTH_BOND | SMP_AUTH_MITM; /* no Secure Connections, no keypress */ + r[4] = 16; /* our largest key size */ + r[5] = SMP_KD_ENC | SMP_KD_ID; /* ours to them (initiator key distribution) */ + r[6] = SMP_KD_ENC | SMP_KD_ID; /* theirs to us (responder key distribution) */ + smp_init_send(r, 7); + bsmp.st = I_RSP; + BLE_DG(ble_dgc.si_pair_req++); + if (mitm) + BLE_DG(ble_dgc.si_mitm_req++); +} + +/* the method (2.3.5.1, Table 2.8 with us DisplayOnly and MITM asked): passkey entry when the responder can type */ +static int smp_init_passkey_method(const uint8_t *rsp) +{ + return rsp[1] == IO_KEYBOARD_ONLY || rsp[1] == IO_KEYBOARD_DISPLAY; +} + +static void smp_init_rsp(const uint8_t *p) +{ + uint8_t c[17], k[4]; + int pk = smp_init_passkey_method(p); + BLE_DG(ble_dgc.si_rsp_io = p[1]); + BLE_DG(ble_dgc.si_rsp_auth = p[3]); + if (p[4] < 7u || p[4] > 16u) { + smp_init_fail(SMP_E_KEY_SIZE, 1); + return; + } + BLE_DG(ble_dgc.si_pair_rsp++); + if (bsmp.mitm && !pk) { + smp_init_fail(SMP_E_AUTH_REQ, 1); /* (Just Works would not satisfy it: refused at once) */ + return; + } + ble_cpy(bsmp.pres, p, 7); + bsmp.key_size = p[4]; + bsmp.bond = (p[3] & 3u) == SMP_AUTH_BOND; + bsmp.ours = (uint8_t)(p[5] & bsmp.preq[5]); /* what the responder agreed to take from us / give us */ + bsmp.theirs = (uint8_t)(p[6] & bsmp.preq[6]); + if (pk) { /* passkey entry: we display, its user types (TK = the passkey) */ + ble_hw_rand(k, 4); + smp_passkey = ((uint32_t)k[0] | (uint32_t)k[1] << 8 | (uint32_t)k[2] << 16 | (uint32_t)k[3] << 24) % 1000000u; + ble_smp_passkey_tk(smp_passkey, bsmp.tk); + bsmp.auth = 1; + BLE_DG(ble_dgc.si_passkey++); + } + ble_hw_rand(bsmp.mrand, 16); + c[0] = SMP_CONFIRM; + smp_c1(bsmp.mrand, c + 1); + smp_init_send(c, 17); + bsmp.st = I_CONFIRM; +} + +static void smp_init_confirm(const uint8_t *p) +{ + uint8_t c[17]; + ble_cpy(bsmp.mconf, p + 1, 16); /* (the responder's Sconfirm: its user typed the passkey) */ + c[0] = SMP_RANDOM; + ble_cpy(c + 1, bsmp.mrand, 16); + smp_init_send(c, 17); + bsmp.st = I_RANDOM; +} + +static void smp_init_random(const uint8_t *p) +{ + static const uint8_t zero[8] = {0}; + uint8_t c[16]; + smp_c1(p + 1, c); + if (!ble_eq(c, bsmp.mconf, 16)) { /* (a passkey typed wrong ends here) */ + smp_init_fail(SMP_E_CONFIRM, 1); + return; + } + smp_passkey = BLE_NO_PASSKEY; + BLE_DG(ble_dgc.si_confirm_ok++); + ble_smp_s1(bsmp.tk, p + 1, bsmp.mrand, bsmp.stk); /* STK = s1(TK, Srand, Mrand) */ + smp_cut(bsmp.stk); + bsmp.st = I_ENC; + BLE_DG(ble_dgc.si_stk_enc++); + ble_ll_start_enc(bsmp.stk, zero, 0); +} + +/* phase 3, after theirs: our keys as agreed (none of them is ever used by us: a peripheral cannot start encryption, + * and we never use a private address), then done */ +static void smp_init_our_keys(void) +{ + uint8_t e[17], m[11]; + if (bsmp.ours & SMP_KD_ENC) { + e[0] = SMP_ENC_INFO; + ble_hw_rand(e + 1, 16); + smp_cut(e + 1); + m[0] = SMP_MASTER_ID; + ble_hw_rand(m + 1, 10); + smp_send(e, 17); + smp_send(m, 11); + BLE_DG(ble_dgc.si_keys_tx += 2); + } + if (bsmp.ours & SMP_KD_ID) { + uint8_t own[6], peer[6], t = ble_ll_addrs(own, peer); + e[0] = SMP_ID_INFO; + smp_own_irk(e + 1); + m[0] = SMP_ID_ADDR; + m[1] = (uint8_t)(t & 1u); + ble_cpy(m + 2, own, 6); + smp_send(e, 17); + smp_send(m, 8); + BLE_DG(ble_dgc.si_keys_tx += 2); + } + bsmp.ours = 0; + bsmp.st = S_IDLE; + BLE_DG(ble_dgc.si_done++); + if (bsmp.auth) + BLE_DG(ble_dgc.si_auth_done++); + if (bsmp.bond && bsmp.keys.has) { + if (bsmp.auth) + bsmp.keys.has |= BLE_KEYS_AUTH; + ble_app_central_keys(&bsmp.keys); + } + ble_central_paired(1, 0, bsmp.auth); +} + +static void smp_init_keys_if_done(void) +{ + if (bsmp.st == I_KEYS && !(bsmp.theirs & (SMP_KD_ENC | SMP_KD_ID | SMP_KD_SIGN))) + smp_init_our_keys(); +} + +/* the link encrypted (ble_host_encrypted, as master): with our STK -> the key distribution; with a bond's LTK -> the + * host carries on */ +static void smp_init_encrypted(void) +{ + if (bsmp.init && bsmp.st == I_ENC) { + bsmp.st = I_KEYS; + smp_init_keys_if_done(); + return; + } + BLE_DG(ble_dgc.si_ltk_enc++); + ble_central_encrypted(); +} + +static void smp_init_their_key(const uint8_t *p) +{ + uint8_t op = p[0]; + BLE_DG(ble_dgc.si_keys_rx++); + switch (op) { + case SMP_ENC_INFO: + ble_cpy(bsmp.keys.ltk, p + 1, 16); + return; + case SMP_MASTER_ID: + bsmp.keys.ediv = ble_rd16(p + 1); + ble_cpy(bsmp.keys.rand, p + 3, 8); + bsmp.keys.has |= BLE_KEYS_LTK; + bsmp.theirs &= (uint8_t)~SMP_KD_ENC; + break; + case SMP_ID_INFO: + ble_cpy(bsmp.keys.irk, p + 1, 16); + return; + case SMP_ID_ADDR: + ble_cpy(bsmp.keys.id, p + 2, 6); + bsmp.keys.id_rand = (uint8_t)(p[1] & 1u); + bsmp.keys.has |= BLE_KEYS_ID; + bsmp.theirs &= (uint8_t)~SMP_KD_ID; + break; + default: /* (Signing Information: not kept) */ + bsmp.theirs &= (uint8_t)~SMP_KD_SIGN; + break; + } + smp_init_keys_if_done(); +} + +/* an SMP PDU from the responder */ +static void smp_init_rx(const uint8_t *p, uint16_t n) +{ + static const uint8_t LEN[12] = {0, 0, 7, 17, 17, 2, 17, 11, 17, 8, 17, 2}; + uint8_t op = p[0], want; + if (op >= sizeof LEN || !LEN[op]) { /* a Pairing Request (a responder never sends it), SC's PDUs */ + smp_fail(SMP_E_CMD); + return; + } + if (n != LEN[op]) { + if (smp_init_busy()) + smp_init_fail(SMP_E_INVALID, 1); + return; + } + switch (op) { + case SMP_SEC_REQ: /* the peripheral asks for security: encrypt with the bond, or pair */ + BLE_DG(ble_dgc.si_sec_req_rx++); + if (!smp_init_busy()) + ble_central_sec_req(p[1]); + return; + case SMP_FAILED: + BLE_DG(ble_dgc.si_fail_rx++); + BLE_DG(ble_dgc.si_last_fail = p[1]); + if (ble_central_late_fail(p[1], !smp_init_busy() ? 0 : bsmp.st == I_RSP ? 1 : 2)) + BLE_DG(ble_dgc.si_fail_late++); /* (after the pairing: iOS did so after a Just Works one, §13.9) */ + else if (smp_init_busy()) + smp_init_fail(p[1], 0); + return; + case SMP_PAIR_RSP: + case SMP_CONFIRM: + case SMP_RANDOM: + want = op == SMP_PAIR_RSP ? I_RSP : op == SMP_CONFIRM ? I_CONFIRM : I_RANDOM; + if (!bsmp.init || bsmp.st != want) { + if (smp_init_busy()) + smp_init_fail(SMP_E_UNSPEC, 1); + return; + } + if (op == SMP_PAIR_RSP) + smp_init_rsp(p); + else if (op == SMP_CONFIRM) + smp_init_confirm(p); + else + smp_init_random(p); + return; + default: /* the responder's keys (phase 3, encrypted) */ + if (bsmp.init && bsmp.st == I_KEYS && ble_ll_encrypted()) + smp_init_their_key(p); + return; + } +} + +/* a pairing request on an encrypted link (ble_central.c: with MITM after Just Works) left unanswered this long: the + * pairing is dropped (the host makes a new link for it) -> 1 */ +#define SMP_RSP_LATE_US 5000000u +static int smp_init_rsp_late(uint32_t now) +{ + if (!bsmp.init || bsmp.st != I_RSP || now - bsmp.t0 <= SMP_RSP_LATE_US) + return 0; + bsmp.st = S_IDLE; + return 1; +} + +/* the 30 s SMP timeout (3.4): no more SMP on this link; the host ends it */ +static int smp_init_timed_out(uint32_t now) +{ + if (!smp_init_busy() || now - bsmp.t0 <= BLE_GATTC_TIMEOUT_US) + return 0; + bsmp.st = S_IDLE; + smp_passkey = BLE_NO_PASSKEY; + return 1; +} + +BLE_API uint32_t ble_central_passkey(void) +{ + return bsmp.init && smp_init_busy() ? smp_passkey : BLE_NO_PASSKEY; +} diff --git a/platform/ble/ble_stack.c b/platform/ble/ble_stack.c new file mode 100644 index 0000000..94c8f31 --- /dev/null +++ b/platform/ble/ble_stack.c @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The BLE stack as part of the firmware's unity build (felucca.c, FELUCCA_BLE=1): every stack function is static + * here (BLE_API), so what this build never calls is left out (the app is linked without --gc-sections). + * A baseband driver built as a unit of its own would need BLE_API empty instead. */ +#define BLE_API static +#include "ble_prim.c" +#if BLE_LL_ENC +#include "ble_aes.c" +#endif +#include "ble_midi.c" +#include "ble_ll.c" +#include "ble_smp.c" +#include "ble_host.c" +#include "ble_att.c" +#include "ble_store.c" /* the one remembered device (the DEVICES list's LAST) */ +#if BLE_CENTRAL +#include "ble_scan.c" /* the AD parser and the nearby devices' table */ +#include "ble_gattc.c" /* the ATT client: the peripheral's BLE-MIDI characteristic */ +#include "ble_central.c" /* connecting out: security, the client, the end of it */ +#endif +#if defined(FELUCCA_BLE_HW) +#define BLE_HW_WL82 0 /* the build brings its own driver */ +#elif defined(FELUCCA_BLE_STUB) && FELUCCA_BLE_STUB +#define BLE_HW_WL82 0 +#include "ble_hw_stub.c" /* a stand-in that never advertises (the stack alone) */ +#else +#define BLE_HW_WL82 1 +#include "ble_hw_wl82.c" /* the AC791N / WL82 baseband engine (hal/fm1_ble.h, docs/BLE-STACK.md §7) */ +#endif diff --git a/platform/ble/ble_store.c b/platform/ble/ble_store.c new file mode 100644 index 0000000..ab803a9 --- /dev/null +++ b/platform/ble/ble_store.c @@ -0,0 +1,122 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The one remembered device (ble_store.h). */ +#include "ble_store.h" +#include "ble_util.h" + +BLE_API void ble_store_reset(struct ble_dev_store *s) +{ + ble_zero((uint8_t *)s, sizeof *s); + s->mark = BLE_DEV_MARK; + s->ver = BLE_DEV_VER; + s->sel = BLE_SEL_NONE; +} + +BLE_API int ble_store_has_last(const struct ble_dev_store *s) +{ + return (s->dev.info & (BLE_DEV_USED | BLE_DEV_CENTRAL)) == (BLE_DEV_USED | BLE_DEV_CENTRAL); +} + +BLE_API int ble_store_load(struct ble_dev_store *s, const uint8_t raw[BLE_DEV_STORE_SIZE]) +{ + ble_cpy((uint8_t *)s, raw, BLE_DEV_STORE_SIZE); + if (s->mark != BLE_DEV_MARK || s->ver != BLE_DEV_VER || s->sel > BLE_SEL_LAST) { + ble_store_reset(s); + return 0; + } + if (!ble_store_has_last(s)) { /* (a role P entry cannot be LAST: the ruling) */ + ble_zero((uint8_t *)&s->dev, sizeof s->dev); + s->sel = BLE_SEL_NONE; + } + return 1; +} + +BLE_API void ble_store_save(const struct ble_dev_store *s, uint8_t raw[BLE_DEV_STORE_SIZE]) +{ + ble_cpy(raw, (const uint8_t *)s, BLE_DEV_STORE_SIZE); +} + +BLE_API void ble_store_set_last(struct ble_dev_store *s, const uint8_t addr[6], uint8_t addr_rand, const char *name, + uint8_t kind) +{ + uint32_t i; + uint8_t keep = (uint8_t)(ble_store_has_last(s) && (s->dev.info & BLE_DEV_RANDOM) == (addr_rand ? 1u : 0u) && + ble_eq(s->dev.addr, addr, 6)); + if (!keep) + ble_zero((uint8_t *)&s->dev, sizeof s->dev); + ble_cpy(s->dev.addr, addr, 6); + s->dev.info = (uint8_t)((s->dev.info & (BLE_DEV_BONDED | BLE_DEV_IRK)) | BLE_DEV_USED | BLE_DEV_CENTRAL | + (addr_rand ? BLE_DEV_RANDOM : 0u) | (kind & 3u) << BLE_DEV_KIND_SHIFT); + for (i = 0; i < BLE_NAME_MAX; i++) + s->dev.name[i] = 0; + for (i = 0; name && i < BLE_NAME_MAX && name[i]; i++) + s->dev.name[i] = name[i]; +} + +BLE_API void ble_store_set_bond(struct ble_dev_store *s, const uint8_t ltk[16], const uint8_t rand[8], uint16_t ediv, + int auth) +{ + if (!ble_store_has_last(s)) + return; + ble_cpy(s->dev.ltk, ltk, 16); + ble_cpy(s->dev.rand, rand, 8); + ble_wr16(s->dev.ediv, ediv); + s->dev.info |= BLE_DEV_BONDED; + s->dev.sec = (uint8_t)((s->dev.sec & ~BLE_DEV_SEC_AUTH) | (auth ? BLE_DEV_SEC_AUTH : 0u)); +} + +BLE_API void ble_store_drop_bond(struct ble_dev_store *s) +{ + s->dev.info &= (uint8_t)~BLE_DEV_BONDED; + s->dev.sec &= (uint8_t)~BLE_DEV_SEC_AUTH; /* (BLE_DEV_SEC_MITM kept: the new pairing asks for the passkey) */ +} + +BLE_API void ble_store_set_mitm(struct ble_dev_store *s) +{ + if (ble_store_has_last(s)) + s->dev.sec |= BLE_DEV_SEC_MITM; +} + +BLE_API void ble_store_set_id(struct ble_dev_store *s, const uint8_t irk[16], const uint8_t id[6], uint8_t id_rand) +{ + if (!ble_store_has_last(s)) + return; + ble_cpy(s->dev.irk, irk, 16); + ble_cpy(s->dev.addr, id, 6); /* the identity address replaces the RPA it was found at */ + s->dev.info = (uint8_t)((s->dev.info & ~BLE_DEV_RANDOM) | (id_rand ? BLE_DEV_RANDOM : 0u) | BLE_DEV_IRK); +} + +BLE_API void ble_store_select(struct ble_dev_store *s, uint8_t sel) +{ + s->sel = (uint8_t)(sel == BLE_SEL_LAST && ble_store_has_last(s) ? BLE_SEL_LAST : BLE_SEL_NONE); +} + +BLE_API void ble_store_forget(struct ble_dev_store *s) +{ + ble_store_reset(s); +} + +BLE_API void ble_addr_text(const uint8_t a[6], char out[15]) +{ + static const char HEX[] = "0123456789ABCDEF"; + static const uint8_t ORD[4] = {5, 4, 1, 0}; /* most significant first, the middle two left out */ + uint32_t k, o = 0; + for (k = 0; k < 4u; k++) { + out[o++] = HEX[a[ORD[k]] >> 4]; + out[o++] = HEX[a[ORD[k]] & 15u]; + if (k < 3u) + out[o++] = ':'; + if (k == 1u) + out[o++] = '.', out[o++] = '.', out[o++] = ':'; + } + out[o] = 0; +} + +BLE_API void ble_store_name(const struct ble_dev_store *s, char out[BLE_NAME_MAX + 1u]) +{ + uint32_t i; + for (i = 0; i < BLE_NAME_MAX && s->dev.name[i]; i++) + out[i] = s->dev.name[i]; + out[i] = 0; + if (!i && ble_store_has_last(s)) + ble_addr_text(s->dev.addr, out); +} diff --git a/platform/ble/ble_store.h b/platform/ble/ble_store.h new file mode 100644 index 0000000..45637ad --- /dev/null +++ b/platform/ble/ble_store.h @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The one remembered device (docs/BLE-DEVICES-DESIGN.md §3, with the user's ruling of 2026-10-09: LAST is the device + * the FM-1 itself connected to, as a central, and reconnects to; a Mac or phone that connects to the FM-1 is accepted + * as always and never becomes LAST). 70 octets at the end of the settings record (storage/project.c persist_t.ble_dev, + * the CRC-checked settings object: never the SDK's VM area 0xE7000-0xE9FFF), plus the DEVICES choice NONE / LAST. + * + * Plain data: the firmware keeps the raw octets with the settings and decodes them once at start-up (ble_store_load); + * an older record (zeros), a foreign one or a damaged one reads as "nothing remembered, NONE". */ +#ifndef BLE_STORE_H +#define BLE_STORE_H +#include +#include "ble_cfg.h" +#include "ble_scan.h" /* BLE_NAME_MAX, BLE_KIND_* */ + +#define BLE_DEV_MARK 0xB6u /* a valid store */ +#define BLE_DEV_VER 1u +#define BLE_DEV_STORE_SIZE 70u /* header 4 + entry 66 */ +enum { BLE_SEL_NONE = 0, BLE_SEL_LAST = 1 }; +/* struct ble_dev.info */ +#define BLE_DEV_RANDOM 0x01u /* addr is a random (static) address; else public */ +#define BLE_DEV_CENTRAL 0x02u /* we connected to it (role C): always set for LAST (the ruling) */ +#define BLE_DEV_BONDED 0x04u /* ltk / rand / ediv valid */ +#define BLE_DEV_IRK 0x08u /* irk valid: find it behind a resolvable private address */ +#define BLE_DEV_KIND_SHIFT 4u /* bits 4-5: BLE_KIND_MIDI / BLE_KIND_FM1 */ +#define BLE_DEV_USED 0x80u + +struct ble_dev { /* 66 octets, multi-octet fields least significant first */ + uint8_t addr[6]; /* its identity address once bonded, else its AdvA */ + uint8_t info; + char name[BLE_NAME_MAX]; /* NUL-padded (not terminated when 16 long) */ + uint8_t ltk[16]; /* the bond (its keys, taken as initiator: the next round) */ + uint8_t rand[8]; + uint8_t ediv[2]; + uint8_t irk[16]; + uint8_t sec; /* BLE_DEV_SEC_* (0 in an older record: nothing known) */ +}; +/* struct ble_dev.sec */ +#define BLE_DEV_SEC_AUTH 0x01u /* the bond is authenticated (a passkey pairing) */ +#define BLE_DEV_SEC_MITM 0x02u /* it needs an authenticated link: pair with a passkey straight away */ +struct ble_dev_store { + uint8_t mark, ver, sel, rsv; + struct ble_dev dev; +}; +_Static_assert(sizeof(struct ble_dev_store) == BLE_DEV_STORE_SIZE, "the device store is 70 octets"); + +BLE_API void ble_store_reset(struct ble_dev_store *s); +/* from the settings record's octets (zeros: an older record) -> 1 something valid was there */ +BLE_API int ble_store_load(struct ble_dev_store *s, const uint8_t raw[BLE_DEV_STORE_SIZE]); +BLE_API void ble_store_save(const struct ble_dev_store *s, uint8_t raw[BLE_DEV_STORE_SIZE]); +BLE_API int ble_store_has_last(const struct ble_dev_store *s); +/* the device we connected to becomes LAST (the one entry, replacing any other; its bond kept only when it is the same + * device again) */ +BLE_API void ble_store_set_last(struct ble_dev_store *s, const uint8_t addr[6], uint8_t addr_rand, const char *name, + uint8_t kind); +/* its bond; auth: from a passkey pairing (BLE_DEV_SEC_AUTH) */ +BLE_API void ble_store_set_bond(struct ble_dev_store *s, const uint8_t ltk[16], const uint8_t rand[8], uint16_t ediv, + int auth); +/* it needs an authenticated link (learned from its refusal after Just Works): kept until FORGET or another LAST */ +BLE_API void ble_store_set_mitm(struct ble_dev_store *s); +/* its bond refused by it (KEY: it forgot it, or never kept it): the next link pairs afresh */ +BLE_API void ble_store_drop_bond(struct ble_dev_store *s); +/* its IRK and identity address (SMP Identity Information / Identity Address Information) */ +BLE_API void ble_store_set_id(struct ble_dev_store *s, const uint8_t irk[16], const uint8_t id[6], uint8_t id_rand); +BLE_API void ble_store_select(struct ble_dev_store *s, uint8_t sel); +/* FORGET: the entry and its keys go, NONE is picked */ +BLE_API void ble_store_forget(struct ble_dev_store *s); +/* an address as shown when there is no name: "C4:7F:..:A1:B2" (14 characters, terminated) */ +BLE_API void ble_addr_text(const uint8_t a[6], char out[15]); +/* LAST's name as shown (terminated), else its address (ble_addr_text) */ +BLE_API void ble_store_name(const struct ble_dev_store *s, char out[BLE_NAME_MAX + 1u]); + +#endif diff --git a/platform/ble/ble_util.h b/platform/ble/ble_util.h new file mode 100644 index 0000000..29b0e22 --- /dev/null +++ b/platform/ble/ble_util.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* Little helpers shared by the BLE stack: little-endian fields (Bluetooth sends the least significant octet + * first) and byte copies. No C library: the firmware builds freestanding (-fno-builtin). */ +#ifndef BLE_UTIL_H +#define BLE_UTIL_H +#include + +static inline uint16_t ble_rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); } +static inline uint32_t ble_rd24(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16; } +static inline uint32_t ble_rd32(const uint8_t *p) { return ble_rd24(p) | (uint32_t)p[3] << 24; } +static inline void ble_wr16(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); +} +static inline void ble_cpy(uint8_t *d, const uint8_t *s, uint32_t n) +{ + while (n--) + *d++ = *s++; +} +static inline void ble_zero(uint8_t *d, uint32_t n) +{ + while (n--) + *d++ = 0; +} +static inline int ble_eq(const uint8_t *a, const uint8_t *b, uint32_t n) +{ + while (n--) + if (*a++ != *b++) + return 0; + return 1; +} +/* a ring's slot written / read before its index moves (one producer interrupt, one consumer: the compiler's order + * is enough on the one core both run on) */ +#ifndef BLE_BARRIER +#define BLE_BARRIER() __asm__ volatile("" ::: "memory") +#endif +static inline uint32_t ble_min(uint32_t a, uint32_t b) { return a < b ? a : b; } + +#endif diff --git a/platform/ble/ble_vm.c b/platform/ble/ble_vm.c new file mode 100644 index 0000000..367c9b4 --- /dev/null +++ b/platform/ble/ble_vm.c @@ -0,0 +1,207 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The stored RF calibration: stock V15's VM read in place, and Optimist's copy of it (ble_vm.h; docs/BLE-HW-FACTS.md + * §14, §15.4 on feat/ble-facts d907ce3). Read only: nothing here writes or erases flash. */ +#include "ble_vm.h" +#include "ble_util.h" + +_Static_assert(sizeof(struct ble_rf_trims) == BLE_RF_TRIMS_SIZE, "the four RF records: 2 + 7 + 20 + 68 bytes"); + +#define VM_CHUNK 32u +/* the candidate areas, in the order they are tried (ble_vm.h), and the mark a copy taken from each carries */ +static const uint32_t vm_cand_off[BLE_VM_NCAND] = {BLE_VM_HW, BLE_VM_HW2, BLE_VM_EMU_A, BLE_VM_EMU_B}; +static const uint32_t vm_cand_size[BLE_VM_NCAND] = {BLE_VM_HW_SIZE, BLE_VM_HW_SIZE, BLE_VM_EMU_SIZE, BLE_VM_EMU_SIZE}; +static const uint8_t vm_cand_mark[BLE_VM_NCAND] = {0xAC, 0xAD, 0xAA, 0xAB}; +static const uint16_t vm_ids[4] = {106, 107, 108, 187}; +static const uint8_t vm_lens[4] = {2, 7, 20, 68}; + +BLE_API uint32_t ble_crc16_xmodem(uint32_t crc, const uint8_t *p, uint32_t n) /* poly 0x1021, init 0 (§14.2) */ +{ + uint32_t k; + while (n--) { + crc ^= (uint32_t)*p++ << 8; + for (k = 0; k < 8u; k++) + crc = crc & 0x8000u ? (crc << 1) ^ 0x1021u : crc << 1; + crc &= 0xFFFFu; + } + return crc; +} + +static uint8_t *vm_slot(struct ble_rf_trims *t, uint32_t i) +{ + return i == 0 ? t->x106 : i == 1u ? t->x107 : i == 2u ? t->x108 : t->x187; +} + +static int vm_187_ok(const uint8_t d[68]) /* the payload's own CRC, little-endian at 64 (§14.5) */ +{ + return ble_crc16_xmodem(0, d, 64) == (uint32_t)(d[64] | d[65] << 8); +} + +BLE_API uint32_t ble_vm_cand(uint32_t i, uint32_t *size) +{ + if (i >= BLE_VM_NCAND) + return 0; + if (size) + *size = vm_cand_size[i]; + return vm_cand_off[i]; +} + +/* one record's data through the check (and into keep when wanted) -> 1 the check holds, 0 not, -1 a read failed */ +static int vm_data(ble_vm_read_fn rd, void *ctx, uint32_t at, uint32_t len, uint8_t check, uint8_t *keep) +{ + uint8_t c[VM_CHUNK]; + uint32_t pos = 0, crc = 0, k; + while (pos < len) { + k = ble_min(VM_CHUNK, len - pos); + if (rd(ctx, at + pos, c, k)) + return -1; + crc = ble_crc16_xmodem(crc, c, k); + if (keep) + ble_cpy(keep + pos, c, k); + pos += k; + } + return (crc & 0xFFu) == check; +} + +/* candidate i holds a VM: the magic, then a first record (length > 0) inside the area whose check holds. The magic + * alone is not enough: other data may sit at a candidate (UP_FM6's voices at 0x095000 on an FM-1) */ +static int vm_is_vm(ble_vm_read_fn rd, void *ctx, uint32_t i) +{ + static const uint8_t magic[4] = {0x55, 0xAA, 0xAA, 0x55}; + uint8_t m[8]; + uint32_t len; + if (rd(ctx, vm_cand_off[i], m, 8) || !ble_eq(m, magic, 4)) + return 0; + len = (uint32_t)(m[6] >> 4) | (uint32_t)m[7] << 4; + return len && 8u + len <= vm_cand_size[i] && vm_data(rd, ctx, vm_cand_off[i] + 8u, len, m[4], 0) == 1; +} + +/* the first candidate that holds a VM (the emulator, both marked: 0x093000, §14.3 step 1) */ +BLE_API uint32_t ble_vm_live(ble_vm_read_fn rd, void *ctx, uint32_t *size) +{ + uint32_t i; + for (i = 0; i < BLE_VM_NCAND; i++) + if (vm_is_vm(rd, ctx, i)) { + if (size) + *size = vm_cand_size[i]; + return vm_cand_off[i]; + } + return 0; +} + +BLE_API int ble_vm_scan(ble_vm_read_fn rd, void *ctx, struct ble_vm_info *info, struct ble_rf_trims *t, + ble_vm_visit_fn visit, void *vctx) +{ + uint8_t h[4], tmp[68]; + uint32_t size = 0, area, off = 4, id, len, i; + int ok; + ble_zero((uint8_t *)info, sizeof *info); + area = ble_vm_live(rd, ctx, &size); + info->area = area; + info->size = size; + if (!area) + return 0; + while (off + 4u <= size) { /* §14.2: records back to back from area + 4 */ + if (rd(ctx, area + off, h, 4)) { + info->read_err = 1; + break; + } + id = h[1] | (h[2] & 0x0Fu) << 8; + len = (uint32_t)(h[2] >> 4) | (uint32_t)h[3] << 4; + if (off + 4u + len > size) /* past the area: the end */ + break; + for (i = 0; i < 4u && vm_ids[i] != id; i++) + ; + ok = vm_data(rd, ctx, area + off + 4u, len, h[0], i < 4u && len == vm_lens[i] ? tmp : 0); + if (ok < 0) { + info->read_err = 1; + break; + } + if (!ok) /* the first failing check ends the log (§14.3) */ + break; + info->nrec++; + if (visit) + visit(vctx, area + off, id, len); + if (i < 4u) { /* the last valid record of an id wins */ + if (len == vm_lens[i]) { + ble_cpy(vm_slot(t, i), tmp, len); + info->have |= (uint8_t)(1u << i); + info->wrong_len &= (uint8_t)~(1u << i); + } else { + info->have &= (uint8_t)~(1u << i); + info->wrong_len |= (uint8_t)(1u << i); + } + } + off += 4u + len; + } + info->end = off; + info->ok187 = (uint8_t)((info->have & 8u) && vm_187_ok(t->x187)); + return info->have == BLE_VM_ALL && info->ok187 && !info->read_err; +} + +/* ---------------------------------------------------------------------------------------------- the copy --- */ + +static uint32_t copy_crc(const uint8_t *c) { return ble_crc16_xmodem(0, c, BLE_RF_COPY_SIZE - 2u); } + +static uint8_t vm_mark(uint32_t area) /* the mark of a copy taken from area (an unknown one: 0x093000's) */ +{ + uint32_t i; + for (i = 0; i < BLE_VM_NCAND; i++) + if (vm_cand_off[i] == area) + return vm_cand_mark[i]; + return vm_cand_mark[2]; +} + +BLE_API uint32_t ble_rf_copy_area(uint8_t mark) +{ + uint32_t i; + for (i = 0; i < BLE_VM_NCAND; i++) + if (vm_cand_mark[i] == mark) + return vm_cand_off[i]; + return 0; +} + +BLE_API int ble_rf_copy_ok(const uint8_t copy[BLE_RF_COPY_SIZE]) +{ + return ble_rf_copy_area(copy[0]) && + copy_crc(copy) == (uint32_t)(copy[BLE_RF_COPY_SIZE - 2] | copy[BLE_RF_COPY_SIZE - 1] << 8) && + vm_187_ok(copy + 1 + 29); /* (187 sits after 106, 107, 108: 2 + 7 + 20) */ +} + +BLE_API void ble_rf_copy_make(uint8_t copy[BLE_RF_COPY_SIZE], const struct ble_rf_trims *t, uint32_t area) +{ + uint32_t c; + copy[0] = vm_mark(area); + ble_cpy(copy + 1, (const uint8_t *)t, BLE_RF_TRIMS_SIZE); + c = copy_crc(copy); + copy[BLE_RF_COPY_SIZE - 2] = (uint8_t)c; + copy[BLE_RF_COPY_SIZE - 1] = (uint8_t)(c >> 8); +} + +BLE_API void ble_rf_copy_get(const uint8_t copy[BLE_RF_COPY_SIZE], struct ble_rf_trims *t) +{ + ble_cpy((uint8_t *)t, copy + 1, BLE_RF_TRIMS_SIZE); +} + +BLE_API int ble_boot_radio(int on, uint32_t boot_failed, int have_trims) +{ + return on && !boot_failed && have_trims; +} + +BLE_API int ble_rf_choose(int vm_complete, const struct ble_rf_trims *vm, uint32_t vm_area, + uint8_t copy[BLE_RF_COPY_SIZE], struct ble_rf_trims *use, int *save) +{ + *save = 0; + if (vm_complete) { /* §15.4 step 3: the VM first */ + ble_cpy((uint8_t *)use, (const uint8_t *)vm, BLE_RF_TRIMS_SIZE); /* (no struct copy: no memcpy here) */ + if (!ble_rf_copy_ok(copy) || !ble_eq(copy + 1, (const uint8_t *)vm, BLE_RF_TRIMS_SIZE)) { + ble_rf_copy_make(copy, vm, vm_area); /* step 2: kept (again) once the set is complete */ + *save = 1; + } + return BLE_RF_FROM_VM; + } + if (ble_rf_copy_ok(copy)) { /* then Optimist's copy */ + ble_rf_copy_get(copy, use); + return BLE_RF_FROM_COPY; + } + return BLE_RF_NONE; /* then none: the radio stays off */ +} diff --git a/platform/ble/ble_vm.h b/platform/ble/ble_vm.h new file mode 100644 index 0000000..ae6d052 --- /dev/null +++ b/platform/ble/ble_vm.h @@ -0,0 +1,94 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The radio's stored calibration (route C, docs/BLE-STACK.md §8.2): a read-only reader of stock V15's SDK "VM" store + * and the copy Optimist keeps of the four RF records. Written from docs/BLE-HW-FACTS.md §14 / §15.4 (branch + * feat/ble-facts, d907ce3), not from vendor code. Portable C, no C library; host-tested in tests/ble_vm_test.c. + * + * VM where: a short list of candidate areas, the first that starts 55 AA AA 55 AND whose first record (length + * > 0, inside the area) passes its check is the live one (the magic alone is not enough: other data may + * sit at a candidate, e.g. UP_FM6's voices at 0x095000 on an FM-1, which must never read as a VM): + * 0x0E8000, 4 KiB: measured on an FM-1 (2026-10-08, console 'flr' after stock V15 booted, then Optimist + * installed by stock's updater): the magic and the six records 106 107 187 108 113 109; the + * next sector, 0x0E9000, is BTIF (record 102), so this area cannot be longer than 4 KiB; + * 0x0E7000, 4 KiB: NOT measured, only a candidate for the second area (read FF on that unit); + * 0x093000 / 0x095000, 8 KiB each: the emulator's layout (§14.1; read FF on the FM-1), kept so the + * emulator's runs still find their VM (both marked: 0x093000). + * Where stock's second area is on hardware, and its size there, are not known. + * Records packed from area + 4: [check = low byte of CRC-16/XMODEM of the data] [id 7:0] + * [id 11:8 | len 3:0 << 4] [len 11:4], then the data. The log ends at the first failing check (an erased + * header always fails) or a record past the area; the last valid record of an id wins (§14.2, §14.3). + * RF 106 (2 B, crystal trims), 107 (7 B, PA), 108 (20 B, PA digital gain), 187 (68 B: 64 + its own + * CRC-16/XMODEM little-endian + 00 00) (§14.5). A set is complete when all four are there with these + * lengths and 187's inner CRC holds. + * copy 100 bytes kept with the settings (storage/project.c persist_t): mark, source area, the four records' + * data (97 B), CRC-16/XMODEM of the first 98 bytes, little-endian (§15.4 step 2). + * choice the VM's set, else the copy, else none: with none the radio is never started (§15.4 step 3). + * + * Nothing here writes flash. */ +#ifndef BLE_VM_H +#define BLE_VM_H +#include +#include "ble_cfg.h" + +#define BLE_VM_HW 0x0E8000u /* stock V15's VM on an FM-1 (measured, see above) */ +#define BLE_VM_HW_SIZE 0x1000u /* (0x0E9000 is BTIF) */ +#define BLE_VM_HW2 0x0E7000u /* a candidate for the second area: not measured */ +#define BLE_VM_EMU_A 0x093000u /* the emulator's area A (§14.1) */ +#define BLE_VM_EMU_B 0x095000u /* the emulator's area B */ +#define BLE_VM_EMU_SIZE 0x2000u /* the emulator's areas: 8 KiB each */ +#define BLE_VM_NCAND 4u +#define BLE_VM_MAXAREA 0x2000u /* the largest candidate */ +#define BLE_VM_MAXREC 0x1000u /* (a 12-bit length) */ + +/* reads n bytes of flash at offset off into dst -> 0 ok */ +typedef int (*ble_vm_read_fn)(void *ctx, uint32_t off, uint8_t *dst, uint32_t n); + +struct ble_rf_trims { /* the four records' data, in id order */ + uint8_t x106[2], x107[7], x108[20], x187[68]; +}; +enum { BLE_RF_TRIMS_SIZE = 97 }; + +struct ble_vm_info { + uint32_t area; /* the live area's flash offset; 0: no VM (no candidate marked) */ + uint32_t size; /* that area's size (the log cannot run past it) */ + uint32_t end; /* the end of its log, from the area start */ + uint16_t nrec; /* valid records in the log */ + uint8_t have; /* bit i: record i of 106, 107, 108, 187 found with its length */ + uint8_t wrong_len; /* bit i: found, but only with another length (not used) */ + uint8_t ok187; /* 187's inner CRC holds (the last 187) */ + uint8_t read_err; /* a flash read failed: the scan stopped there */ +}; +#define BLE_VM_ALL 0x0Fu + +/* one valid record of the log, in order (the console's dump) */ +typedef void (*ble_vm_visit_fn)(void *ctx, uint32_t off, uint32_t id, uint32_t len); + +BLE_API uint32_t ble_crc16_xmodem(uint32_t crc, const uint8_t *p, uint32_t n); +/* candidate i (0 .. BLE_VM_NCAND - 1, in the order they are tried): its flash offset, *size its size; 0 past the end */ +BLE_API uint32_t ble_vm_cand(uint32_t i, uint32_t *size); +/* the live area's flash offset (0 = none: no candidate with the magic and a valid first record) and, when found, + * its size in *size (may be 0) */ +BLE_API uint32_t ble_vm_live(ble_vm_read_fn rd, void *ctx, uint32_t *size); +/* walk the live area: fills info and t (the last valid 106 / 107 / 108 / 187; untouched where absent) and calls + * visit (may be 0) per valid record -> 1 when the set is complete (BLE_VM_ALL and 187's inner CRC) */ +BLE_API int ble_vm_scan(ble_vm_read_fn rd, void *ctx, struct ble_vm_info *info, struct ble_rf_trims *t, + ble_vm_visit_fn visit, void *vctx); + +/* ---- the copy kept in Optimist's own store. Its first byte names the area it was taken from: 0xAA 0x093000, + * 0xAB 0x095000 (as before), 0xAC 0x0E8000, 0xAD 0x0E7000 (the candidates' marks) */ +enum { BLE_RF_COPY_SIZE = 100, BLE_RF_COPY_MARK = 0xB1 }; +/* the area a copy's mark names (0: not a mark) */ +BLE_API uint32_t ble_rf_copy_area(uint8_t mark); +enum { BLE_RF_NONE = 0, BLE_RF_FROM_VM = 1, BLE_RF_FROM_COPY = 2 }; +BLE_API int ble_rf_copy_ok(const uint8_t copy[BLE_RF_COPY_SIZE]); +BLE_API void ble_rf_copy_make(uint8_t copy[BLE_RF_COPY_SIZE], const struct ble_rf_trims *t, uint32_t area); +BLE_API void ble_rf_copy_get(const uint8_t copy[BLE_RF_COPY_SIZE], struct ble_rf_trims *t); +/* the precedence of §15.4: VM (complete) -> the copy (valid) -> none. *use gets the trims chosen; *save = 1 when + * the copy must be (re)written from the VM (absent, damaged or different) -> BLE_RF_NONE / _FROM_VM / _FROM_COPY */ +BLE_API int ble_rf_choose(int vm_complete, const struct ble_rf_trims *vm, uint32_t vm_area, + uint8_t copy[BLE_RF_COPY_SIZE], struct ble_rf_trims *use, int *save); +/* at boot (midi_ble.c ble_midi_init): start the radio now? Only with BLUETOOTH ON saved, the boot guard counting no + * failed start-up (boot_failed: system/bootguard.h's count of warm resets within a boot's first 30 s, a watchdog + * reset after a radio start-up that hung among them; a power-on clears it) and the trims there (have_trims) -> 1 */ +BLE_API int ble_boot_radio(int on, uint32_t boot_failed, int have_trims); + +#endif diff --git a/platform/ble/rf_share.h b/platform/ble/rf_share.h new file mode 100644 index 0000000..24e44b9 --- /dev/null +++ b/platform/ble/rf_share.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* The one radio, BLE's and BR/EDR's (Bluetooth MIDI and Bluetooth audio at the same time; docs/BT-CLASSIC.md §9.1). + * Both stacks start it the first time they need it; whichever comes first runs the start-up, the other finds it up: + * rfs_rf_up(trims) the radio's start-up (hal/fm1_ble.h fm1_ble_rf_init), once per boot -> 1 run now, 0 up already. + * BLE (ble_hw_wl82.c ble_hw_wl82_start) and BR/EDR (bt/bt_inq.c bti_radio_up) both call it: a + * second start-up under a live link would retune the radio under it + * rfs_le_ble(b, n) BLE's baseband window (fm1_ble_bb_init with the driver's RAM): always, it is the LE block's owner; + * after BR/EDR's stand-in window it takes the block over (that window carries no link) + * rfs_le_br(b, n) BR/EDR's LE enable (stock V15 enables the LE block beside BR/EDR, BR §14): only while BLE has + * not set its own window -> 1 done now. Over a live BLE it would move the window to a dummy and + * clear BLE's interrupt enables (fm1_ble_bb_init's end), so it is skipped: the block is on already + * Included by ble/ble_hw_wl82.c and bt/bt_inq.c after fm1_ble.h (the host tests: tests/bt_coex_test.c with counting + * stand-ins). One byte of RAM. */ +#ifndef FELUCCA_RF_SHARE_H +#define FELUCCA_RF_SHARE_H +enum { RFS_RF = 1u, RFS_LE_BLE = 2u, RFS_LE_BR = 4u }; +static uint8_t rfs; /* RFS_*: what has run this boot */ + +static int rfs_rf_up(const uint8_t *x106, const uint8_t *x107, const uint8_t *x108, const uint8_t *x187) +{ + if (rfs & RFS_RF) + return 0; + fm1_ble_rf_init(x106, x107, x108, x187); + rfs |= RFS_RF; + return 1; +} +static int rfs_is_up(void) { return (rfs & RFS_RF) != 0u; } +static void rfs_le_ble(uint32_t base, uint32_t size) +{ + fm1_ble_bb_init(base, size); + rfs |= RFS_LE_BLE; +} +static int rfs_le_br(uint32_t base, uint32_t size) +{ + if (rfs & (RFS_LE_BLE | RFS_LE_BR)) + return 0; + fm1_ble_bb_init(base, size); + rfs |= RFS_LE_BR; + return 1; +} +#endif diff --git a/platform/bt.c b/platform/bt.c new file mode 100644 index 0000000..f5d4e79 --- /dev/null +++ b/platform/bt.c @@ -0,0 +1,194 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +/* foma: Bluetooth MIDI on Felucca's platform (the bluetooth option). Part of fm1.c (the unity build). + * + * The stack is Henri David's, from Optimist (platform/ble, from the Bluetooth Core and BLE-MIDI specifications), with + * felucca-bsp's radio drivers (hal/fm1_ble.h, fm1_ble_rf.h) and its start-up calibration (hal/fm1_rf_cal.h), so + * nothing stored on the FM-1 is needed. No JieLi library, no tasks: the stack runs in the radio's two interrupts + * (IRQ 45 and 29, priority 2: below the audio and TIMER5) and talks to the rest through single-producer rings: + * in: the BLE interrupts write, the TIMER5 tick moves it to the MIDI ring (and the clock) as cable 2; + * out: midi_send writes (interrupts off), the BLE interrupts send it. + * The FM-1 is a BLE MIDI peripheral: a computer or phone connects to it. No pairing (macOS and iOS connect anyway), + * no central role, no audio. */ +#ifndef BLE_DEVICE_NAME +#define BLE_DEVICE_NAME APP_NAME /* advertised as "NAME XXXX", XXXX from this FM-1's address */ +#endif +#define FELUCCA_BLE_DIAG 0 +#define BLE_CENTRAL 0 +#include "ble/ble_stack.c" + +/* the SDK board's constant records (crystal load, PA bias; the Wi-Fi rates' gains left as they are): as fm1-base's + * bt_own.c. The radio's own record (187) is measured at every start (fm1_rf_cal.h) */ +static const struct ble_rf_trims BT_TRIMS = {{0x0B, 0x0B}, {1, 7, 4, 7, 11, 1, 7}, {0}, {0}}; + +#define BQ 64u +static struct { + uint32_t pkt, t; +} bt_in[BQ]; +static volatile uint32_t bi_w, bi_r; +static struct { + uint32_t pkt; + uint16_t ms; +} bt_out[BQ]; +static volatile uint32_t bo_w, bo_r; +static uint8_t bt_addr[6]; +static volatile uint8_t bt_up, bt_on, bt_live; /* the radio started; switched on; a central listens for MIDI */ +static uint8_t bt_held[16][16]; /* notes a central holds on: ended when the link goes */ + +/* ---- the stack's side: the BLE interrupts */ +BLE_API int ble_app_midi_peek(uint32_t *pkt, uint32_t *t_ms) { + if (bo_r == bo_w) { + return 0; + } + *pkt = bt_out[bo_r % BQ].pkt; + *t_ms = bt_out[bo_r % BQ].ms; + return 1; +} +BLE_API void ble_app_midi_pop(void) { + if (bo_r != bo_w) { + bo_r++; + } +} +BLE_API void ble_app_midi_in(uint32_t pkt, uint16_t ts, uint16_t last_ts) { + (void)ts, (void)last_ts; + if (bi_w - bi_r < BQ) { + bt_in[bi_w % BQ].pkt = pkt & ~0xF0u; + bt_in[bi_w % BQ].t = fm1_ticks(); + RING_PUBLISH(); + bi_w++; + } +} +BLE_API void ble_app_state(void) { bt_live = (uint8_t)(bt_on && ble_midi_ready()); } + +/* ---- the platform's side */ +static void bt_put(uint32_t pkt) { /* TIMER5: into the MIDI ring, cable 2 */ + if (mi_w - mi_r < MQ) { + midi_in_q[mi_w % MQ] = (pkt & ~0xF0u) | 0x20u; + RING_PUBLISH(); + mi_w++; + } +} + +static void bt_poll(void) { /* TIMER5, beside usb_poll */ + static uint8_t was_live; + uint8_t live = bt_live; + while (bi_r != bi_w) { + uint32_t pk = bt_in[bi_r % BQ].pkt, t = bt_in[bi_r % BQ].t, cin = pk & 15u, st = (pk >> 8) & 0xFFu; + bi_r++; + if (cin == 0xFu && (st == 0xF8u || st == 0xFAu || st == 0xFBu || st == 0xFCu)) { +#if FOMA_MIDI_CLOCK + if (clock_in(st, MIDI_BLE, t)) { + continue; + } +#else + (void)t; +#endif + bt_put(0xFu | st << 8); + } else if (cin >= 8u && cin <= 0xEu && (st >> 4) == cin) { + uint32_t ch = st & 15u, n = (pk >> 16) & 0x7Fu; + if (cin == 9u && (pk >> 24)) { + bt_held[ch][n >> 3] |= (uint8_t)(1u << (n & 7u)); + } else if (cin == 8u || cin == 9u) { + bt_held[ch][n >> 3] &= (uint8_t) ~(1u << (n & 7u)); + } + bt_put(pk); + } + } + if (was_live && !live) { /* the link went: no stuck notes */ + for (uint32_t ch = 0; ch < 16u; ch++) { + for (uint32_t n = 0; n < 128u; n++) { + if (bt_held[ch][n >> 3] >> (n & 7u) & 1u) { + bt_put(8u | (0x80u | ch) << 8 | n << 16); + } + } + for (uint32_t i = 0; i < 16u; i++) { + bt_held[ch][i] = 0; + } + } + } + was_live = live; +} + +static void bt_midi_out(uint32_t pkt) { /* midi_send, interrupts off */ + if (bt_live && bo_w - bo_r < BQ) { + bt_out[bo_w % BQ].pkt = pkt; + bt_out[bo_w % BQ].ms = (uint16_t)fm1_ms; + RING_PUBLISH(); + bo_w++; + } +} + +/* the address: static random, from the flash's unique ID (the same on every boot) */ +static void bt_addr_make(void) { + static uint8_t uid[16]; /* (in RAM: the flash driver writes it with the flash off) */ + uint32_t h = 2166136261u, g = 0x9E3779B9u, i, same = 1, f = irq_save(); + if (flash_ok && FL_FAR(fl_uid_ram)(uid) == 0) { + for (i = 1; i < 16u; i++) { + same &= uid[i] == uid[0]; + } + } + irq_restore(f); + if (!same) { + for (i = 0; i < 16u; i++) { + h = (h ^ uid[i]) * 16777619u; + g = (g ^ uid[i]) * 2246822519u; + } + } else { /* no ID: a new one each boot */ + h ^= fm1_ticks(); + g ^= fm1_ticks() * 2654435761u; + } + bt_addr[0] = (uint8_t)h; + bt_addr[1] = (uint8_t)(h >> 8); + bt_addr[2] = (uint8_t)g; + bt_addr[3] = (uint8_t)(g >> 8); + bt_addr[4] = (uint8_t)(g >> 16); + bt_addr[5] = (uint8_t)((g >> 24) | 0xC0u); /* static random: the top two bits set */ +} + +/* the first bt_enable: the two BLE vectors (masked), the radio and its calibration, then advertising. Nothing of + * this runs at boot: a firmware that never turns Bluetooth on never touches the radio (attaching the vectors at + * boot crashed the FM-1) */ +static void bt_start(void) { + uint32_t f; + bt_addr_make(); + f = irq_save(); + fm1_guard_unlock_top(); + ble_hw_wl82_attach(); + fm1_guard_lock_top(); + irq_restore(f); + ble_init(bt_addr, 1); + fm1_rf_cal_on = 1; + ble_hw_wl82_start(&BT_TRIMS); + bt_up = 1; +} + +int bt_enable(int features) { + uint8_t on = (uint8_t)((features & BT_MIDI) != 0); + if (on && !bt_up) { + bt_start(); + } + if (bt_up) { + bt_on = on; + fm1_ble_irqs_hold(1); + ble_enable(on); + bt_live = (uint8_t)(on && ble_midi_ready()); + fm1_ble_irqs_hold(0); + } + return 0; +} + +void bt_status(bt_status_t *s) { + *s = (bt_status_t){0}; + s->ready = bt_up; + s->ble_state = !bt_up || !bt_on ? BLE_OFF : bt_live ? BLE_READY + : ble_connected() ? BLE_CONNECTED + : BLE_ADVERTISING; +} + +/* not on this platform: the central role (connecting to a controller) and audio from Bluetooth */ +int ble_central(int on) { return on ? -3 : 0; } +int ble_scan(void) { return -3; } +int ble_device(int i, char name[25], int *rssi) { return (void)i, (void)name, (void)rssi, -1; } +int ble_connect(int i) { return (void)i, -3; } +int ble_disconnect(void) { return -3; } +int ble_forget(void) { return -3; } +const int32_t *bt_audio_in(void) { return 0; } diff --git a/platform/fm1.c b/platform/fm1.c index dfa3753..84e3185 100644 --- a/platform/fm1.c +++ b/platform/fm1.c @@ -62,6 +62,9 @@ static volatile uint32_t fm1_ms; /* milliseconds since power-on (TIMER5) */ #define SETTINGS_AT 0x000FC000u #define SETTINGS_END 0x000FF000u #define FL_RANGE_OK(off, n) (FL_IN(off, n, FL_OTA_LO, FL_OTA_HI) || FL_IN(off, n, SETTINGS_AT, SETTINGS_END)) +#if FOMA_BLUETOOTH +#define FL_UID /* the flash's unique ID: the Bluetooth address */ +#endif #include "fm1_flash.h" static uint8_t flash_ok; static int st_read(uint32_t off, void *dst, uint32_t n) { @@ -126,6 +129,9 @@ static void ota_commit(const uint8_t *parm) { fm1_enter_update(parm); } #include "recovery.c" +#if FOMA_BLUETOOTH +#include "bt.c" +#endif /* ---- the screen, the sound helpers (shared with the emulator) */ #include "common.c" @@ -203,11 +209,16 @@ int midi_read(uint8_t *status, uint8_t *d1, uint8_t *d2) { *status = (uint8_t)(pk >> 8); *d1 = (uint8_t)(pk >> 16); *d2 = (uint8_t)(pk >> 24); - return pk & 0x10u ? MIDI_TRS : MIDI_USB; + return pk & 0x20u ? MIDI_BLE : pk & 0x10u ? MIDI_TRS + : MIDI_USB; /* the cable: 0 USB, 1 TRS, 2 Bluetooth */ } void midi_send(uint8_t status, uint8_t d1, uint8_t d2) { uint32_t st = status, f = irq_save(); /* (loop() and audio() may both send) */ - midi_out_event((st >> 4) | st << 8 | (uint32_t)(d1 & 0x7Fu) << 16 | (uint32_t)(d2 & 0x7Fu) << 24); + uint32_t pk = (st >> 4) | st << 8 | (uint32_t)(d1 & 0x7Fu) << 16 | (uint32_t)(d2 & 0x7Fu) << 24; + midi_out_event(pk); +#if FOMA_BLUETOOTH + bt_midi_out(pk); +#endif irq_restore(f); } @@ -307,6 +318,9 @@ void fm1_timer5_irq(void) { usb_poll(); #if FOMA_TRS_MIDI uart_midi_poll(); +#endif +#if FOMA_BLUETOOTH + bt_poll(); #endif } owed = 0; diff --git a/platform/fm1.h b/platform/fm1.h index a5736ff..7a9dfc2 100644 --- a/platform/fm1.h +++ b/platform/fm1.h @@ -23,7 +23,7 @@ #define FOMA_MIDI_CLOCK 1 /* midi_clock: one MIDI clock for audio(), its own or followed: clock_*() */ #endif #ifndef FOMA_BLUETOOTH -#define FOMA_BLUETOOTH 0 /* bluetooth: BLE MIDI and audio from a phone, bt_*() / ble_*() (the "mvave" platform only) */ +#define FOMA_BLUETOOTH 0 /* bluetooth: BLE MIDI, bt_*() / ble_*() (and audio from a phone: the "mvave" platform) */ #endif /* FOMA_MVAVE: 1 when built on M-VAVE's FM1 SDK ("platform": "mvave" in firmware.json), else Felucca's platform */ #ifndef FOMA_MVAVE @@ -143,10 +143,10 @@ uint32_t clock_bpm(void); /* BPM x 100: its tempo, or the foll #endif #if FOMA_BLUETOOTH -/* ---- Bluetooth (bluetooth: the "mvave" platform). Off until bt_enable(). BLE MIDI comes in through midi_read - * (MIDI_BLE) and midi_send goes out over it too; a phone or computer can play into the FM-1 (bt_audio_in). - * By default phones and computers connect to the FM-1 (it shows up as a BLE MIDI device); ble_central(1) - * makes it connect to a BLE MIDI controller instead: ble_scan(), then ble_device() / ble_connect(). From loop(); +/* ---- Bluetooth (bluetooth). Off until bt_enable(). BLE MIDI comes in through midi_read (MIDI_BLE) and midi_send + * goes out over it too. Phones and computers connect to the FM-1 (it shows up as a BLE MIDI device). The "mvave" + * platform also has: a phone or computer playing into the FM-1 (bt_audio_in), and ble_central(1), which makes it + * connect to a BLE MIDI controller instead: ble_scan(), then ble_device() / ble_connect(). From loop(); * the calls return 0 when taken, -2 busy (try again), -3 not ready */ enum { BT_AUDIO = 1, BT_MIDI = 2 }; diff --git a/platform/hal/ble_rf_tables.h b/platform/hal/ble_rf_tables.h new file mode 100644 index 0000000..6ed54e9 --- /dev/null +++ b/platform/hal/ble_rf_tables.h @@ -0,0 +1,5 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +/* fm1_ble_rf.h includes "ble_rf_tables.h" (felucca-bsp's build puts a fresh capture there): foma uses the committed + * tables, captured from M-VAVE's stock V15 firmware (Apache-2.0, see LICENSING.md) */ +#pragma once +#include "ble_rf_tables_v15.h" diff --git a/platform/hal/ble_rf_tables_v15.h b/platform/hal/ble_rf_tables_v15.h new file mode 100644 index 0000000..2c4075e --- /dev/null +++ b/platform/hal/ble_rf_tables_v15.h @@ -0,0 +1,304 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/* BLE radio start-up values captured from the stock FM-1 V15 firmware (see docs/BLE-STACK.md): M-VAVE's FM-1_015.fwsc, + * Copyright (c) 2026 Zhuhai Shengke / M-VAVE, published under Apache-2.0 as sdk/firmware/FM-1_015.fwsc in + * https://github.com/m-vave/fm1_open (its THIRD_PARTY.md). The writes are V15's rf_init, JieLi's radio start-up + * (wl_rf_common.a, btctrler.a), which JieLi publishes under Apache-2.0 in its AC79 AIoT SDK: Copyright (c) 2024-2026 + * Zhuhai Jieli Technology Co., Ltd., https://gitee.com/Jieli-Tech/fw-AC79_AIoT_SDK (cpu/wl82/liba/). + * Changed by Optimist (Apache-2.0 section 4(b)): not the code but the writes it made, recorded in the emulator by + * tools/ble_rf_capture.py, cut into groups, the window-D read-back loop left out, packed by tools/ble_rf_pack.py. */ +#pragma once +#include +#define BLE_RF_TABLES_FORMAT 3 +#define BLE_RF_SHA256 "30ba97eac84ae1b5574c6328a2ab67df7a0c97720b7276b3dcb13cb0e49dcba3" +#define BLE_RF_BBP_FLAGS 0x80000u /* the BBP command word's fixed upper bits (§5.2) */ +#define BLE_RF_SKIPPED 3537u /* window-D read-back loop transactions left out (§16.2) */ +#define BLE_RF_LUT_TRIMMED 160u /* LUT words a stored trim changes: written as captured, TODO(hardware) */ +#define BLE_RF_NFIELDS 52u +/* program 10706 bytes as captured (format 2), 5795 packed (tools/ble_rf_pack.py: OP_LUT2, OP_WWG): 522 register writes, 1179 window writes, 18 window reads, 26 direct BBP, 512 LUT words, 101 trim marks, 4 delays, 1 replays, sections 2 3 4 5 6 7 8 10 11 13 (§16.1 groups) */ +static const uint8_t ble_rf_prog[5795] = { + 0x90, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x05, + 0x00, 0x02, 0x00, 0x00, 0x05, 0x00, 0x02, 0x00, 0x8C, 0x1C, 0x00, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x90, 0x03, 0x8C, + 0x3E, 0x00, 0x1A, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, + 0x00, 0x00, 0x00, 0x1A, 0x00, 0x01, 0x00, 0x00, 0x1A, 0x40, 0x01, 0x00, 0x00, 0x1A, 0x41, 0x01, 0x00, 0x00, 0x1A, 0x45, 0x01, 0x00, 0x00, 0x1A, + 0x4D, 0x01, 0x00, 0x00, 0x1A, 0x4F, 0x01, 0x00, 0x00, 0x1F, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x05, 0x00, 0x00, 0x00, + 0x1F, 0x05, 0x00, 0x00, 0x07, 0x1F, 0x05, 0x00, 0x00, 0x47, 0x1F, 0x05, 0x00, 0x00, 0x47, 0x1D, 0x00, 0x00, 0x00, 0x01, 0x23, 0x00, 0x08, 0x00, + 0x00, 0x23, 0x00, 0x0C, 0x00, 0x00, 0x23, 0x00, 0x0E, 0x00, 0x00, 0x23, 0x20, 0x0E, 0x00, 0x00, 0x23, 0x30, 0x0E, 0x00, 0x00, 0x23, 0x30, 0x0E, + 0x00, 0x00, 0x23, 0x34, 0x0E, 0x00, 0x00, 0x23, 0x36, 0x0E, 0x00, 0x00, 0x23, 0x37, 0x0E, 0x00, 0x00, 0x22, 0x00, 0x04, 0x00, 0x00, 0x22, 0x00, + 0x04, 0x00, 0x00, 0x22, 0x00, 0x04, 0x00, 0x00, 0x22, 0x60, 0x04, 0x00, 0x00, 0x22, 0x60, 0x04, 0x00, 0x00, 0x22, 0x68, 0x04, 0x00, 0x00, 0x22, + 0x6C, 0x04, 0x00, 0x00, 0x22, 0x6E, 0x04, 0x00, 0x00, 0x22, 0x6F, 0x04, 0x00, 0x00, 0x24, 0x03, 0x00, 0x00, 0x00, 0x21, 0x1E, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x00, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x90, 0x04, 0x88, 0x16, 0x00, 0x88, 0x15, 0x31, 0x88, 0x15, 0x30, 0x88, 0x19, 0x00, + 0x26, 0x14, 0x03, 0x14, 0x00, 0x25, 0x0B, 0x0C, 0xA4, 0x33, 0x27, 0x04, 0x08, 0x04, 0x00, 0x28, 0x08, 0x08, 0x0C, 0x00, 0x29, 0x04, 0x01, 0x0C, + 0x00, 0x2A, 0x90, 0x12, 0x0F, 0x00, 0x20, 0x07, 0x94, 0x00, 0x00, 0x24, 0x03, 0x00, 0x00, 0x00, 0x21, 0x1E, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, + 0x00, 0x00, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x88, 0x16, 0x00, 0x88, 0x15, 0x31, 0x88, 0x15, 0x30, 0x88, 0x19, 0x00, 0x82, 0x4D, 0x01, 0x82, 0x4E, + 0x01, 0x82, 0x4F, 0x00, 0x82, 0x29, 0x6C, 0x82, 0x2A, 0x01, 0x82, 0x2B, 0x02, 0x82, 0x2C, 0x02, 0x82, 0x31, 0x03, 0x82, 0x36, 0x6B, 0x82, 0x37, + 0x01, 0x82, 0x38, 0x02, 0x82, 0x39, 0x02, 0x82, 0x3E, 0x02, 0x82, 0x43, 0x6C, 0x82, 0x44, 0x01, 0x82, 0x45, 0x02, 0x82, 0x46, 0x02, 0x82, 0x4B, + 0x03, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x88, 0x16, 0x00, 0x88, 0x15, 0x31, 0x88, 0x15, 0x30, 0x88, 0x19, 0x00, 0x26, 0x14, 0x03, 0x14, 0x00, 0x25, + 0x0B, 0x0C, 0xA4, 0x33, 0x27, 0x04, 0x08, 0x04, 0x00, 0x28, 0x08, 0x08, 0x0C, 0x00, 0x29, 0x04, 0x01, 0x0C, 0x00, 0x2A, 0x90, 0x12, 0x0F, 0x00, + 0x20, 0x07, 0x94, 0x00, 0x00, 0x92, 0x00, 0x06, 0x2F, 0x2B, 0x4E, 0x54, 0x55, 0x2F, 0x80, 0x00, 0xEC, 0x00, 0xB0, 0xFF, 0x80, 0x01, 0xED, 0x01, + 0xB8, 0xFF, 0x81, 0x02, 0xEE, 0x02, 0xC0, 0xFF, 0x82, 0x03, 0xEF, 0x03, 0xC8, 0xFF, 0x83, 0x04, 0xF0, 0x04, 0xD0, 0xFF, 0x84, 0x05, 0xF1, 0x05, + 0xD8, 0xFF, 0x85, 0x06, 0xF2, 0x06, 0xE0, 0xFF, 0x86, 0x07, 0xF3, 0x07, 0xE8, 0xFF, 0x87, 0x08, 0xF4, 0x08, 0xF0, 0xFF, 0x88, 0x09, 0xF5, 0x09, + 0xF8, 0xFF, 0x89, 0x0A, 0xF6, 0x0A, 0x00, 0x00, 0x8A, 0x0B, 0xF7, 0x0B, 0x08, 0x00, 0x8B, 0x0C, 0xF8, 0x0C, 0x10, 0x00, 0x8C, 0x0D, 0xF9, 0x0D, + 0x18, 0x00, 0x8D, 0x0E, 0xFA, 0x0E, 0x20, 0x00, 0x8E, 0x0F, 0xFB, 0x0F, 0x28, 0x00, 0x8F, 0x10, 0xFC, 0x10, 0x30, 0x00, 0x90, 0x11, 0xFD, 0x11, + 0x38, 0x00, 0x91, 0x12, 0xFE, 0x12, 0x40, 0x00, 0x92, 0x13, 0xFF, 0x13, 0x48, 0x00, 0x93, 0x14, 0x00, 0x14, 0x50, 0x00, 0x94, 0x15, 0x01, 0x15, + 0x58, 0x00, 0x95, 0x16, 0x02, 0x16, 0x60, 0x00, 0x96, 0x17, 0x03, 0x17, 0x68, 0x00, 0x97, 0x18, 0x04, 0x18, 0x70, 0x00, 0x98, 0x19, 0x05, 0x19, + 0x78, 0x00, 0x99, 0x1A, 0x06, 0x1A, 0x80, 0x00, 0x9A, 0x1B, 0x07, 0x1B, 0x88, 0x00, 0x9B, 0x1C, 0x08, 0x1C, 0x90, 0x00, 0x9C, 0x1D, 0x09, 0x1D, + 0x98, 0x00, 0x9D, 0x1E, 0x0A, 0x1E, 0xA0, 0x00, 0x9E, 0x1F, 0x0B, 0x1F, 0xA8, 0x00, 0x9F, 0x20, 0x0C, 0x20, 0xB0, 0x00, 0xA0, 0x21, 0x0D, 0x21, + 0xB8, 0x00, 0xA1, 0x22, 0x0E, 0x22, 0xC0, 0x00, 0xA2, 0x23, 0x0F, 0x23, 0xC8, 0x00, 0xA3, 0x24, 0x10, 0x24, 0xD0, 0x00, 0xA4, 0x25, 0x11, 0x25, + 0xD8, 0x00, 0xA5, 0x26, 0x12, 0x26, 0xE0, 0x00, 0xA6, 0x27, 0x13, 0x27, 0xE8, 0x00, 0xA7, 0x28, 0x14, 0x28, 0xF0, 0x00, 0xA8, 0x29, 0x15, 0x29, + 0xF8, 0x00, 0xA9, 0x2A, 0x16, 0x2A, 0x00, 0x01, 0xAA, 0x2B, 0x17, 0x2B, 0x08, 0x01, 0xAB, 0x2C, 0x18, 0x2C, 0x10, 0x01, 0xAC, 0x2D, 0x19, 0x2D, + 0x18, 0x01, 0xAD, 0x2E, 0x1A, 0x2E, 0x20, 0x01, 0xAE, 0x2F, 0x1B, 0x2F, 0x28, 0x01, 0xAF, 0x30, 0x1C, 0x30, 0x30, 0x01, 0xB0, 0x31, 0x1D, 0x31, + 0x38, 0x01, 0xB1, 0x32, 0x1E, 0x32, 0x40, 0x01, 0xB2, 0x33, 0x1F, 0x33, 0x48, 0x01, 0xB3, 0x34, 0x20, 0x34, 0x50, 0x01, 0xB4, 0x35, 0x21, 0x35, + 0x58, 0x01, 0xB5, 0x36, 0x22, 0x36, 0x60, 0x01, 0xB6, 0x37, 0x23, 0x37, 0x68, 0x01, 0xB7, 0x38, 0x24, 0x38, 0x70, 0x01, 0xB8, 0x39, 0x25, 0x39, + 0x78, 0x01, 0xB9, 0x3A, 0x26, 0x3A, 0x80, 0x01, 0xBA, 0x3B, 0x27, 0x3B, 0x88, 0x01, 0xBB, 0x3C, 0x28, 0x3C, 0x90, 0x01, 0xBC, 0x3D, 0x29, 0x3D, + 0x98, 0x01, 0xBD, 0x3E, 0x2A, 0x3E, 0xA0, 0x01, 0xBE, 0x3F, 0x2B, 0x3F, 0xA8, 0x01, 0xBF, 0x40, 0x2C, 0x40, 0xB0, 0x01, 0xC0, 0x41, 0x2D, 0x41, + 0xB8, 0x01, 0xC1, 0x42, 0x2E, 0x42, 0xC0, 0x01, 0xC2, 0x43, 0x2F, 0x43, 0xC8, 0x01, 0xC3, 0x44, 0x30, 0x44, 0xD0, 0x01, 0xC4, 0x45, 0x31, 0x45, + 0xD8, 0x01, 0xC5, 0x46, 0x32, 0x46, 0xE0, 0x01, 0xC6, 0x47, 0x33, 0x47, 0xE8, 0x01, 0xC7, 0x48, 0x34, 0x48, 0xF0, 0x01, 0xC8, 0x49, 0x35, 0x49, + 0xF8, 0x01, 0xC9, 0x4A, 0x36, 0x4A, 0x00, 0x02, 0xCA, 0x4B, 0x37, 0x4B, 0x08, 0x02, 0xCB, 0x4C, 0x38, 0x4C, 0x10, 0x02, 0xCC, 0x4D, 0x39, 0x4D, + 0x18, 0x02, 0xCD, 0x4E, 0x3A, 0x4E, 0x20, 0x02, 0xCE, 0x4F, 0x3B, 0x4F, 0x28, 0x02, 0xCF, 0x50, 0x3C, 0x50, 0x30, 0x02, 0xD0, 0x51, 0x3D, 0x51, + 0x38, 0x02, 0xD1, 0x52, 0x3E, 0x52, 0x40, 0x02, 0xD2, 0x53, 0x3F, 0x53, 0x48, 0x02, 0xD3, 0x54, 0x3F, 0x54, 0x50, 0x02, 0xD4, 0x55, 0x3F, 0x55, + 0x58, 0x02, 0xD5, 0x56, 0x3F, 0x56, 0x60, 0x02, 0xD6, 0x57, 0x3F, 0x57, 0x68, 0x02, 0xD7, 0x58, 0x3F, 0x58, 0x70, 0x02, 0xD8, 0x59, 0x3F, 0x59, + 0x78, 0x02, 0xD9, 0x5A, 0x3F, 0x5A, 0x80, 0x02, 0xDA, 0x5B, 0x3F, 0x5B, 0x88, 0x02, 0xDB, 0x5C, 0x3F, 0x5C, 0x90, 0x02, 0xDC, 0x5D, 0x3F, 0x5D, + 0x98, 0x02, 0xDD, 0x5E, 0x3F, 0x5E, 0xA0, 0x02, 0xDE, 0x5F, 0x3F, 0x5F, 0xA8, 0x02, 0xDF, 0x60, 0x3F, 0x60, 0xB0, 0x02, 0xE0, 0x61, 0x3F, 0x61, + 0xB8, 0x02, 0xE1, 0x62, 0x3F, 0x62, 0xC0, 0x02, 0xE2, 0x63, 0x3F, 0x63, 0xC8, 0x02, 0xE3, 0x64, 0x3F, 0x64, 0xD0, 0x02, 0xE4, 0x65, 0x3F, 0x65, + 0xD8, 0x02, 0xE5, 0x66, 0x3F, 0x66, 0xE0, 0x02, 0xE6, 0x67, 0x3F, 0x67, 0xE8, 0x02, 0xE7, 0x68, 0x3F, 0x68, 0xF0, 0x02, 0xE8, 0x69, 0x3F, 0x69, + 0xF8, 0x02, 0xE9, 0x6A, 0x3F, 0x6A, 0x00, 0x03, 0xEA, 0x6B, 0x3F, 0x6B, 0x08, 0x03, 0xEB, 0x6C, 0x3F, 0x6C, 0x10, 0x03, 0xEC, 0x6D, 0x3F, 0x6D, + 0x18, 0x03, 0xED, 0x6E, 0x3F, 0x6E, 0x20, 0x03, 0xEE, 0x6F, 0x3F, 0x6F, 0x28, 0x03, 0xEF, 0x70, 0x3F, 0x70, 0x30, 0x03, 0xF0, 0x71, 0x3F, 0x71, + 0x38, 0x03, 0xF1, 0x72, 0x3F, 0x72, 0x40, 0x03, 0xF2, 0x73, 0x3F, 0x73, 0x48, 0x03, 0xF3, 0x74, 0x3F, 0x74, 0x50, 0x03, 0xF4, 0x75, 0x3F, 0x75, + 0x58, 0x03, 0xF5, 0x76, 0x3F, 0x76, 0x60, 0x03, 0xF6, 0x77, 0x3F, 0x77, 0x68, 0x03, 0xF7, 0x78, 0x3F, 0x78, 0x70, 0x03, 0xF8, 0x79, 0x3F, 0x79, + 0x78, 0x03, 0xF9, 0x7A, 0x3F, 0x7A, 0x80, 0x03, 0xFA, 0x7B, 0x3F, 0x7B, 0x88, 0x03, 0xFB, 0x7C, 0x3F, 0x7C, 0x90, 0x03, 0xFC, 0x7D, 0x3F, 0x7D, + 0x98, 0x03, 0xFD, 0x7E, 0x3F, 0x7E, 0xA0, 0x03, 0xFE, 0x7F, 0x3F, 0x7F, 0xA8, 0x03, 0xFF, 0x80, 0x2F, 0x00, 0x80, 0x54, 0xC0, 0x80, 0x55, 0x01, + 0x80, 0x4E, 0x42, 0x80, 0x2B, 0x42, 0x80, 0x2C, 0x42, 0x80, 0x79, 0x00, 0x80, 0x7A, 0x20, 0x80, 0x00, 0x8A, 0x80, 0x01, 0x20, 0x80, 0x02, 0x04, + 0x80, 0x03, 0x08, 0x80, 0x04, 0x0C, 0x80, 0x05, 0x10, 0x80, 0x06, 0xB0, 0x80, 0x07, 0xA0, 0x80, 0x08, 0x70, 0x80, 0x09, 0x32, 0x80, 0x0A, 0x0C, + 0x80, 0x0B, 0xE0, 0x80, 0x0C, 0x01, 0x80, 0x0D, 0x00, 0x80, 0x0E, 0xB5, 0x80, 0x0F, 0x91, 0x80, 0x10, 0x44, 0x80, 0x11, 0x43, 0x80, 0x12, 0x44, + 0x80, 0x13, 0x04, 0x80, 0x14, 0x7F, 0x80, 0x15, 0x0F, 0x80, 0x16, 0x00, 0x80, 0x17, 0x05, 0x80, 0x18, 0x77, 0x80, 0x19, 0x80, 0x80, 0x1A, 0x12, + 0x80, 0x1B, 0xBE, 0x80, 0x1C, 0x35, 0x80, 0x1D, 0xEF, 0x80, 0x1E, 0x0F, 0x80, 0x1F, 0x0F, 0x80, 0x20, 0x4F, 0x80, 0x21, 0x05, 0x80, 0x22, 0x05, + 0x80, 0x23, 0x93, 0x80, 0x24, 0x04, 0x80, 0x25, 0x0D, 0x80, 0x26, 0x03, 0x80, 0x27, 0x84, 0x80, 0x28, 0x1E, 0x80, 0x29, 0x0A, 0x80, 0x2A, 0x94, + 0x80, 0x30, 0x20, 0x80, 0x31, 0x06, 0x80, 0x32, 0x3F, 0x80, 0x33, 0x0C, 0x80, 0x34, 0x0C, 0x80, 0x35, 0x04, 0x80, 0x36, 0x0C, 0x80, 0x37, 0x04, + 0x80, 0x38, 0x10, 0x80, 0x39, 0x10, 0x80, 0x3A, 0x20, 0x80, 0x3B, 0xC0, 0x80, 0x3C, 0xF0, 0x80, 0x3D, 0xD0, 0x80, 0x3E, 0x80, 0x80, 0x3F, 0xD0, + 0x80, 0x40, 0xE7, 0x80, 0x41, 0x87, 0x80, 0x42, 0x18, 0x80, 0x43, 0xE8, 0x80, 0x44, 0x30, 0x80, 0x45, 0x30, 0x80, 0x46, 0x07, 0x80, 0x47, 0x00, + 0x80, 0x48, 0xBE, 0x80, 0x49, 0x96, 0x80, 0x4B, 0x70, 0x80, 0x4C, 0x50, 0x80, 0x4F, 0x8C, 0x80, 0x50, 0x80, 0x80, 0x51, 0x90, 0x80, 0x52, 0xFF, + 0x80, 0x53, 0x03, 0x80, 0x54, 0x00, 0x80, 0x55, 0x01, 0x80, 0x56, 0x01, 0x80, 0x57, 0x27, 0x80, 0x58, 0x03, 0x80, 0x59, 0x28, 0x80, 0x5A, 0xD8, + 0x80, 0x5B, 0x0C, 0x80, 0x5C, 0x01, 0x80, 0x5D, 0x05, 0x80, 0x5E, 0x50, 0x80, 0x5F, 0x80, 0x80, 0x60, 0x80, 0x80, 0x61, 0xDD, 0x80, 0x62, 0x20, + 0x80, 0x63, 0xFE, 0x80, 0x64, 0x50, 0x80, 0x65, 0x50, 0x80, 0x66, 0x50, 0x80, 0x67, 0x00, 0x80, 0x68, 0x00, 0x80, 0x69, 0x64, 0x80, 0x6A, 0x84, + 0x80, 0x6B, 0xDF, 0x80, 0x6C, 0x47, 0x80, 0x6D, 0x40, 0x80, 0x6E, 0x2C, 0x80, 0x6F, 0x70, 0x80, 0x70, 0x50, 0x80, 0x71, 0xE0, 0x80, 0x72, 0x01, + 0x80, 0x73, 0x9C, 0x80, 0x75, 0x00, 0x80, 0x76, 0x03, 0x80, 0x77, 0x49, 0x80, 0x78, 0x00, 0x80, 0x79, 0x04, 0x80, 0x7A, 0xD0, 0x83, 0x00, 0x3A, + 0x83, 0x04, 0x6A, 0x83, 0x05, 0x00, 0x83, 0x06, 0x00, 0x83, 0x07, 0xB5, 0x83, 0x03, 0x15, 0x83, 0x08, 0xC1, 0x83, 0x0D, 0x2B, 0x83, 0x0E, 0xA0, + 0x83, 0x0F, 0xC4, 0x83, 0x10, 0x04, 0x83, 0x11, 0xA0, 0x83, 0x12, 0x2B, 0x83, 0x13, 0x00, 0x83, 0x14, 0x00, 0x83, 0x15, 0x00, 0x83, 0x16, 0x00, + 0x83, 0x17, 0x00, 0x83, 0x18, 0x00, 0x83, 0x19, 0x39, 0x83, 0x1A, 0x6A, 0x83, 0x1B, 0x38, 0x83, 0x1C, 0x00, 0x83, 0x18, 0x00, 0x81, 0x00, 0x62, + 0x81, 0x01, 0x58, 0x81, 0x02, 0x45, 0x81, 0x03, 0xE5, 0x81, 0x04, 0x00, 0x81, 0x05, 0x0A, 0x81, 0x06, 0x12, 0x81, 0x07, 0x04, 0x81, 0x08, 0x00, + 0x81, 0x09, 0x70, 0x81, 0x0A, 0x34, 0x81, 0x0B, 0x00, 0x81, 0x0C, 0x00, 0x81, 0x0D, 0x9A, 0x81, 0x0E, 0xA6, 0x81, 0x0F, 0x33, 0x81, 0x10, 0x9A, + 0x81, 0x11, 0xA6, 0x81, 0x12, 0x33, 0x81, 0x13, 0x9A, 0x81, 0x14, 0xA6, 0x81, 0x15, 0x33, 0x81, 0x16, 0x9A, 0x81, 0x17, 0xA6, 0x81, 0x18, 0x33, + 0x81, 0x19, 0x9A, 0x81, 0x1A, 0xA6, 0x81, 0x1B, 0x33, 0x81, 0x1C, 0x08, 0x81, 0x1D, 0x0F, 0x81, 0x1E, 0x10, 0x81, 0x1F, 0x10, 0x81, 0x20, 0x10, + 0x81, 0x21, 0x24, 0x81, 0x22, 0x25, 0x81, 0x23, 0x24, 0x81, 0x24, 0x25, 0x81, 0x25, 0x25, 0x81, 0x26, 0x25, 0x81, 0x27, 0x25, 0x81, 0x28, 0x25, + 0x81, 0x29, 0x25, 0x81, 0x2A, 0x25, 0x81, 0x2B, 0x25, 0x81, 0x2C, 0x25, 0x81, 0x2D, 0x1D, 0x81, 0x2E, 0x25, 0x81, 0x2F, 0x1C, 0x81, 0x30, 0x25, + 0x81, 0x31, 0x0A, 0x81, 0x32, 0x0A, 0x81, 0x33, 0x0A, 0x81, 0x34, 0x0A, 0x81, 0x35, 0x0A, 0x81, 0x36, 0x0A, 0x81, 0x37, 0x0A, 0x81, 0x38, 0x07, + 0x81, 0x39, 0x2E, 0x81, 0x3A, 0x08, 0x81, 0x3B, 0x20, 0x81, 0x3C, 0xFF, 0x81, 0x3D, 0x08, 0x81, 0x3E, 0x00, 0x81, 0x3F, 0x04, 0x81, 0x40, 0x00, + 0x81, 0x41, 0x60, 0x81, 0x42, 0x0F, 0x81, 0x43, 0x00, 0x81, 0x44, 0x04, 0x81, 0x45, 0x00, 0x81, 0x46, 0x00, 0x81, 0x47, 0x00, 0x82, 0x00, 0x02, + 0x82, 0x0B, 0x20, 0x82, 0x0D, 0x20, 0x82, 0x0F, 0x20, 0x82, 0x11, 0x20, 0x82, 0x13, 0x20, 0x82, 0x15, 0x20, 0x82, 0x17, 0x20, 0x82, 0x19, 0x20, + 0x82, 0x1B, 0x20, 0x82, 0x1D, 0x20, 0x82, 0x1F, 0x20, 0x82, 0x21, 0x20, 0x82, 0x0C, 0x00, 0x82, 0x0E, 0x00, 0x82, 0x10, 0x00, 0x82, 0x12, 0x00, + 0x82, 0x14, 0x00, 0x82, 0x16, 0x00, 0x82, 0x18, 0x00, 0x82, 0x1A, 0x00, 0x82, 0x1C, 0x00, 0x82, 0x1E, 0x00, 0x82, 0x20, 0x00, 0x82, 0x22, 0x00, + 0x82, 0x23, 0x03, 0x82, 0x24, 0x32, 0x82, 0x25, 0x00, 0x82, 0x26, 0x3F, 0x82, 0x27, 0xE5, 0x82, 0x28, 0x00, 0x82, 0x29, 0xCC, 0x82, 0x2A, 0x01, + 0x82, 0x2B, 0x8A, 0x82, 0x2C, 0x02, 0x82, 0x2D, 0xCA, 0x82, 0x2E, 0x01, 0x82, 0x2F, 0x88, 0x82, 0x30, 0x02, 0x82, 0x31, 0x06, 0x82, 0x32, 0x04, + 0x82, 0x33, 0x19, 0x82, 0x34, 0xB6, 0x82, 0x35, 0x00, 0x82, 0x36, 0x99, 0x82, 0x37, 0x01, 0x82, 0x38, 0x42, 0x82, 0x39, 0x02, 0x82, 0x3A, 0xE6, + 0x82, 0x3B, 0x01, 0x82, 0x3C, 0xAF, 0x82, 0x3D, 0x02, 0x82, 0x3E, 0x04, 0x82, 0x3F, 0x04, 0x82, 0x40, 0x44, 0x82, 0x41, 0x5B, 0x82, 0x42, 0x00, + 0x82, 0x43, 0xCC, 0x82, 0x44, 0x01, 0x82, 0x45, 0x8A, 0x82, 0x46, 0x02, 0x82, 0x47, 0x99, 0x82, 0x48, 0x01, 0x82, 0x49, 0x43, 0x82, 0x4A, 0x02, + 0x82, 0x4B, 0x06, 0x82, 0x4C, 0x05, 0x82, 0x50, 0x00, 0x82, 0x51, 0x4F, 0x82, 0x52, 0xA4, 0x82, 0x53, 0x90, 0x82, 0x54, 0xED, 0x82, 0x55, 0xDA, + 0x82, 0x56, 0x54, 0x82, 0x57, 0x6B, 0x82, 0x58, 0x00, 0x82, 0x59, 0x10, 0x82, 0x5A, 0xD6, 0x82, 0x5B, 0x90, 0x82, 0x5C, 0xC0, 0x82, 0x5D, 0x00, + 0x82, 0x5F, 0x40, 0x82, 0x00, 0x02, 0x80, 0x2A, 0x94, 0x80, 0x57, 0x27, 0x83, 0x19, 0x39, 0x80, 0x37, 0x04, 0x83, 0x0F, 0xC4, 0x83, 0x1B, 0x38, + 0x81, 0x3C, 0x01, 0x88, 0x6A, 0x04, 0x88, 0x54, 0x02, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x88, 0x16, 0x00, 0x88, 0x15, 0x31, 0x88, 0x15, 0x30, 0x88, + 0x19, 0x00, 0x90, 0x05, 0x0C, 0x01, 0x00, 0x00, 0x00, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x0C, 0x07, 0x00, 0x00, 0x00, 0x0C, 0x0F, 0x00, 0x00, 0x00, + 0x0C, 0x1F, 0x00, 0x00, 0x00, 0x0C, 0x5F, 0x00, 0x00, 0x00, 0x0C, 0x5F, 0x00, 0x00, 0x00, 0x0C, 0x5F, 0x02, 0x00, 0x00, 0x0C, 0x5F, 0x02, 0x00, + 0x00, 0x0C, 0x5F, 0x02, 0x00, 0x00, 0x0C, 0x5F, 0x02, 0x00, 0x00, 0x0C, 0x5F, 0x02, 0x00, 0x00, 0x0C, 0x5F, 0x02, 0x00, 0x00, 0x8B, 0x00, 0x00, + 0x0C, 0x5F, 0x62, 0x01, 0x00, 0x8B, 0x00, 0x00, 0x8B, 0x01, 0x00, 0x0C, 0x5F, 0x62, 0x59, 0x00, 0x8B, 0x00, 0x00, 0x8B, 0x01, 0x00, 0x0C, 0x5F, + 0x62, 0xD9, 0x05, 0x90, 0x06, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, + 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, + 0x02, 0x00, 0x00, 0x05, 0x40, 0x02, 0x00, 0x00, 0x05, 0x40, 0x22, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x40, 0x22, 0x00, 0x00, 0x05, + 0x40, 0x22, 0x00, 0x00, 0x05, 0x40, 0x22, 0x02, 0x00, 0x05, 0x40, 0x22, 0x02, 0x00, 0x05, 0x40, 0x22, 0x0A, 0x00, 0x05, 0x40, 0x22, 0x0A, 0x01, + 0x80, 0x00, 0x00, 0x00, 0x00, 0x05, 0x40, 0x22, 0x2A, 0x00, 0x05, 0x40, 0x22, 0x6A, 0x00, 0x05, 0x40, 0x22, 0xEA, 0x01, 0x80, 0x08, 0x00, 0x00, + 0x01, 0x80, 0x58, 0x00, 0x00, 0x01, 0x80, 0x58, 0x00, 0x00, 0x01, 0x80, 0x58, 0x03, 0x00, 0x01, 0x80, 0x58, 0x03, 0x00, 0x01, 0x80, 0x58, 0xC3, + 0x01, 0x01, 0x80, 0x58, 0xC3, 0x01, 0x01, 0x80, 0x58, 0xC3, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, + 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x01, 0x00, 0x02, 0x10, 0x00, 0x01, 0x00, 0x02, 0x10, + 0x00, 0x01, 0x04, 0x02, 0x10, 0x00, 0x01, 0x0C, 0x02, 0x10, 0x00, 0x01, 0x1C, 0x02, 0x10, 0x00, 0x01, 0x1C, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x03, + 0x01, 0x00, 0x00, 0x00, 0x03, 0x09, 0x00, 0x00, 0x00, 0x03, 0x09, 0x00, 0x00, 0x00, 0x03, 0x09, 0x00, 0x00, 0x00, 0x03, 0x49, 0x00, 0x00, 0x00, + 0x03, 0x49, 0x03, 0x00, 0x00, 0x03, 0x49, 0x13, 0x00, 0x00, 0x03, 0x49, 0x13, 0x00, 0x00, 0x03, 0x49, 0x93, 0x00, 0x00, 0x03, 0x49, 0x93, 0x03, + 0x00, 0x03, 0x49, 0x93, 0x0B, 0x00, 0x03, 0x49, 0x93, 0x0B, 0x00, 0x03, 0x49, 0x93, 0x2B, 0x00, 0x03, 0x49, 0x93, 0x2B, 0x00, 0x03, 0x49, 0x93, + 0x2B, 0x01, 0x03, 0x49, 0x93, 0x2B, 0x07, 0x04, 0x0E, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x09, 0x00, 0x00, 0x03, 0x49, + 0x93, 0x2B, 0x07, 0x03, 0x49, 0x93, 0x2B, 0x67, 0x04, 0x8E, 0x09, 0x00, 0x00, 0x04, 0x8E, 0x09, 0x00, 0x00, 0x04, 0x8E, 0x09, 0x08, 0x00, 0x04, + 0x8E, 0x09, 0x08, 0x00, 0x04, 0x8E, 0x09, 0x08, 0x00, 0x04, 0x8E, 0x09, 0x08, 0x01, 0x04, 0x8E, 0x09, 0x08, 0x01, 0x04, 0x8E, 0x09, 0x08, 0x05, + 0x04, 0x8E, 0x09, 0x08, 0x05, 0x04, 0x8E, 0x09, 0x08, 0x05, 0x04, 0x8E, 0x09, 0x08, 0x05, 0x05, 0x01, 0x00, 0x00, 0x00, 0x05, 0x09, 0x00, 0x00, + 0x00, 0x05, 0x19, 0x00, 0x00, 0x00, 0x05, 0x19, 0x00, 0x00, 0x00, 0x05, 0x19, 0x03, 0x00, 0x00, 0x05, 0x19, 0x03, 0x00, 0x00, 0x05, 0x19, 0x03, + 0x00, 0x00, 0x05, 0x19, 0x03, 0x00, 0x00, 0x05, 0x19, 0x43, 0x00, 0x00, 0x05, 0x19, 0xC3, 0x00, 0x00, 0x05, 0x19, 0xC3, 0x00, 0x00, 0x05, 0x19, + 0xC3, 0x18, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x05, 0x19, 0xC3, 0x38, 0x00, 0x05, 0x19, 0xC3, 0x78, 0x00, 0x05, + 0x19, 0xC3, 0x78, 0x00, 0x05, 0x19, 0xC3, 0x78, 0x00, 0x05, 0x19, 0xC3, 0x78, 0x00, 0x05, 0x19, 0xC3, 0x78, 0x40, 0x06, 0x04, 0x00, 0x00, 0x00, + 0x06, 0x24, 0x00, 0x00, 0x00, 0x06, 0x24, 0x00, 0x00, 0x00, 0x06, 0x24, 0x00, 0x00, 0x00, 0x06, 0x24, 0x02, 0x00, 0x00, 0x06, 0x24, 0x0A, 0x00, + 0x00, 0x06, 0x24, 0x2A, 0x00, 0x00, 0x06, 0x24, 0x6A, 0x00, 0x00, 0x06, 0x24, 0x6A, 0x07, 0x00, 0x06, 0x24, 0x6A, 0x07, 0x00, 0x07, 0x00, 0x00, + 0x00, 0x00, 0x07, 0x06, 0x00, 0x00, 0x00, 0x07, 0x06, 0x00, 0x00, 0x00, 0x07, 0x66, 0x00, 0x00, 0x00, 0x07, 0x66, 0x40, 0x00, 0x00, 0x07, 0x66, + 0xC0, 0x00, 0x00, 0x07, 0x66, 0xC0, 0x01, 0x00, 0x07, 0x66, 0xC0, 0x05, 0x00, 0x07, 0x66, 0xC0, 0x15, 0x00, 0x07, 0x66, 0xC0, 0x15, 0x00, 0x07, + 0x66, 0xC0, 0x15, 0x00, 0x07, 0x66, 0xC0, 0x15, 0x01, 0x07, 0x66, 0xC0, 0x15, 0x01, 0x08, 0x40, 0x00, 0x00, 0x00, 0x08, 0xC0, 0x00, 0x00, 0x00, + 0x08, 0xC0, 0x01, 0x00, 0x00, 0x07, 0x66, 0xC0, 0x15, 0x09, 0x07, 0x66, 0xC0, 0x15, 0x29, 0x07, 0x66, 0xC0, 0x15, 0x29, 0x08, 0xC0, 0x01, 0x00, + 0x00, 0x08, 0xC0, 0x41, 0x02, 0x00, 0x08, 0xC0, 0x41, 0x06, 0x00, 0x08, 0xC0, 0x41, 0x06, 0x00, 0x08, 0xC0, 0x41, 0x06, 0x00, 0x08, 0xC0, 0x41, + 0x26, 0x00, 0x08, 0xC0, 0x41, 0x26, 0x00, 0x08, 0xC0, 0x41, 0xA6, 0x00, 0x08, 0xC0, 0x41, 0xA6, 0x00, 0x08, 0xC0, 0x41, 0xA6, 0x00, 0x09, 0x07, + 0x00, 0x00, 0x00, 0x09, 0x17, 0x00, 0x00, 0x00, 0x09, 0x17, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, + 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, + 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x00, 0x00, 0x09, 0x57, 0x00, 0x08, + 0x00, 0x09, 0x57, 0x00, 0x38, 0x00, 0x09, 0x57, 0x00, 0x38, 0x00, 0x09, 0x57, 0x00, 0xB8, 0x00, 0x09, 0x57, 0x00, 0xB8, 0x05, 0x09, 0x57, 0x00, + 0xB8, 0x05, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x0A, 0x07, 0x00, 0x00, 0x00, 0x0A, 0x07, 0x00, 0x00, 0x00, 0x0A, 0x27, 0x00, 0x00, 0x00, 0x0A, 0xE7, + 0x01, 0x00, 0x00, 0x0A, 0xE7, 0x07, 0x00, 0x00, 0x0A, 0xE7, 0x07, 0x00, 0x00, 0x0A, 0xE7, 0x67, 0x00, 0x00, 0x0A, 0xE7, 0xE7, 0x02, 0x00, 0x0A, + 0xE7, 0xE7, 0x02, 0x00, 0x0A, 0xE7, 0xE7, 0x0A, 0x00, 0x0A, 0xE7, 0xE7, 0x3A, 0x00, 0x0A, 0xE7, 0xE7, 0xFA, 0x02, 0x0A, 0xE7, 0xE7, 0xFA, 0x02, + 0x0A, 0xE7, 0xE7, 0xFA, 0x1A, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x10, 0x00, 0x00, 0x00, 0x0B, 0x70, 0x00, 0x00, + 0x00, 0x0B, 0x70, 0x00, 0x00, 0x00, 0x0B, 0x70, 0x00, 0x00, 0x00, 0x0B, 0x70, 0x00, 0x00, 0x00, 0x0B, 0x70, 0x20, 0x00, 0x00, 0x0B, 0x70, 0x20, + 0x00, 0x00, 0x0B, 0x70, 0xA0, 0x00, 0x00, 0x0B, 0x70, 0xA0, 0x02, 0x00, 0x0B, 0x70, 0xA0, 0x02, 0x00, 0x0B, 0x70, 0xA0, 0x12, 0x00, 0x0B, 0x70, + 0xA0, 0x52, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x33, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x01, 0x0D, 0x00, 0x00, 0x00, 0x01, 0x0D, + 0x00, 0x00, 0x00, 0x01, 0x0D, 0x00, 0x00, 0x00, 0x01, 0x0E, 0x33, 0xD0, 0x00, 0x00, 0x0E, 0x33, 0xD0, 0x01, 0x00, 0x0E, 0x33, 0xD0, 0x03, 0x00, + 0x0E, 0x33, 0xD0, 0x03, 0x00, 0x0E, 0x33, 0xD0, 0x9B, 0x01, 0x0E, 0x33, 0xD0, 0x9B, 0x01, 0x0E, 0x33, 0xD0, 0x9B, 0x01, 0x0E, 0x33, 0xD0, 0x9B, + 0x01, 0x0E, 0x33, 0xD0, 0x9B, 0x01, 0x0E, 0x33, 0xD0, 0x9B, 0x01, 0x0E, 0x33, 0xD0, 0x9B, 0x81, 0x0F, 0x02, 0x00, 0x00, 0x00, 0x0F, 0x12, 0x00, + 0x00, 0x00, 0x0F, 0xF2, 0x0E, 0x00, 0x00, 0x0F, 0xF2, 0x0E, 0x00, 0x00, 0x0F, 0xF2, 0x0E, 0x38, 0x00, 0x0F, 0xF2, 0x0E, 0x78, 0x00, 0x0F, 0xF2, + 0x0E, 0x78, 0x00, 0x0F, 0xF2, 0x0E, 0x78, 0x02, 0x0F, 0xF2, 0x0E, 0x78, 0x3A, 0x0F, 0xF2, 0x0E, 0x78, 0x3A, 0x10, 0x00, 0x00, 0x00, 0x00, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x10, 0x90, 0x00, 0x00, 0x00, 0x10, 0x90, 0x00, 0x00, 0x00, + 0x10, 0x90, 0x14, 0x00, 0x00, 0x10, 0x90, 0x14, 0x00, 0x00, 0x10, 0x90, 0x14, 0x00, 0x00, 0x10, 0x90, 0x14, 0x04, 0x00, 0x10, 0x90, 0x14, 0x14, + 0x00, 0x10, 0x90, 0x14, 0x34, 0x00, 0x10, 0x90, 0x14, 0xB4, 0x00, 0x10, 0x90, 0x14, 0xB4, 0x00, 0x10, 0x90, 0x14, 0xB4, 0x00, 0x10, 0x90, 0x14, + 0xB4, 0x00, 0x10, 0x90, 0x14, 0xB4, 0x08, 0x11, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, + 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x11, 0x80, 0x00, 0x00, 0x00, 0x11, 0x80, 0x02, 0x00, 0x00, 0x11, 0x80, 0x0A, 0x00, 0x00, 0x11, + 0x80, 0x0A, 0x00, 0x00, 0x11, 0x80, 0x0A, 0x00, 0x00, 0x11, 0x80, 0x0A, 0x00, 0x00, 0x16, 0x00, 0x00, 0x01, 0x00, 0x00, 0x05, 0x40, 0x22, 0xEA, + 0x01, 0x80, 0x58, 0xC3, 0x01, 0x03, 0x49, 0x93, 0x2B, 0x67, 0x03, 0x49, 0x93, 0x2B, 0x67, 0x03, 0x49, 0x93, 0x2B, 0x67, 0x04, 0x8E, 0x09, 0x08, + 0x05, 0x04, 0x8E, 0x09, 0x08, 0x05, 0x05, 0x19, 0xC3, 0x78, 0x40, 0x05, 0x19, 0xC3, 0x78, 0x40, 0x06, 0x24, 0x6A, 0x07, 0x00, 0x06, 0x24, 0x6A, + 0x07, 0x00, 0x05, 0x19, 0xC3, 0x78, 0x40, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x06, 0x24, 0x6A, 0x07, 0x00, 0x07, 0x66, 0xC0, 0x15, 0x29, 0x07, 0x66, + 0xC0, 0x15, 0x29, 0x08, 0xC0, 0x41, 0xA6, 0x00, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x09, + 0x57, 0x00, 0xB8, 0x65, 0x0A, 0xE7, 0xE7, 0xFA, 0x1A, 0x0A, 0xE7, 0xE7, 0xFA, 0x1A, 0x0E, 0x33, 0xD0, 0x9B, 0x81, 0x0E, 0x33, 0xD0, 0x9B, 0x81, + 0x04, 0x8E, 0x09, 0x08, 0x05, 0x0B, 0x70, 0xA0, 0x52, 0x00, 0x0B, 0x70, 0xA0, 0x52, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x90, 0x07, 0x10, 0x90, + 0x14, 0xB4, 0x09, 0x00, 0x05, 0x00, 0x22, 0xEA, 0x00, 0x05, 0x40, 0x22, 0xEA, 0x00, 0x05, 0x00, 0x22, 0xEA, 0x00, 0x05, 0x00, 0x22, 0xEA, 0x00, + 0x05, 0x00, 0x22, 0xEA, 0x00, 0x05, 0x00, 0x22, 0xEA, 0x00, 0x05, 0x00, 0x22, 0xEA, 0x00, 0x05, 0x00, 0x22, 0xEA, 0x00, 0x05, 0x00, 0x22, 0xEA, + 0x8D, 0x32, 0x09, 0x78, 0x3A, 0x90, 0x08, 0x0F, 0x32, 0x0F, 0x78, 0x3A, 0x0E, 0x33, 0xD0, 0xB7, 0x81, 0x10, 0x90, 0x14, 0xB4, 0x08, 0x0D, 0x00, + 0x00, 0x00, 0x01, 0x0D, 0x00, 0x00, 0x00, 0x01, 0x0D, 0x00, 0x00, 0xC0, 0x01, 0x0E, 0x65, 0xD0, 0xB7, 0x81, 0x10, 0x91, 0x14, 0xB4, 0x08, 0x10, + 0x11, 0x14, 0xB4, 0x08, 0x0F, 0x32, 0x0F, 0x64, 0x3A, 0x0F, 0x32, 0x0F, 0x64, 0x12, 0x13, 0x20, 0x25, 0x82, 0x02, 0x0E, 0x65, 0xD0, 0xB6, 0x81, + 0x0E, 0x65, 0xD0, 0xB2, 0x81, 0x0D, 0x00, 0x00, 0xC0, 0x00, 0x0E, 0x65, 0xD0, 0xB3, 0x81, 0x0D, 0x00, 0x00, 0xC0, 0x01, 0x0E, 0x65, 0xD0, 0xB7, + 0x81, 0x8C, 0x25, 0x00, 0x0E, 0x65, 0xD0, 0xB3, 0x81, 0x8C, 0x1E, 0x00, 0x0E, 0x65, 0xD0, 0xB7, 0x81, 0x8B, 0x08, 0x00, 0x07, 0x66, 0xC0, 0x15, + 0x29, 0x8B, 0x09, 0x00, 0x08, 0xC0, 0x41, 0xA6, 0x00, 0x90, 0x0A, 0x8B, 0x1E, 0x00, 0x82, 0x04, 0x00, 0x86, 0x61, 0x8B, 0x18, 0x01, 0x82, 0x61, + 0x00, 0x8B, 0x1F, 0x00, 0x82, 0x05, 0x00, 0x86, 0x61, 0x8B, 0x19, 0x01, 0x82, 0x61, 0x00, 0x8B, 0x20, 0x00, 0x82, 0x06, 0x00, 0x86, 0x61, 0x8B, + 0x1A, 0x01, 0x82, 0x61, 0x00, 0x8B, 0x21, 0x00, 0x82, 0x07, 0x00, 0x86, 0x61, 0x8B, 0x1B, 0x01, 0x82, 0x61, 0x00, 0x8B, 0x22, 0x00, 0x82, 0x08, + 0x00, 0x86, 0x62, 0x8B, 0x1C, 0x01, 0x82, 0x62, 0x00, 0x8B, 0x23, 0x00, 0x82, 0x09, 0x00, 0x86, 0x62, 0x8B, 0x1D, 0x01, 0x82, 0x62, 0x00, 0x8B, + 0x0C, 0x00, 0x8B, 0x0D, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x8B, 0x0C, 0x00, 0x8B, 0x0D, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x8B, 0x0C, 0x00, + 0x8B, 0x0D, 0x00, 0x8B, 0x0E, 0x00, 0x8B, 0x0F, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x8B, 0x0C, 0x00, 0x8B, 0x0D, 0x00, 0x8B, 0x0E, 0x00, 0x8B, + 0x0F, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x8B, 0x24, 0x00, 0x83, 0x09, 0x00, 0x8B, 0x25, 0x00, 0x83, 0x0B, 0x00, 0x8B, 0x26, 0x00, 0x83, 0x0A, + 0x00, 0x8B, 0x27, 0x00, 0x83, 0x0C, 0x00, 0x8B, 0x10, 0x00, 0x8B, 0x11, 0x00, 0x8B, 0x12, 0x00, 0x8B, 0x13, 0x00, 0x14, 0xFF, 0xFF, 0xFF, 0xFF, + 0x8B, 0x14, 0x00, 0x8B, 0x15, 0x00, 0x8B, 0x16, 0x00, 0x8B, 0x17, 0x00, 0x15, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, 0x58, 0xC3, 0x01, 0x8B, 0x09, + 0x00, 0x8B, 0x0A, 0x00, 0x08, 0xC0, 0xFD, 0xA7, 0x00, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xC9, 0x3F, 0x05, 0x00, 0x05, 0x00, 0xA2, 0xEA, 0x01, 0x80, + 0xD8, 0xC3, 0x01, 0x03, 0x59, 0x93, 0x2B, 0x67, 0x03, 0x79, 0x93, 0x2B, 0x67, 0x03, 0x79, 0x93, 0x3B, 0x67, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, + 0x3F, 0x05, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x3F, 0x0D, 0x05, 0x19, 0xCB, 0x78, 0x40, 0x05, 0x19, 0xCB, 0x7C, 0x40, 0x06, 0x25, 0x6A, 0x07, + 0x00, 0x06, 0x27, 0x6A, 0x07, 0x00, 0x05, 0x19, 0xCB, 0x7C, 0x44, 0x8B, 0x0C, 0x00, 0x8B, 0x0D, 0x00, 0x8B, 0x0E, 0x00, 0x8B, 0x0F, 0x00, 0x02, + 0x10, 0x00, 0x01, 0x9C, 0x06, 0x27, 0x6A, 0x07, 0x00, 0x8B, 0x08, 0x00, 0x07, 0x66, 0xC0, 0x15, 0x29, 0x8B, 0x08, 0x00, 0x07, 0x66, 0xC0, 0x15, + 0x29, 0x8B, 0x09, 0x00, 0x8B, 0x0A, 0x00, 0x08, 0xC0, 0xFD, 0xA7, 0x00, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x09, 0x57, + 0x00, 0xB8, 0x65, 0x09, 0x57, 0x00, 0xB8, 0x65, 0x0A, 0xE7, 0xE7, 0xFA, 0x1A, 0x0A, 0xE7, 0xE7, 0xFA, 0x1A, 0x0E, 0x65, 0xD0, 0xB7, 0x85, 0x0E, + 0x65, 0xD0, 0xB7, 0x85, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x3F, 0x0D, 0x0B, 0x70, 0xA0, 0x52, 0x00, 0x0B, 0x70, 0xA0, 0x52, 0x00, 0x8B, 0x0C, + 0x00, 0x8B, 0x0D, 0x00, 0x8B, 0x0E, 0x00, 0x8B, 0x0F, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x8B, 0x02, 0x00, 0x09, 0x57, 0x00, 0xB8, 0x61, 0x8B, + 0x03, 0x00, 0x0A, 0xE7, 0xE7, 0xFA, 0x1A, 0x8B, 0x03, 0x00, 0x8B, 0x04, 0x00, 0x0A, 0xE7, 0xE9, 0xFA, 0x1A, 0x8B, 0x03, 0x00, 0x8B, 0x04, 0x00, + 0x8B, 0x05, 0x00, 0x0A, 0xE7, 0xE9, 0xFB, 0x1A, 0x8B, 0x03, 0x00, 0x8B, 0x04, 0x00, 0x8B, 0x05, 0x00, 0x8B, 0x06, 0x00, 0x0A, 0xE7, 0xE9, 0xFB, + 0x1A, 0x8B, 0x07, 0x00, 0x0B, 0x71, 0xA0, 0x52, 0x00, 0x86, 0x04, 0x86, 0x61, 0x86, 0x05, 0x86, 0x61, 0x86, 0x06, 0x86, 0x61, 0x86, 0x07, 0x86, + 0x61, 0x86, 0x08, 0x86, 0x62, 0x86, 0x09, 0x86, 0x62, 0x01, 0x80, 0xD8, 0xC3, 0x01, 0x01, 0x80, 0xC8, 0xC3, 0x01, 0x8B, 0x0C, 0x00, 0x8B, 0x0D, + 0x00, 0x8B, 0x0E, 0x00, 0x8B, 0x0F, 0x00, 0x02, 0x10, 0x00, 0x01, 0x9C, 0x03, 0x79, 0x93, 0x3B, 0x67, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x3F, + 0x0D, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x3F, 0x0D, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x7F, 0x0D, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x7F, + 0x0D, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x7F, 0x0C, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x7F, 0x0C, 0x8B, 0x0B, 0x00, 0x04, 0x8E, 0xD9, 0x7F, + 0x08, 0x05, 0x19, 0x4B, 0x7C, 0x44, 0x05, 0x19, 0x5B, 0x7C, 0x44, 0x05, 0x19, 0x5B, 0x7C, 0x44, 0x05, 0x19, 0x1B, 0x7C, 0x44, 0x05, 0x19, 0x1B, + 0x7C, 0x44, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x88, 0x16, 0x00, 0x88, 0x15, 0x31, 0x88, 0x15, 0x30, 0x88, 0x19, 0x00, 0x26, 0x14, 0x03, 0x14, 0x00, + 0x25, 0x0B, 0x0C, 0xA4, 0x33, 0x27, 0x04, 0x08, 0x04, 0x00, 0x28, 0x08, 0x08, 0x0C, 0x00, 0x29, 0x04, 0x01, 0x0C, 0x00, 0x2A, 0x90, 0x12, 0x0F, + 0x00, 0x20, 0x07, 0x94, 0x00, 0x00, 0x8E, 0xB5, 0x01, 0xAC, 0x06, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x88, 0x16, 0x00, 0x88, 0x15, 0x31, 0x88, 0x15, + 0x30, 0x88, 0x19, 0x00, 0x82, 0x4D, 0x0F, 0x82, 0x4E, 0x0F, 0x82, 0x4F, 0x00, 0x82, 0x26, 0x37, 0x82, 0x27, 0x01, 0x82, 0x28, 0x02, 0x82, 0x29, + 0x6C, 0x82, 0x2A, 0x01, 0x82, 0x2B, 0x02, 0x82, 0x2C, 0x02, 0x82, 0x31, 0x03, 0x82, 0x2D, 0x6A, 0x82, 0x2E, 0x01, 0x82, 0x2F, 0x01, 0x82, 0x30, + 0x02, 0x82, 0x32, 0x00, 0x82, 0x33, 0x38, 0x82, 0x34, 0x01, 0x82, 0x35, 0x01, 0x82, 0x36, 0xEC, 0x82, 0x37, 0x01, 0x82, 0x38, 0xB7, 0x82, 0x39, + 0x02, 0x82, 0x3E, 0x02, 0x82, 0x3A, 0xEB, 0x82, 0x3B, 0x01, 0x82, 0x3C, 0xB6, 0x82, 0x3D, 0x02, 0x82, 0x3F, 0x01, 0x82, 0x40, 0x38, 0x82, 0x41, + 0x01, 0x82, 0x42, 0x01, 0x82, 0x43, 0x6B, 0x82, 0x44, 0x01, 0x82, 0x45, 0x02, 0x82, 0x46, 0x02, 0x82, 0x4B, 0x02, 0x82, 0x47, 0x6A, 0x82, 0x48, + 0x01, 0x82, 0x49, 0x01, 0x82, 0x4A, 0x02, 0x82, 0x4C, 0x00, 0x82, 0x0B, 0x20, 0x82, 0x0D, 0x20, 0x82, 0x0F, 0x20, 0x82, 0x11, 0x20, 0x82, 0x13, + 0x20, 0x82, 0x15, 0x2B, 0x82, 0x17, 0x26, 0x82, 0x19, 0x20, 0x82, 0x1B, 0x20, 0x82, 0x1D, 0x2B, 0x82, 0x1F, 0x26, 0x82, 0x21, 0x20, 0x82, 0x23, + 0x23, 0x82, 0x24, 0x32, 0x82, 0x25, 0x00, 0x8F, 0xD1, 0x0D, 0x17, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, + 0x00, 0x17, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x01, 0x00, 0x17, 0x10, 0x00, + 0x01, 0x00, 0x17, 0x10, 0x00, 0x01, 0x00, 0x17, 0x10, 0x00, 0x01, 0x00, 0x17, 0x10, 0x00, 0x01, 0x00, 0x17, 0x10, 0x00, 0x01, 0x00, 0x17, 0x00, + 0x00, 0x01, 0x00, 0x17, 0x00, 0x00, 0x01, 0x00, 0x17, 0x00, 0x00, 0x01, 0x00, 0x17, 0x00, 0x00, 0x01, 0x00, 0x17, 0x00, 0x00, 0x01, 0x00, 0x90, + 0x0B, 0x91, 0x0E, 0x0D, 0x00, 0xFF, 0x0A, 0x26, 0x55, 0x55, 0x40, 0x06, 0xAB, 0xAA, 0x00, 0x00, 0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x55, 0x55, 0xC8, 0xFF, 0x56, 0x55, 0x03, 0x00, 0x55, 0x55, 0x03, 0x00, 0x7A, 0x00, 0xA6, 0x79, 0x90, 0xFF, 0xFF, 0xFF, 0x6F, 0x00, 0xE0, 0x7F, + 0xA0, 0x79, 0x1B, 0x8A, 0x00, 0x00, 0x20, 0x00, 0x00, 0xFE, 0x1F, 0x00, 0x00, 0xEE, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x80, 0xF5, + 0x00, 0xFE, 0x9F, 0x00, 0x00, 0x00, 0xA0, 0x00, 0x00, 0xEC, 0x9F, 0x00, 0x50, 0x3A, 0xA5, 0x6B, 0x00, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0xF0, + 0x00, 0x00, 0x00, 0xF8, 0x01, 0x00, 0x00, 0xEC, 0x01, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x90, 0xEC, 0x00, 0x00, 0x14, 0xEC, 0x01, 0x00, 0x5C, 0xF3, + 0x20, 0x07, 0x00, 0xFC, 0x00, 0x80, 0x10, 0xEC, 0x40, 0x8D, 0xEF, 0x0B, 0x60, 0x8E, 0xEF, 0x0B, 0x60, 0x07, 0x00, 0x00, 0x00, 0x00, 0x10, 0xED, + 0x80, 0x07, 0x00, 0xF8, 0xA0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC0, 0x07, 0x00, 0x04, 0x00, 0x00, 0x11, 0xEC, 0x7F, 0x99, 0x29, 0x19, + 0x00, 0x00, 0x00, 0x40, 0xFB, 0x9F, 0x9F, 0x3F, 0x00, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x04, 0x00, 0x00, 0x40, + 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, + 0x01, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x01, 0x02, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, + 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x07, + 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x05, 0x07, 0x06, 0x06, 0x06, 0x06, 0x05, 0x07, 0x06, 0x06, 0x06, 0x06, 0x05, 0x06, 0x06, 0x07, 0x06, 0x06, + 0x05, 0x06, 0x06, 0x08, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, + 0x07, 0x09, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0B, 0x03, 0x0A, 0x03, 0x0A, 0x08, 0x0C, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, + 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0D, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0E, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, + 0x03, 0x0A, 0x03, 0x0F, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x10, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x11, + 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0F, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x10, + 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x12, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x13, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x14, 0x03, 0x13, + 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x15, 0x03, 0x13, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x16, 0x03, 0x0A, 0x03, 0x17, 0x03, 0x0A, + 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x18, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x10, 0x03, 0x19, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, + 0x03, 0x0A, 0x03, 0x1A, 0x03, 0x1B, 0x03, 0x0A, 0x03, 0x1C, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x0A, 0x03, 0x04, 0x03, 0x04, + 0x09, 0x1D, 0x03, 0x01, 0x03, 0x01, 0x03, 0x01, 0x03, 0x1E, 0x03, 0x1E, 0x03, 0x1E, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, + 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x1F, 0x03, 0x20, 0x03, 0x20, 0x03, 0x21, 0x03, 0x21, 0x03, 0x01, 0x03, 0x22, 0x03, 0x1E, + 0x03, 0x1E, 0x03, 0x23, 0x03, 0x24, 0x03, 0x25, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x17, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, + 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, + 0x00, 0x01, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x12, 0x04, 0x00, 0x00, 0x00, 0x12, 0x0C, 0x00, 0x00, 0x00, 0x0E, + 0x65, 0xD0, 0xB7, 0x85, 0x0E, 0x65, 0xD0, 0xB7, 0x8D, 0x12, 0x0C, 0x00, 0x80, 0x00, 0x12, 0x0C, 0x00, 0x80, 0x00, 0x12, 0x0C, 0x00, 0x80, 0x10, + 0x1F, 0x05, 0x00, 0x00, 0x47, 0x1F, 0x05, 0x00, 0x00, 0x47, 0x12, 0x0C, 0x04, 0x80, 0x10, 0x12, 0x0C, 0x0C, 0x80, 0x10, 0x12, 0x0C, 0x1C, 0x80, + 0x10, 0x12, 0x0C, 0x3C, 0x80, 0x10, 0x12, 0x0C, 0x3C, 0x84, 0x10, 0x12, 0x0C, 0x3C, 0x8C, 0x10, 0x12, 0x0C, 0x3C, 0x9C, 0x10, 0x12, 0x0C, 0x3C, + 0xBC, 0x10, 0x12, 0x0C, 0x3C, 0xBC, 0x10, 0x8B, 0x02, 0x00, 0x09, 0x77, 0x00, 0xB8, 0x61, 0x8B, 0x02, 0x00, 0x09, 0x77, 0x00, 0xB8, 0x61, 0x8B, + 0x02, 0x00, 0x09, 0xF7, 0x00, 0xB8, 0x61, 0x8B, 0x02, 0x00, 0x09, 0xF7, 0x00, 0xB8, 0x61, 0x8B, 0x02, 0x00, 0x09, 0xF7, 0x01, 0xB8, 0x61, 0x12, + 0x0C, 0x3C, 0xBC, 0x50, 0x12, 0x0C, 0x3C, 0xBC, 0x50, 0x16, 0x00, 0x00, 0x01, 0x20, 0x1F, 0x05, 0x00, 0x00, 0x47, 0x12, 0x1C, 0x3C, 0xBC, 0x50, + 0x12, 0x1C, 0x3C, 0xBC, 0x50, 0x12, 0x5C, 0x3C, 0xBC, 0x50, 0x12, 0xDC, 0x3C, 0xBC, 0x50, 0x12, 0xDC, 0x3D, 0xBC, 0x50, 0x12, 0xDC, 0x3F, 0xBC, + 0x50, 0x12, 0xDC, 0x7F, 0xBC, 0x50, 0x12, 0xDC, 0xFF, 0xBC, 0x50, 0x12, 0xDC, 0xFF, 0xBD, 0x50, 0x12, 0xDC, 0xFF, 0xBF, 0x50, 0x12, 0xDC, 0xFF, + 0xBF, 0x51, 0x12, 0xDC, 0xFF, 0xBF, 0x53, 0x12, 0xDC, 0xFF, 0xBF, 0x57, 0x12, 0xDC, 0xFF, 0xBF, 0x57, 0x16, 0x00, 0x00, 0x01, 0x3B, 0x1F, 0x05, + 0x00, 0x06, 0x47, 0x1F, 0x6B, 0x00, 0x06, 0x47, 0x90, 0x0D, 0x8B, 0x28, 0x00, 0x82, 0x0B, 0x20, 0x8B, 0x29, 0x00, 0x82, 0x0D, 0x20, 0x8B, 0x2A, + 0x00, 0x82, 0x0F, 0x20, 0x8B, 0x2B, 0x00, 0x82, 0x11, 0x20, 0x8B, 0x2C, 0x00, 0x82, 0x1B, 0x20, 0x8B, 0x2D, 0x00, 0x82, 0x1D, 0x2B, 0x8B, 0x2E, + 0x00, 0x82, 0x1F, 0x26, 0x8B, 0x2F, 0x00, 0x82, 0x21, 0x20, 0x8B, 0x30, 0x00, 0x82, 0x13, 0x20, 0x8B, 0x31, 0x00, 0x82, 0x15, 0x2B, 0x8B, 0x32, + 0x00, 0x82, 0x17, 0x26, 0x8B, 0x33, 0x00, 0x82, 0x19, 0x20, 0xFF +}; +static const uint32_t ble_rf_addr[43] = { + 0x11900u, 0x11904u, 0x11908u, 0x1190Cu, 0x11910u, 0x11914u, 0x11918u, 0x1191Cu, + 0x11920u, 0x11924u, 0x11928u, 0x1192Cu, 0x11930u, 0x11934u, 0x11938u, 0x1193Cu, + 0x11940u, 0x11944u, 0x11950u, 0x11954u, 0x1195Cu, 0x11960u, 0x11964u, 0x14028u, + 0x1402Cu, 0x14030u, 0x14040u, 0x14044u, 0x14048u, 0x1404Cu, 0x14050u, 0x1405Cu, + 0x30308u, 0x3030Cu, 0x30F00u, 0x30F04u, 0x31004u, 0x31100u, 0x31104u, 0x31330u, + 0x31334u, 0x31338u, 0x31348u +}; +static const uint32_t ble_rf_agc[128] = { + 0x008000B6u, 0x000000F0u, 0x008009B5u, 0x000000F0u, 0x008012B4u, 0x000000F0u, 0x00801BB3u, 0x000000F0u, + 0x008024B2u, 0x000000F0u, 0x00802DB1u, 0x000000F0u, 0x008036B0u, 0x000000F0u, 0x00803FB0u, 0x000000F0u, + 0x008047B0u, 0x000000F0u, 0x00804FB0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, + 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, + 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, + 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, + 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, + 0x008057B0u, 0x000000F0u, 0x008057B0u, 0x000000F0u, 0x45103081u, 0x00001C61u, 0x49289208u, 0x00001C61u, + 0x8A28A248u, 0x000028A2u, 0x8A28A28Au, 0x000028A2u, 0x5D75D74Au, 0x000075D7u, 0x5D75D75Du, 0x000075D7u, + 0x5D75D75Du, 0x000075D7u, 0x5D75D75Du, 0x000075D7u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, + 0x82040000u, 0x00000830u, 0x85103082u, 0x00001871u, 0x5D75D747u, 0x000075D7u, 0x5D75D75Du, 0x000075D7u, + 0x5D75D75Du, 0x000075D7u, 0x5D75D75Du, 0x000075D7u, 0x40000000u, 0x00000410u, 0x03082081u, 0x00001041u, + 0x04104104u, 0x00001441u, 0x45145145u, 0x00001851u, 0x5D75D746u, 0x000075D7u, 0x5D75D75Du, 0x000075D7u, + 0x5D75D75Du, 0x000075D7u, 0x5D75D75Du, 0x000075D7u, 0xEEB6CAEAu, 0x0000C70Bu, 0xF6D74CF2u, 0x0000E78Du, + 0xFEF7CEFAu, 0x0000000Fu, 0x85103081u, 0x00002071u, 0x8D30B289u, 0x000040F3u, 0x10410410u, 0x00004104u, + 0x10410410u, 0x00004104u, 0xFFFFF800u, 0x0000FFFFu, 0x00000700u, 0x00000000u, 0x000000FFu, 0x00000000u +}; +/* trim fields: record (0 = VM 106, 1 = 107, 2 = 108, 3 = 187), byte, shift, width | kind << 7 (1: a non-zero + * byte replaces the value) (§14.5, §16.4) */ +static const uint8_t ble_rf_fields[208] = { + 0, 0, 13, 4, 0, 1, 19, 4, 1, 0, 24, 3, 1, 1, 0, 3, + 1, 2, 9, 3, 1, 3, 15, 3, 1, 4, 22, 4, 1, 5, 0, 3, + 3, 24, 8, 2, 3, 25, 0, 2, 3, 42, 10, 2, 3, 42, 14, 2, + 3, 32, 7, 2, 3, 33, 15, 1, 3, 36, 17, 2, 3, 37, 25, 1, + 3, 40, 0, 8, 3, 41, 8, 8, 3, 42, 16, 8, 3, 43, 24, 8, + 3, 44, 0, 8, 3, 45, 8, 8, 3, 46, 16, 8, 3, 47, 24, 8, + 3, 0, 0, 2, 3, 4, 2, 2, 3, 8, 4, 2, 3, 12, 6, 2, + 3, 16, 0, 2, 3, 20, 2, 2, 3, 1, 6, 2, 3, 5, 6, 2, + 3, 9, 6, 2, 3, 13, 6, 2, 3, 17, 6, 2, 3, 21, 6, 2, + 3, 26, 0, 8, 3, 27, 0, 8, 3, 28, 0, 8, 3, 29, 0, 8, + 2, 0, 0, 136, 2, 1, 0, 136, 2, 2, 0, 136, 2, 3, 0, 136, + 2, 5, 0, 136, 2, 7, 0, 136, 2, 9, 0, 136, 2, 11, 0, 136, + 2, 12, 0, 136, 2, 14, 0, 136, 2, 16, 0, 136, 2, 19, 0, 136 +}; diff --git a/platform/hal/fm1_ble.h b/platform/hal/fm1_ble.h new file mode 100644 index 0000000..64b20eb --- /dev/null +++ b/platform/hal/fm1_ble.h @@ -0,0 +1,321 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* FM-1 (AC791N / WL82) BLE baseband: the registers, the link-column port, the interrupt lines and the radio + * bring-up, for the route C driver (src/ble/ble_hw_wl82.c, FELUCCA_BLE). Written only from the clean-room fact + * sheet docs/BLE-HW-FACTS.md (branch feat/ble-facts, 41b7374; §14-§17 from d907ce3): every register access names its + * section there as "HW §n". Nothing in this file ran on a real FM-1; the emulator models only the baseband engine + * (fm1-emulator feat/ble-engine), not the radio analog side. + * + * fm1_ble_rf_init(trims) the radio in stock's second-boot order (HW §16): the captured Wi-Fi front end with + * the stored trims (hal/fm1_ble_rf.h), clocks and power, the BT analog block (HW §5.1, + * §5.4); what stays TODO(hardware) is listed in fm1_ble_rf.h + * fm1_ble_bb_init(base, size) the BLE baseband (HW §5.5): enable, timing words, the baseband RAM window + * fm1_ble_col_wr / _rd the per-link column port (HW §2.1 0x2801C/20/24, §2.3) + * fm1_ble_irq_attach(prio) IRQ 45 (event) and IRQ 29 (RX) to the driver's bodies (HW §10) + * fm1_ble_rng32() the random-number source (HW §1 0x13B00/04) */ +#pragma once +#include +#include "fm1_cc.h" +#include "fm1_irq.h" +#include "fm1_time.h" +#include "fm1_ble_rf.h" /* the captured start-up program (build/gen/ble_rf_tables.h) */ + +/* ---- BLE baseband registers (HW §2.1), all 32-bit accesses */ +#define FM1_BLE_CON (*(volatile uint32_t *)0x28000u) /* bit0 enable, 13/14 init, 4 cleared */ +#define FM1_BLE_T08 (*(volatile uint32_t *)0x28008u) /* [9:0] 70, [15:12] 0xF */ +#define FM1_BLE_T0C (*(volatile uint32_t *)0x2800Cu) /* [9:0] 70: a path delay in us [I] */ +#define FM1_BLE_T10 (*(volatile uint32_t *)0x28010u) /* 62 | 62 << 8 */ +#define FM1_BLE_T14 (*(volatile uint32_t *)0x28014u) /* 30 */ +#define FM1_BLE_T18 (*(volatile uint32_t *)0x28018u) /* 20 | 20 << 8 */ +#define FM1_BLE_COLCMD (*(volatile uint32_t *)0x2801Cu) /* column << 10 | link << 4 | op (5 write, 2 read) */ +#define FM1_BLE_COLDATA (*(volatile uint32_t *)0x28020u) /* the data word for op 5 */ +#define FM1_BLE_COLRES (*(volatile uint32_t *)0x28024u) /* the result of op 2 */ +#define FM1_BLE_IEN (*(volatile uint32_t *)0x28028u) /* bit n event (IRQ 45), bit 8+n RX (IRQ 29) */ +#define FM1_BLE_IACK (*(volatile uint32_t *)0x2802Cu) /* write 1 to acknowledge */ +#define FM1_BLE_IPND (*(volatile uint32_t *)0x28030u) /* pending, the same bits */ +#define FM1_BLE_T34 (*(volatile uint32_t *)0x28034u) /* bit0 1, [15:8] a parameter (stock 0x0A) */ +#define FM1_BLE_STAT (*(volatile uint32_t *)0x28038u) /* bit1 busy; bit7 flag, acknowledged by bit6 */ +#define FM1_BLE_G2EN (*(volatile uint32_t *)0x2804Cu) /* second group: bit n enable, bit 8+n acknowledge */ +#define FM1_BLE_G2PND (*(volatile uint32_t *)0x28050u) /* second group pending */ + +/* ---- BT analog / configuration block (HW §2.2) */ +#define FM1_BT_C00 (*(volatile uint32_t *)0x2FC00u) +#define FM1_BT_C04 (*(volatile uint32_t *)0x2FC04u) +#define FM1_BT_C08 (*(volatile uint32_t *)0x2FC08u) /* [9:0], [19:10] stored I / Q trims */ +#define FM1_BT_C0C (*(volatile uint32_t *)0x2FC0Cu) +#define FM1_BT_C10 (*(volatile uint32_t *)0x2FC10u) /* bytes 0..2 stored trims */ +#define FM1_BT_C14 (*(volatile uint32_t *)0x2FC14u) +#define FM1_BT_C18 (*(volatile uint32_t *)0x2FC18u) +#define FM1_BT_C1C (*(volatile uint32_t *)0x2FC1Cu) +#define FM1_BT_C20 (*(volatile uint32_t *)0x2FC20u) +#define FM1_BT_C24 (*(volatile uint32_t *)0x2FC24u) +#define FM1_BT_C28 (*(volatile uint32_t *)0x2FC28u) +#define FM1_BT_C40 (*(volatile uint32_t *)0x2FC40u) /* BT block enable / config [I] */ +#define FM1_BT_C48 (*(volatile uint32_t *)0x2FC48u) +#define FM1_BT_C78 (*(volatile uint32_t *)0x2FC78u) +#define FM1_BT_C7C (*(volatile uint32_t *)0x2FC7Cu) +#define FM1_BT_BLE_EN (*(volatile uint32_t *)0x2FC80u) /* bit0 BLE block enable [I] */ +#define FM1_BT_BB_BASE (*(volatile uint32_t *)0x2FC84u) /* baseband RAM base (an SRAM address) */ +#define FM1_BT_PLL_TBL (*(volatile uint32_t *)0x2FC88u) /* the PLL channel table (an SRAM address) */ +#define FM1_BT_C98 (*(volatile uint32_t *)0x2FC98u) +#define FM1_BT_C9C (*(volatile uint32_t *)0x2FC9Cu) +#define FM1_BT_CA0 (*(volatile uint32_t *)0x2FCA0u) +#define FM1_BT_BB_END (*(volatile uint32_t *)0x2FCBCu) /* baseband RAM end = base + size */ +#define FM1_BT_AGC0 (*(volatile uint32_t *)0x2FD80u) +#define FM1_BT_AGC(i) (*(volatile uint32_t *)(0x2FD84u + 4u * (i))) /* 0x2FD84 .. 0x2FD94 */ +#define FM1_BT_BRCON (*(volatile uint32_t *)0x20000u) /* BR/EDR baseband control (HW §5.1 step 4) */ +#define FM1_WL_BTEN (*(volatile uint32_t *)0x14000u) /* BT / RF enable (HW §5.1 step 3) */ +#define FM1_CLK_CON1_BT (*(volatile uint32_t *)0x10010u) /* bits 14-15: BT domain power / reset (HW §5.1) */ +#define FM1_RNG_LO (*(volatile uint32_t *)0x13B00u) /* random source (HW §1) */ +#define FM1_RNG_HI (*(volatile uint32_t *)0x13B04u) + +enum { FM1_IRQ_BLE_RX = 29, FM1_IRQ_BLE_EVENT = 45 }; /* HW §10 */ + +/* Values the fact sheet does not settle, named so nobody mistakes them for measurements. */ +#define FM1_BLE_STEP_DELAY_US 100u /* HW §5.1 step 3: "a 240-unit delay" and "delays between steps", unit and + * length unknown [M:s]; 100 us is a guess, generous for a power switch */ +#define FM1_BLE_T34_VALUE 0x0A01u /* HW §5.5 step 3: stock V15 0x0A01, demo_ble 0x0901; [15:8] unknown (U5) */ + +FM1_INLINE void fm1_ble_sync(void) { __asm__ volatile("csync" ::: "memory"); } + +/* the column port (HW §2.1 0x2801C/20, §2.3): data first, csync, then the command */ +FM1_INLINE void fm1_ble_col_wr(uint32_t link, uint32_t col, uint32_t data) +{ + FM1_BLE_COLDATA = data & 0xFFFFu; + fm1_ble_sync(); + FM1_BLE_COLCMD = col << 10 | link << 4 | 5u; +} +FM1_INLINE uint32_t fm1_ble_col_rd(uint32_t link, uint32_t col) /* HW §2.1 0x28024: op 2 */ +{ + FM1_BLE_COLCMD = col << 10 | link << 4 | 2u; + fm1_ble_sync(); + return FM1_BLE_COLRES & 0xFFFFu; +} + +/* the 24-bit running slot count of link n (HW §2.3: column 0 low 16 bits, column 14 [7:0] bits 23:16) */ +static uint32_t fm1_ble_clock(uint32_t link) +{ + uint32_t hi = fm1_ble_col_rd(link, 14) & 0xFFu, lo = fm1_ble_col_rd(link, 0), hi2 = fm1_ble_col_rd(link, 14) & 0xFFu; + if (hi2 != hi) /* the low half wrapped between the reads */ + lo = fm1_ble_col_rd(link, 0); + return hi2 << 16 | lo; +} + +/* stop link n: column 14 = 0 (HW §2.3), its interrupts off (HW §5.5 end), then wait until the engine is idle (HW §2.1 + * 0x28038 bit1 [M:s]) for at most max_us, and acknowledge what was raised meanwhile (the window that was open when the + * link stopped ends with its event interrupt: none is left pending for the next link) -> the microseconds it waited + * (>= max_us: still busy when the wait gave up; console 'blell' busy_*, stop_*). The FM-1 (blell-dev3 / dev4, + * 2026-10-09): bit1 still set 2,000 polls (~0.75 ms) after a scanning link stopped, every time. + * The wait is bounded twice: by TIMER4 (max_us), and by a count of reads that no CPU clock gets through in max_us + * (FM1_BLE_STOP_POLLS_PER_US: one read of 0x28038 and of TIMER4 per pass, each a bus access), so a TIMER4 that does + * not count (stopped, or its source gated) cannot hold the caller: boot, the main loop or a BLE interrupt. */ +#define FM1_BLE_STOP_POLLS_PER_US 64u +static uint32_t fm1_ble_link_stop(uint32_t link, uint32_t max_us) +{ + uint32_t t0, d = 0, span = max_us * FM1_TICKS_PER_US, polls = max_us * FM1_BLE_STOP_POLLS_PER_US + 1u; + fm1_ble_col_wr(link, 14, 0); + FM1_BLE_IEN &= ~(0x101u << link); /* HW §5.5: enables cleared when a link is opened */ + FM1_BLE_G2EN &= ~(0x101u << link); + FM1_BLE_IACK = 0x101u << link; /* HW §2.1: write 1 to acknowledge */ + t0 = fm1_ticks(); + while ((FM1_BLE_STAT & 2u) && (d = fm1_ticks() - t0) < span && --polls) + ; + if (!polls) + d = span; /* (the reads ran out first: counted as a timeout) */ + FM1_BLE_IACK = 0x101u << link; /* (raised while the engine finished) */ + return d / FM1_TICKS_PER_US; +} + +/* link n's interrupts on, in stock's order (HW §6 step 11 [M:t]) */ +static void fm1_ble_link_irqs_on(uint32_t link) +{ + FM1_BLE_IACK = 0x001u << link; + FM1_BLE_IACK = 0x101u << link; + FM1_BLE_G2EN = 0x100u << link; + FM1_BLE_IEN = FM1_BLE_IEN | 0x001u << link; + FM1_BLE_IEN = FM1_BLE_IEN | 0x101u << link; + FM1_BLE_G2EN = 0x101u << link; +} + +/* acknowledge and test the pending bits (HW §8: serviced when enable AND pending) */ +FM1_INLINE int fm1_ble_rx_pending(uint32_t link) { return (FM1_BLE_IEN & FM1_BLE_IPND & (0x100u << link)) != 0; } +FM1_INLINE void fm1_ble_rx_ack(uint32_t link) { FM1_BLE_IACK = 0x100u << link; } /* HW §8 IRQ 29 step 1 */ +FM1_INLINE int fm1_ble_event_pending(uint32_t link) { return (FM1_BLE_IEN & FM1_BLE_IPND & (1u << link)) != 0; } +FM1_INLINE void fm1_ble_event_ack(uint32_t link) { FM1_BLE_IACK = 1u << link; } /* HW §8 IRQ 45 step 1 */ +/* the end of the event ISR (HW §8 IRQ 45 steps 4, 5): the second group and the 0x28038 flag */ +static void fm1_ble_event_tail(uint32_t link) +{ + if (FM1_BLE_G2EN & FM1_BLE_G2PND & (1u << link)) + FM1_BLE_G2EN |= 0x100u << link; /* acknowledge; its "link timeout" is ours (ble_ll.c) */ + if (FM1_BLE_STAT & 0x80u) + FM1_BLE_STAT = 0x40u; +} + +/* the interrupt and status registers as they read now, for the console (HW §2.1): enables, pending, the second group's + * enables and pending, 0x28038 */ +static void fm1_ble_irq_regs(uint32_t r[5]) +{ + r[0] = FM1_BLE_IEN; + r[1] = FM1_BLE_IPND; + r[2] = FM1_BLE_G2EN; + r[3] = FM1_BLE_G2PND; + r[4] = FM1_BLE_STAT; +} + +FM1_INLINE uint32_t fm1_ble_rng32(void) { return FM1_RNG_LO ^ (FM1_RNG_HI * 0x9E3779B9u); } /* HW §1 */ + +/* ---- radio bring-up (HW §5.1 - §5.4, §16). Unverified on hardware in every step. */ + +/* HW §2.4: 81 entries x 3 words, one per 1 MHz channel; stock V15's form {i | i << 8, 0, 0} [M:d], meaning [I] */ +static uint32_t fm1_ble_pll_tbl[81 * 3] __attribute__((aligned(4))); + +#define FM1_BT_AGC_IDX (*(volatile uint32_t *)0x2FD98u) /* HW §2.2: the AGC table's write index (0) */ +#define FM1_BT_AGC_DATA (*(volatile uint32_t *)0x2FD9Cu) /* HW §2.2: its data port, 128 words */ + +/* The radio in stock's second-boot order (HW §16.1), with the stored trims (the data of VM 106, 107, 108, 187: + * src/ble/ble_vm.c found them in the VM or in Optimist's copy; without them the caller never gets here, §15.4): + * HW §16.1 groups 2-13 the Wi-Fi front end the BT RF init runs first (HW §5.2), from the captured program + * (hal/fm1_ble_rf.h, build/gen/ble_rf_tables.h), the trim fields byte by byte (§16.4), + * our own VCO scan (group 7); + * HW §5.1 steps 3, 4 the BT domain; + * HW §5.4 / §16.1 g. 14 the PLL channel table, the AGC table (captured) and configuration, the BT analog words. + * The clock words of HW §16.1 group 1 (0x10010 bit 10 = our UART's clock, hal/fm1_uart.h; 0x10008 bit 3 = the + * second core's start, hal/fm1_dual.h) are not the radio's: left as the firmware set them. */ +static void fm1_ble_rf_init(const uint8_t *x106, const uint8_t *x107, const uint8_t *x108, const uint8_t *x187) +{ + uint32_t i; + fm1_ble_rf_run(x106, x107, x108, x187); /* HW §16.1 groups 2-13 */ + fm1_ble_rf_section(FM1_RF_SECT_BT); /* HW §16.1 group 14 */ + /* HW §5.1 step 3: BT domain power / reset, then the BT / RF enable */ + FM1_CLK_CON1_BT &= ~(3u << 14); /* bits 14-15 cleared [M:s] */ + fm1_delay_us(FM1_BLE_STEP_DELAY_US); + FM1_WL_BTEN |= 1u << 7; /* -> 0x000C0081 in three steps [M:t] */ + fm1_delay_us(FM1_BLE_STEP_DELAY_US); + FM1_WL_BTEN = (FM1_WL_BTEN & ~(0x1Fu << 16)) | 0x0Cu << 16; + fm1_delay_us(FM1_BLE_STEP_DELAY_US); + FM1_WL_BTEN |= 1u; + fm1_delay_us(FM1_BLE_STEP_DELAY_US); + /* HW §5.1 step 4 [M:t] */ + FM1_BT_C40 |= 1u << 10; + FM1_BT_BRCON = 0xC0000000u; + FM1_BT_C40 = 0xFFFFu; + FM1_BT_C40 = 0xFCFDu; + FM1_BT_C78 = 0x0Fu; + FM1_BT_C78 = 0x3FFu; + /* (VM 110, the carrier offset -> PLL_COMP: V15 writes no 110 and a hand-made one changed nothing in the + * emulator, HW §14.5; U14) */ + /* HW §5.4: the PLL channel table, then the AGC */ + for (i = 0; i < 81u; i++) { + fm1_ble_pll_tbl[3u * i] = i | i << 8; + fm1_ble_pll_tbl[3u * i + 1u] = 0; + fm1_ble_pll_tbl[3u * i + 2u] = 0; + } + FM1_BT_PLL_TBL = (uint32_t)(uintptr_t)fm1_ble_pll_tbl; + FM1_BT_AGC_IDX = 0; /* HW §2.2, §5.4: the AGC table (captured, §17) */ + for (i = 0; i < 128u; i++) + FM1_BT_AGC_DATA = ble_rf_agc[i]; + FM1_BT_C20 = 0; /* HW §5.4 AGC config [M:t] */ + FM1_BT_AGC0 = 0x000F0000u; + FM1_BT_AGC(0) = 0x1872BF14u; + FM1_BT_AGC(1) = 0x1872BF55u; + FM1_BT_AGC(2) = 0x1872BF00u; + FM1_BT_AGC(3) = 0; + FM1_BT_AGC(4) = 0; + FM1_BT_AGC0 = 0x000F0001u; + FM1_BT_C7C |= 1u; + FM1_BT_C48 = 0xB9u; /* HW §2.2 (0xAD after the BR/EDR init, not done here) */ + FM1_BT_C00 = 0x00FFD144u; /* HW §2.2, §5.4: 0x2FC00 - 0x2FC28 [M:t] */ + FM1_BT_C04 = 0x4E143CDFu; + { /* the BT TX IQ / DC trims: bt_rf_analog_init's base values, with our calibration the compensation from the + * measured record (fm1_rf_cal.h, RF-CALIBRATION.md §5) */ + uint32_t c08 = 0x03100000u, c10 = 0x80008080u; + if (fm1_rf_cal_on && fm1_rfc_trimmed) + fm1_rf_cal_bt_trims(fm1_rfc_x187, &c08, &c10); + FM1_BT_C08 = c08; + FM1_BT_C0C = 0x80808080u; + FM1_BT_C10 = c10; + } + FM1_BT_C14 = 0x80u; + FM1_BT_C18 = 0; + FM1_BT_C1C = 0; + FM1_BT_C20 = 0x36555537u; + FM1_BT_C24 = 0x00034041u; + FM1_BT_C28 = 0x0005C000u; + FM1_BT_C98 = 0x02360236u; /* HW §2.2: constants [M:s] */ + FM1_BT_C9C = 0x36360008u; + FM1_BT_CA0 = 0x00003636u; + /* HW §5.4 then initialises the BR/EDR baseband (0x2FC44, 0x2000C ... 0x20168) and the slot timer. Not done: a + * BLE-only link layer probably needs neither (HW §10), but whether the engine needs the BT clock running is U12 */ + fm1_ble_rf_section(FM1_RF_SECT_DONE); +} + +/* HW §5.5: the BLE baseband, steps 1-4 and 6-7 (step 5, the interrupts, is fm1_ble_irq_attach) */ +static void fm1_ble_bb_init(uint32_t base, uint32_t size) +{ + FM1_BT_BLE_EN |= 1u; /* step 1 */ + FM1_BLE_CON = 1u; /* step 2 */ + FM1_BLE_T34 = FM1_BLE_T34_VALUE; /* step 3 */ + FM1_BT_BB_BASE = base; /* step 4 (the block is zeroed by the caller) */ + FM1_BT_BB_END = base + size; + FM1_BLE_CON |= 0x2000u; /* step 6 -> 0x6001 */ + FM1_BLE_CON |= 0x4000u; + FM1_BLE_CON &= ~0x10u; + FM1_BLE_T08 = (FM1_BLE_T08 & ~0x3FFu) | 70u; /* step 7 */ + FM1_BLE_T08 |= 0xF000u; + FM1_BLE_T0C = 70u; + FM1_BLE_T10 = 62u | 62u << 8; + FM1_BLE_T14 = 30u; + FM1_BLE_T18 = 20u | 20u << 8; + FM1_BLE_IEN = 0; /* HW §5.5 end: enables cleared */ + FM1_BLE_G2EN = 0; +} + +/* The interrupt entries (as fm1_isr.S), here so a build without BLE carries none of it. The C bodies are the + * driver's (src/ble/ble_hw_wl82.c). */ +void ble_wl82_event_irq(void); +void ble_wl82_rx_irq(void); +__asm__(".section .text.isr_ble_event,\"ax\",@progbits\n" + "\t.globl isr_ble_event\n" + "isr_ble_event:\n" + "\t[--sp] = {psr, rets, reti}\n" + "\t[--sp] = {r3-r0}\n" + "\tcall ble_wl82_event_irq\n" + "\t{r3-r0} = [sp++]\n" + "\t{psr, rets, reti} = [sp++]\n" + "\tcsync\n" + "\trti\n" + "\t.previous\n"); +__asm__(".section .text.isr_ble_rx,\"ax\",@progbits\n" + "\t.globl isr_ble_rx\n" + "isr_ble_rx:\n" + "\t[--sp] = {psr, rets, reti}\n" + "\t[--sp] = {r3-r0}\n" + "\tcall ble_wl82_rx_irq\n" + "\t{r3-r0} = [sp++]\n" + "\t{psr, rets, reti} = [sp++]\n" + "\tcsync\n" + "\trti\n" + "\t.previous\n"); +extern void isr_ble_event(void); +extern void isr_ble_rx(void); + +/* the two BLE interrupts masked (hold 1) or let go (0) in the interrupt controller, their priority kept: the main loop + * holds them while it changes the link layer's state (a pending one is taken when they are let go) */ +static void fm1_ble_irqs_hold(int hold) +{ + static const uint8_t irq[2] = {FM1_IRQ_BLE_EVENT, FM1_IRQ_BLE_RX}; + uint32_t i; + for (i = 0; i < 2u; i++) { + uint32_t bit = 1u << ((irq[i] & 7u) * 4u); + if (hold) + FM1_ICFG(irq[i]) &= ~bit; + else + FM1_ICFG(irq[i]) |= bit; + } +} + +/* HW §5.5 step 5, §10: stock registers both at priority 2 on CPU 0. IRQs off. */ +static void fm1_ble_irq_attach(uint32_t prio) +{ + fm1_irq_attach(FM1_IRQ_BLE_EVENT, isr_ble_event, prio); + fm1_irq_attach(FM1_IRQ_BLE_RX, isr_ble_rx, prio); +} diff --git a/platform/hal/fm1_ble_rf.h b/platform/hal/fm1_ble_rf.h new file mode 100644 index 0000000..b1b27f0 --- /dev/null +++ b/platform/hal/fm1_ble_rf.h @@ -0,0 +1,514 @@ +/* SPDX-License-Identifier: GPL-3.0-only OR MPL-2.0 */ +/* FM-1 (AC791N / WL82) radio start-up, the part before the BT block: the shared Wi-Fi front end that the BT RF + * init runs first (docs/BLE-HW-FACTS.md §5.2, §16; branch feat/ble-facts d907ce3, "HW §n" below). Included by + * hal/fm1_ble.h in a BLE build with the real driver. + * + * The long constant parts (§16.1 groups 2-6, 8-13: about 34,000 register words on a second boot) are a small program + * in ble_rf_tables_v15.h, captured by tools/ble_rf_capture.py from the stock V15 firmware in the emulator and committed + * (tools/build.py puts it, or a fresh capture, at build/gen/ble_rf_tables.h). This file runs it, in boot-2 order: + * + * register write §16.1 groups 2, 3, 5, 6, 8, 9, 12 (0x11900-0x11964, 0x14040-0x1405C, the MAC window); + * bit 14 of 0x11900 kept as found (§16.2: a periodic routine's bit, not a trim) + * BBP window write / read §16.3: entry address, data, commit 1 / address, commit 2, the read-back register; + * direct BBP registers; the port 0x3101C (§5.2: bit 17 start, bit 16 read) + * RF-die LUT words §5.2 SPI port 0x14028 / 0x1402C, the five-high five-low kick (§16.1 group 11) + * trim field §14.5, §16.4: the next write takes a field from VM 106 / 107 / 108 / 187 (the bytes + * given to fm1_ble_rf_run); a read-modify-write field goes into the last read-back + * delay the gaps of 20 us or more in stock's trace + * VCO scan §16.1 group 7: our own search (fm1_ble_vco_scan below), not stock's + * replay §16.1 group 10: the BBP reload, the same as the first load (group 4) + * skipped §16.2: the window-D read-back loop (DC / IQ [I]), TODO(hardware) + * section marker where a §16.1 group starts (found by register pattern: ble_rf_capture.py sections()): + * 2 analog word, 3 radio config, 4 BBP first load, 5 crystal trim (VM 106), 6 analog init, + * 7 VCO scan, 8 post-scan set-up, 10 BBP second phase, 11 RF-die LUT, 13 VM 108; then + * fm1_ble_rf_init marks 14 (the BT block, hal/fm1_ble.h) and 15 (done). The console's + * 'bletrim' prints the last one entered and the set: on a unit where the start-up stops, + * the group it stopped in + * + * TODO(hardware), the unknowns in HW §12 and §16.2: + * - the window-D read-back loop (§16.2, 3,537 transactions in stock's boot 2): left out; its results depend on + * read-backs the emulator returns as 0 (U17). §18.3 step 3, the read-back build: write a window entry and read + * it back through 0xD3 (a read-back console command still to write, HW §18), then decide how to measure and + * write those entries; + * - the RF-die LUT words a stored trim changes (VM 107 -> entries 0xE0-0xFF of both words, VM 187 bytes 48-63, the + * scan -> word-1 entries 0x00-0x7F): written as captured (the emulator's calibration), their mapping unknown. + * §16.5 row 1: after the scan, read the LUT back (SPI command 0x6); + * - the VCO band and the final 0x11934-0x11940: the scan below finds an in-range band, but stock's final writes + * (constants of the capture) are kept; compare with the emulator's on hardware (§18.3 step 3); + * - the BT TX trims (0x2FC08, 0x2FC10: §16.2, live from BBP read-backs): hal/fm1_ble.h keeps stock's first values; + * - delays: stock's gaps in the emulator, not a datasheet's settle times. */ +#pragma once +#include +#include "fm1_cc.h" +#include "fm1_irq.h" +#include "fm1_time.h" +#include "ble_rf_tables.h" /* build/gen: tools/build.py copies firmware/hal/ble_rf_tables_v15.h or a fresh capture there */ + +#if !defined(BLE_RF_TABLES_FORMAT) || BLE_RF_TABLES_FORMAT != 3 +#error "build/gen/ble_rf_tables.h is from another tools/ble_rf_capture.py: capture it again or update ble_rf_tables_v15.h" +#endif + +#define FM1_RF_REG(a) (*(volatile uint32_t *)(uintptr_t)(a)) +#define FM1_BBP_PORT (*(volatile uint32_t *)0x3101Cu) /* HW §5.2: bit17 start, bit16 read, [15:8] reg, [7:0] data */ +#define FM1_RFSPI_CTL (*(volatile uint32_t *)0x14028u) /* HW §5.2: [22:20] busy, 0x10000 | address << 8 | command */ +#define FM1_RFSPI_DATA (*(volatile uint32_t *)0x1402Cu) +#define FM1_RFSPI_WAIT (*(volatile uint32_t *)0x14034u) /* written 0 while waiting (HW §5.2) */ +#define FM1_WL_A00 0x11900u /* HW §16.2: bit 14 kept */ +#define FM1_WL_VCO_EN (*(volatile uint32_t *)0x11934u) /* HW §16.1 group 7: bit 24 pulsed per step */ +#define FM1_WL_VCO_BAND (*(volatile uint32_t *)0x11938u) /* [25:19] the band; bits 16, 18 pulsed per step */ +#define FM1_WL_VCO_FINE (*(volatile uint32_t *)0x1193Cu) +#define FM1_WL_CAL_START (*(volatile uint32_t *)0x11968u) /* bit 28: start a comparator measurement */ +#define FM1_WL_CAL_STROBE (*(volatile uint32_t *)0x11978u) /* strobe 1 x 8 then 0; read: bit 17 low, bit 18 high */ + +/* values the sheet does not settle, named so nobody mistakes them for measurements */ +#define FM1_BBP_POLLS 1000u /* the BBP start bit polled to 0 (stock reads it once; the bound is ours) */ +#define FM1_RFSPI_POLLS 1000u /* HW §5.2 busy [22:20]; the bound is ours */ +#define FM1_VCO_BANDS 64u /* stock's scan used bands 0..63 (§16.1 group 7, 0x11938 [25:19]) */ +#define FM1_VCO_EDGE_US 2u /* between the step's pulse edges (stock: ~2 us in the emulator) [I] */ +#define FM1_VCO_SETTLE_US 50u /* before a measurement (stock: ~45 us in the emulator) [I] */ + +/* §16.1 groups run as one burst: decoded first (trim fields applied), then written by fm1_rf_burst_run from RAM + * with the interrupts off, so nothing reads flash between the group's first and last write. Group 5, the 0x11930 + * ramp (1, 3, 7, 0xF, 0x1F, 0x5F, 0x25F, then the VM 106 trims): on hardware, rf_init hung in group 5 in exactly the + * builds where a flash data-cache line of ble_rf_prog began right after the write of 3 (ble_rf_prog at 8 mod 32: + * 1f0ab85, 3a153c3), and ran in the builds where the first line began after 0x5F (24 mod 32: 1cc6e04, 510e616), the + * code identical. [I] the ramp's first steps leave the flash path (XIP) unusable until it is complete, so a flash + * access there never returns and the watchdog resets. A group that holds anything but register writes and trim + * fields, or more than FM1_RF_BURST_MAX writes, runs op by op as before (rf_burst 0 in 'bletrim'). */ +#define FM1_RF_BURST_GROUPS (1u << 5) +#define FM1_RF_BURST_MAX 32u /* group 5 has 16 writes (§16.1: 14 + 2) */ + +struct fm1_ble_rf_stat { /* what the start-up did, for the console (io/console.c 'bletrim') */ + uint32_t ops, bbp_timeouts, spi_timeouts, lut_words, trims, skipped, delay_us; + uint32_t sections; /* bit g: §16.1 group g entered (section markers) */ + uint32_t scan_result; /* the last comparator word */ + uint32_t group_op; /* ops when the last group was entered */ + uint8_t ran, scan_found, scan_band, scan_steps, bad_op; + uint8_t burst; /* writes of the last burst group (FM1_RF_BURST_GROUPS); 0: none ran */ + volatile uint8_t section; /* the last group entered (0: not started) */ +}; +#define FM1_RF_SECT_BT 14u /* the BT block (hal/fm1_ble.h fm1_ble_rf_init, HW §16.1 group 14) */ +#define FM1_RF_SECT_DONE 15u + +/* The BLE breadcrumb: kept in .noinit, so it survives a watchdog reset (not a power cycle). main.c moves it to + * prev / prev_irqs at boot (fm1_ble_crumb_boot) and the console's 'dbg' prints both. now: bits [31:24] 0xB1 (the word + * is valid), [23:16] the step of the BLUETOOTH ON path (FM1_BLE_STEP_*), [15:8] rf_ops / 256 at the last rf_init + * group, [7:0] that group (§16.1). irqs: the BLE interrupts taken since that ON (a storm shows as a huge count). + * op: rf_init's op count (rf_ops) when the last op began; gop: that op's index within its group (the group's marker + * is 0; in a burst group, FM1_RF_BURST_GROUPS: op is the group's first op, gop the write, 1..rf_burst); addr: the last access begun, so a hang names it: a register's address, 0xBB0000 | BBP register << 8 | data + * for a BBP transaction (port 0x3101C), 0x5B0000 | command << 8 | address for an RF-die SPI command (port 0x14028). + * stop: the last link stop (hal/fm1_ble.h fm1_ble_link_stop through ble_hw_wl82.c hw_stop): 0x5D000000 | path << 16 + * (BDS_*) while it waits for the engine, 0x5E000000 | path << 16 | the microseconds it waited (at most 0xFFFF) once + * done: a hang in that wait names it. + * (New words go last: a reflash moves none of the older ones.) */ +enum { + FM1_BLE_STEP_NONE, FM1_BLE_STEP_SET_ON, FM1_BLE_STEP_STACK_INIT, FM1_BLE_STEP_RF_INIT, FM1_BLE_STEP_BB_INIT, + FM1_BLE_STEP_STARTED, FM1_BLE_STEP_ENABLE, FM1_BLE_STEP_LINK_STOP, FM1_BLE_STEP_LINK_OPEN, FM1_BLE_STEP_ADV_PROG, + FM1_BLE_STEP_ADV_STARTED, FM1_BLE_STEP_IRQS_ON, FM1_BLE_STEP_RUNNING, FM1_BLE_STEP_SET_OFF +}; +static volatile struct { + uint32_t now, irqs, prev, prev_irqs; + uint32_t op, gop, addr, prev_op, prev_gop, prev_addr; + uint32_t stop, prev_stop; +} fm1_ble_bc __attribute__((section(".noinit.ble"))); +#if defined(FELUCCA_DUAL) && FELUCCA_DUAL +/* hal/fm1_dual.h fm1_dual_snap: where the BLE start-up / link was when an exception came (2026-10-15: CPU1 faults only + * in BLE builds) */ +#define FM1_DUAL_SNAP_BLE 1 +static void fm1_dual_snap_ble(fm1_c1_snap_t *s) +{ + s->ble[0] = fm1_ble_bc.now; + s->ble[1] = fm1_ble_bc.irqs; + s->ble[2] = fm1_ble_bc.op; + s->ble[3] = fm1_ble_bc.gop; + s->ble[4] = fm1_ble_bc.addr; +} +#endif +#define fm1_ble_crumb fm1_ble_bc.now +#define fm1_ble_crumb_irqs fm1_ble_bc.irqs +static uint32_t fm1_ble_step_at[16]; /* TIMER4 / 24000 (ms) when each step was first reached (0: not yet; the + * console's boot: against CPU1's start, 2026-10-15) */ +FM1_INLINE void fm1_ble_step(uint32_t step) +{ + fm1_ble_crumb = 0xB1000000u | (step & 0xFFu) << 16 | (fm1_ble_crumb & 0xFFFFu); + if (!fm1_ble_step_at[step & 15u]) + fm1_ble_step_at[step & 15u] = 1u + fm1_ticks() / (1000u * FM1_TICKS_PER_US); +} +static void fm1_ble_crumb_boot(void) /* at boot (main.c): what the last run left, then from zero */ +{ + fm1_ble_bc.prev = fm1_ble_bc.now >> 24 == 0xB1u ? fm1_ble_bc.now : 0u; /* (a power cycle: RAM noise -> 0) */ + fm1_ble_bc.prev_irqs = fm1_ble_bc.prev ? fm1_ble_bc.irqs : 0u; + fm1_ble_bc.prev_op = fm1_ble_bc.prev ? fm1_ble_bc.op : 0u; + fm1_ble_bc.prev_gop = fm1_ble_bc.prev ? fm1_ble_bc.gop : 0u; + fm1_ble_bc.prev_addr = fm1_ble_bc.prev ? fm1_ble_bc.addr : 0u; + fm1_ble_bc.prev_stop = fm1_ble_bc.prev ? fm1_ble_bc.stop : 0u; + fm1_ble_bc.now = fm1_ble_bc.irqs = 0; + fm1_ble_bc.op = fm1_ble_bc.gop = fm1_ble_bc.addr = fm1_ble_bc.stop = 0; +} + +static struct fm1_ble_rf_stat fm1_ble_rf_stat; +static void fm1_ble_rf_section(uint32_t g) +{ + fm1_ble_rf_stat.section = (uint8_t)g; + fm1_ble_rf_stat.group_op = fm1_ble_rf_stat.ops; + fm1_ble_crumb = (fm1_ble_crumb & 0xFFFF0000u) | (fm1_ble_rf_stat.ops >> 8 & 0xFFu) << 8 | (g & 0xFFu); + fm1_ble_rf_stat.sections |= 1u << (g & 31u); +} + +static uint32_t fm1_bbp(uint32_t reg, uint32_t data, uint32_t rd) /* one BBP transaction -> the port's [7:0] */ +{ + uint32_t c = BLE_RF_BBP_FLAGS | rd << 16 | reg << 8 | data, i; + fm1_ble_bc.addr = 0xBB0000u | (reg & 0xFFu) << 8 | (data & 0xFFu); + FM1_BBP_PORT = c; + FM1_BBP_PORT = c | 1u << 17; /* HW §5.2: the command, then with the start bit */ + for (i = 0; i < FM1_BBP_POLLS && (FM1_BBP_PORT & 1u << 17); i++) + ; + if (i == FM1_BBP_POLLS) + fm1_ble_rf_stat.bbp_timeouts++; + return FM1_BBP_PORT & 0xFFu; +} + +/* the BBP windows (HW §16.3): window w's commit, address, data, read-back = 0xC8 + 4w .. 0xCB + 4w */ +static void fm1_bbp_win_wr(uint32_t w, uint32_t entry, uint32_t v) +{ + fm1_bbp(0xC9u + 4u * w, entry, 0); + fm1_bbp(0xCAu + 4u * w, v & 0xFFu, 0); + fm1_bbp(0xC8u + 4u * w, 1, 0); +} +static uint32_t fm1_bbp_win_rd(uint32_t w, uint32_t entry) /* [I] that it returns the entry: U17 */ +{ + fm1_bbp(0xC9u + 4u * w, entry, 0); + fm1_bbp(0xC8u + 4u * w, 2, 0); + return fm1_bbp(0xCBu + 4u * w, 0, 1); +} + +static void fm1_rfspi(uint32_t addr, uint32_t cmd, uint32_t data) /* HW §5.2: one RF-die SPI command */ +{ + uint32_t i; + fm1_ble_bc.addr = 0x5B0000u | (cmd & 0xFu) << 8 | (addr & 0xFFu); + for (i = 0; i < FM1_RFSPI_POLLS && (FM1_RFSPI_CTL >> 20 & 7u); i++) + FM1_RFSPI_WAIT = 0; + if (i == FM1_RFSPI_POLLS) + fm1_ble_rf_stat.spi_timeouts++; + FM1_RFSPI_DATA = data; + FM1_RFSPI_CTL = 0x10000u | (addr & 0xFFu) << 8 | (cmd & 0xFu); + for (i = 0; i < 5u; i++) /* the kick: bit 4 five times high, five times low */ + FM1_RFSPI_CTL |= 0x10u; + for (i = 0; i < 5u; i++) + FM1_RFSPI_CTL &= ~0x10u; +} + +/* Our own calibration (fm1_rf_cal.h, JieLi's, Apache-2.0): with fm1_rf_cal_on set before fm1_ble_rf_run, the replay + * measures this unit's radio instead of taking a stored record 187: the stock VCO scan at group 7's scan op, the trim + * before the first write that carries a 187 field (after group 8's PLL set-up), then every 187 field, the RF-die + * table's banks (word 1, entries 0-127) and RX DC (word 0, 128-223) from what it measured. The x187 given to + * fm1_ble_rf_run is ignored then. docs/bt/RF-CALIBRATION.md. */ +#include "fm1_rf_cal.h" +static uint8_t fm1_rf_cal_on; /* set by the firmware: measure (1), or the stored 187 (0) */ +static struct fm1_rf_cal fm1_rfc; /* what was measured (the log reads it) */ +static uint8_t fm1_rfc_x187[68]; /* the record built from it */ +static uint8_t fm1_rfc_scanned, fm1_rfc_trimmed; +static int fm1_rfc_scan_rc, fm1_rfc_trim_rc; + +/* the rest of the replay with measured values: a 187 field's write gets the record's true fields (the captured ones + * are 1-2-bit slices found by perturbation) */ +static int fm1_rfc_is187(const uint8_t *trim, uint32_t nt) +{ + uint32_t i; + for (i = 0; i < nt; i++) + if ((ble_rf_fields[4u * trim[i]] & 3u) == 3u) + return 1; + return 0; +} +static void fm1_rfc_before_187(void) /* the first 187 field: measure now */ +{ + if (fm1_rf_cal_on && !fm1_rfc_trimmed) { + fm1_rfc_trimmed = 1; + fm1_rfc_trim_rc = fm1_rf_cal_trim(&fm1_rfc, fm1_rfc_x187); + } +} +static uint32_t fm1_rfc_lut(uint32_t entry, uint32_t cmd, uint32_t w) /* an RF-die word, patched */ +{ + if (!fm1_rf_cal_on) + return w; + if (cmd == 0xDu && entry < 128u && fm1_rfc_scanned) + return fm1_rf_cal_rfd_w1(&fm1_rfc, entry, w); + if (cmd == 0xEu && entry >= 128u && entry < 224u && fm1_rfc_trimmed) + return fm1_rf_cal_rfd_w0(entry, w, fm1_rfc_x187); + return w; +} + +/* §16.1 group 7, our own search (not stock's): with the fine code stock starts from, find a band whose comparator + * reads neither low (bit 17) nor high (bit 18): bisection over FM1_VCO_BANDS, a higher band when low. The step: + * the band into 0x11938 [25:19], 0x11938 bits 16 / 18 and 0x11934 bit 24 pulsed low then high, 0x11968 bit 28, + * eight strobes of 0x11978 then 0, the comparator in 0x11978 (the registers and the order as stock's boot-2 trace + * shows them: BLE-STACK.md §8.1). Its result is reported only: stock's final band and fine code follow as constants + * (TODO(hardware) above). */ +static void fm1_ble_vco_scan(uint32_t fine0) +{ + uint32_t lo = 0, hi = FM1_VCO_BANDS - 1u, b, r, i; + FM1_WL_VCO_FINE = fine0; + fm1_ble_rf_stat.scan_found = 0; + fm1_ble_rf_stat.scan_steps = 0; + while (lo <= hi) { + b = (lo + hi) / 2u; + FM1_WL_VCO_BAND = (FM1_WL_VCO_BAND & ~(0x7Fu << 19)) | b << 19; + FM1_WL_VCO_BAND &= ~(1u << 16); + FM1_WL_VCO_BAND &= ~(1u << 18); + FM1_WL_VCO_EN &= ~(1u << 24); + fm1_delay_us(FM1_VCO_EDGE_US); + FM1_WL_VCO_BAND |= 1u << 16; + fm1_delay_us(FM1_VCO_EDGE_US); + FM1_WL_VCO_EN |= 1u << 24; + FM1_WL_VCO_BAND |= 1u << 18; + fm1_delay_us(FM1_VCO_SETTLE_US); + FM1_WL_CAL_START |= 1u << 28; + for (i = 0; i < 8u; i++) + FM1_WL_CAL_STROBE = 1; + FM1_WL_CAL_STROBE = 0; + r = FM1_WL_CAL_STROBE; + fm1_ble_rf_stat.scan_steps++; + fm1_ble_rf_stat.scan_result = r; + fm1_ble_rf_stat.scan_band = (uint8_t)b; + if (r & 1u << 17) + lo = b + 1u; /* low: a higher band */ + else if (r & 1u << 18) { + if (!b) + break; + hi = b - 1u; /* high: a lower band */ + } else { + fm1_ble_rf_stat.scan_found = 1; + break; + } + } +} + +static uint32_t fm1_rf_field(uint32_t v, uint32_t f, const uint8_t *const rec[4]) /* §14.5 / §16.4 */ +{ + const uint8_t *d = &ble_rf_fields[4u * f]; + uint32_t x = rec[d[0] & 3u][d[1]], s = d[2], w = d[3] & 0x7Fu, m; + if (d[3] & 0x80u) /* VM 108: a non-zero byte replaces the default */ + return x ? x : v; + m = ((1u << w) - 1u) << s; + return (v & ~m) | (x << s & m); +} + +static uint32_t fm1_rf_u32(const uint8_t *p) { return p[0] | p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; } + +/* the burst's writes, from RAM: no flash fetch, no flash data (a and v are on the caller's stack, fm1_ble_bc is RAM) + * between the first write and the last. tools/build.py checks it links into .ram_text. */ +__attribute__((section(".ram_text"), noinline, used)) +static void fm1_rf_burst_run(const uint32_t *a, const uint32_t *v, uint32_t n) +{ + uint32_t i; + for (i = 0; i < n; i++) { + fm1_ble_bc.gop = i + 1u; + fm1_ble_bc.addr = a[i]; + FM1_RF_REG(a[i]) = v[i]; + } +} + +/* a group of FM1_RF_BURST_GROUPS, from its first op at pc: decode its register writes and trim fields up to the next + * section marker, then write them in one burst with the interrupts off (icfg bit 9 is the global enable that + * cli / sti clear and set: the emulator's model [I]). -> the pc after the group, or pc itself when the group holds + * anything else (the caller then runs it op by op) */ +static uint32_t fm1_ble_rf_burst(uint32_t pc, uint32_t end, const uint8_t *const rec[4]) +{ + const uint8_t *p = ble_rf_prog; + uint32_t a[FM1_RF_BURST_MAX], v[FM1_RF_BURST_MAX], n = 0, ops = 0, trims = 0, q = pc, i, ie; + void (*volatile run)(const uint32_t *, const uint32_t *, uint32_t) = fm1_rf_burst_run; /* (XIP -> RAM: a + * direct call does not reach, hal/fm1_clock.h fm1_clk_far) */ + uint8_t trim[8], nt = 0; + while (q < end && p[q] != 0x90u) { + if (p[q] < 0x80u) { + if (n == FM1_RF_BURST_MAX || q + 5u > end || ble_rf_addr[p[q]] == FM1_WL_A00) + return pc; /* (0x11900 needs a read: not in a burst) */ + a[n] = ble_rf_addr[p[q]]; + v[n] = fm1_rf_u32(p + q + 1); + for (i = 0; i < nt; i++) + v[n] = fm1_rf_field(v[n], trim[i], rec); + n++; + nt = 0; + q += 5; + } else if (p[q] == 0x8Bu && q + 3u <= end && nt < sizeof trim && p[q + 1] < BLE_RF_NFIELDS) { + trim[nt++] = p[q + 1]; /* (a read-back field: only window writes use it) */ + trims++; + q += 3; + } else + return pc; + ops++; + } + if (nt) + return pc; /* a trim field for an op outside the group */ + fm1_ble_bc.op = fm1_ble_rf_stat.ops + 1u; + ie = fm1_icfg() & 0x200u; + fm1_irq_off(); + run(a, v, n); + if (ie) + fm1_irq_on(); + fm1_ble_rf_stat.ops += ops; + fm1_ble_rf_stat.trims += trims; + fm1_ble_rf_stat.burst = (uint8_t)n; + return q; +} + +/* one op more for the console and the breadcrumb (each write of a packed op counts as the op it replaced) */ +static void fm1_ble_rf_tick(void) +{ + fm1_ble_rf_stat.ops++; + fm1_ble_bc.op = fm1_ble_rf_stat.ops; + fm1_ble_bc.gop = fm1_ble_rf_stat.ops - fm1_ble_rf_stat.group_op; +} + +/* the packed ops (capture format 3, tools/ble_rf_pack.py), write for write the format-2 ops they replace: + * OP_LUT2 0x91: cmd A, cmd B, first entry, count - 1, nA, nB, the deltas (4 bytes each), then count pairs of delta + * indices (A's word, then B's, for each entry; a word is its command's last + the delta, from 0) -> the bytes used */ +static uint32_t fm1_ble_rf_lut2(const uint8_t *p) +{ + uint32_t n = p[4] + 1u, na = p[5], wa = 0, wb = 0, i; + const uint8_t *da = p + 7, *db = da + 4u * na, *ix = db + 4u * p[6]; + for (i = 0; i < n; i++) { + if (i) + fm1_ble_rf_tick(); + wa += fm1_rf_u32(da + 4u * ix[2u * i]); + fm1_rfspi(p[3] + i, p[1], fm1_rfc_lut(p[3] + i, p[1], wa)); + fm1_ble_rf_tick(); + wb += fm1_rf_u32(db + 4u * ix[2u * i + 1u]); + fm1_rfspi(p[3] + i, p[2], fm1_rfc_lut(p[3] + i, p[2], wb)); + } + fm1_ble_rf_stat.lut_words += 2u * n; + return (uint32_t)(ix + 2u * n - p); +} + +/* OP_WWG 0x92: window, n, n entries, records r, then r x n values: the window writes of the n entries, r times */ +static uint32_t fm1_ble_rf_wwg(const uint8_t *p) +{ + uint32_t n = p[2], r = p[3u + n], k, j; + const uint8_t *v = p + 4u + n; + for (k = 0; k < r; k++) + for (j = 0; j < n; j++) { + if (k | j) + fm1_ble_rf_tick(); + fm1_bbp_win_wr(p[1] & 3u, p[3u + j], *v++); + } + return (uint32_t)(v - p); +} + +/* run ble_rf_prog[pc, end) (one level of replay); rec = the data of VM 106, 107, 108, 187 */ +static void fm1_ble_rf_exec(uint32_t pc, uint32_t end, const uint8_t *const rec[4], int depth) +{ + const uint8_t *p = ble_rf_prog; + uint8_t trim[8], rmw = 0, nt = 0; + uint32_t last = 0, v, a, i, n; + while (pc < end) { + uint32_t op = p[pc]; + fm1_ble_rf_tick(); + if (op < 0x80u) { /* a register write */ + a = ble_rf_addr[op]; + v = fm1_rf_u32(p + pc + 1); + fm1_ble_bc.addr = a; + if (a == FM1_WL_A00) + v = (v & ~(1u << 14)) | (FM1_RF_REG(a) & 1u << 14); + if (fm1_rf_cal_on && fm1_rfc_is187(trim, nt)) { + fm1_rfc_before_187(); + for (i = 0; i < nt; i++) + if ((ble_rf_fields[4u * trim[i]] & 3u) != 3u) + v = fm1_rf_field(v, trim[i], rec); + v = fm1_rf_cal_reg(a, v, fm1_rfc_x187); + } else + for (i = 0; i < nt; i++) + v = fm1_rf_field(v, trim[i], rec); + if (fm1_rf_cal_on && fm1_rfc_scanned && a == (uint32_t)(uintptr_t)&FM1_WL_VCO_BAND) + v = (v & ~(0x7Fu << 19)) | (uint32_t)fm1_rfc.bank121 << 19; /* our scan's bank, not the capture's */ + FM1_RF_REG(a) = v; + nt = rmw = 0; + pc += 5; + } else if ((op & 0xFCu) == 0x80u) { /* a window write */ + v = rmw ? last : p[pc + 2]; + if (fm1_rf_cal_on && fm1_rfc_is187(trim, nt)) { + fm1_rfc_before_187(); + for (i = 0; i < nt; i++) + if ((ble_rf_fields[4u * trim[i]] & 3u) != 3u) + v = fm1_rf_field(v, trim[i], rec); + v = fm1_rf_cal_win(op & 3u, p[pc + 1], v, fm1_rfc_x187); + } else + for (i = 0; i < nt; i++) + v = fm1_rf_field(v, trim[i], rec); + fm1_bbp_win_wr(op & 3u, p[pc + 1], v); + nt = rmw = 0; + pc += 3; + } else if ((op & 0xFCu) == 0x84u) { /* a window read */ + last = fm1_bbp_win_rd(op & 3u, p[pc + 1]); + pc += 2; + } else if (op == 0x88u) { + fm1_bbp(p[pc + 1], p[pc + 2], 0); + pc += 3; + } else if (op == 0x89u) { + last = fm1_bbp(p[pc + 1], 0, 1); + pc += 2; + } else if (op == 0x8Au) { /* LUT words: command, first entry, count, words */ + n = p[pc + 3]; + for (i = 0; i < n; i++) + fm1_rfspi(p[pc + 2] + i, p[pc + 1], fm1_rfc_lut(p[pc + 2] + i, p[pc + 1], fm1_rf_u32(p + pc + 4 + 4u * i))); + fm1_ble_rf_stat.lut_words += n; + pc += 4u + 4u * n; + } else if (op == 0x8Bu) { /* a trim field for the next write */ + if (nt < sizeof trim && p[pc + 1] < BLE_RF_NFIELDS) + trim[nt++] = p[pc + 1]; + else + fm1_ble_rf_stat.bad_op = (uint8_t)op; + rmw |= p[pc + 2] & 1u; + fm1_ble_rf_stat.trims++; + pc += 3; + } else if (op == 0x8Cu) { + n = p[pc + 1] | p[pc + 2] << 8; + fm1_delay_us(n); + fm1_ble_rf_stat.delay_us += n; + pc += 3; + } else if (op == 0x8Du) { + if (fm1_rf_cal_on) { /* the stock scan (fm1_rf_cal.h) */ + fm1_rfc_scan_rc = fm1_rf_cal_scan(&fm1_rfc); + fm1_rfc_scanned = 1; + } else + fm1_ble_vco_scan(fm1_rf_u32(p + pc + 1)); + pc += 5; + } else if (op == 0x8Eu) { + a = p[pc + 1] | p[pc + 2] << 8; + n = p[pc + 3] | p[pc + 4] << 8; + if (!depth && a + n <= sizeof ble_rf_prog) + fm1_ble_rf_exec(a, a + n, rec, 1); + else + fm1_ble_rf_stat.bad_op = (uint8_t)op; + pc += 5; + } else if (op == 0x8Fu) { + fm1_ble_rf_stat.skipped += p[pc + 1] | p[pc + 2] << 8; /* TODO(hardware): the read-back loop */ + pc += 3; + } else if (op == 0x91u) { /* the LUT words of two commands (packed) */ + pc += fm1_ble_rf_lut2(p + pc); + } else if (op == 0x92u) { /* window writes repeating n entries (packed) */ + pc += fm1_ble_rf_wwg(p + pc); + nt = rmw = 0; + } else if (op == 0x90u) { /* a section marker (§16.1 group) */ + fm1_ble_rf_section(p[pc + 1]); + pc += 2; + if (p[pc - 1] < 32u && (FM1_RF_BURST_GROUPS >> p[pc - 1] & 1u)) + pc = fm1_ble_rf_burst(pc, end, rec); /* (unchanged: run op by op below) */ + } else { /* 0xFF: the end (anything else: stop there) */ + if (op != 0xFFu) + fm1_ble_rf_stat.bad_op = (uint8_t)op; + return; + } + } +} + +/* HW §16.1 groups 2-13 with the stored trims (the data of VM 106, 107, 108, 187, in that order) */ +static void fm1_ble_rf_run(const uint8_t *x106, const uint8_t *x107, const uint8_t *x108, const uint8_t *x187) +{ + const uint8_t *const rec[4] = {x106, x107, x108, x187}; + fm1_ble_rf_exec(0, sizeof ble_rf_prog, rec, 0); + if (fm1_rf_cal_on && fm1_rfc_trimmed) + fm1_rfc_cal_att(0); /* the attenuators as JieLi's trim leaves them (its last + * rx_tx_cal_attenuation(0)); the replay's words are a + * start without a trim (measured against the SDK build) */ + fm1_ble_rf_stat.ran = 1; +} diff --git a/platform/hal/fm1_flash.h b/platform/hal/fm1_flash.h index 18ec13e..2d7df3b 100644 --- a/platform/hal/fm1_flash.h +++ b/platform/hal/fm1_flash.h @@ -154,6 +154,23 @@ static RAMFN uint32_t fl_jedec_ram(void) /* expect 0x856014 */ return id; } +/* the part's factory unique ID (0x4B, four dummy bytes; the stock Puya P25Q80 gives 16 bytes, a Winbond-style part + * 8): dst (RAM) gets 16 bytes; the same on every read of the same part. Only with FL_UID defined: RAM code costs + * every firmware that includes this (from felucca-bsp chip/fm1_flash.h) */ +#ifdef FL_UID +static RAMFN int fl_uid_ram(uint8_t *dst) +{ + fl_saved_t s; uint32_t i; + if (fl_enter(&s)) return -2; + fl_cs(0); + for (i = 0; i < 5u; i++) fl_tx(i ? 0 : 0x4B); + for (i = 0; i < 16u; i++) dst[i] = fl_rx(); + fl_cs(1); + fl_exit(&s); + return 0; +} +#endif + static RAMFN uint32_t fl_status_ram(void) /* SR1 | SR2 << 8 */ { fl_saved_t s; uint32_t v; diff --git a/platform/hal/fm1_rf_cal.h b/platform/hal/fm1_rf_cal.h new file mode 100644 index 0000000..670819d --- /dev/null +++ b/platform/hal/fm1_rf_cal.h @@ -0,0 +1,912 @@ +/* SPDX-License-Identifier: Apache-2.0 + * Copyright (c) 2024-2026 Zhuhai Jieli Technology Co., Ltd. + * Copyright (C) 2026 Charles Vestal */ +/* FM-1 (AC791N / WL82): the 2.4 GHz radio's own calibration, run at every boot before the BLE radio starts, so a + * unit with no stored calibration (no SDK VM, no record 187) still gets a working radio. It follows JieLi's + * calibration in wl_rf_common.a (wf_rf_cal.c, wf_rf_init.c, wf_phy_mac_lib.c) from the AC79 SDK, + * https://gitee.com/Jieli-Tech/fw-AC79_AIoT_SDK (cpu/wl82/liba/), Apache-2.0. + * + * Changed from the original (Apache-2.0 section 4(b)): rewritten in C for felucca-bsp from the library's code, with + * timeouts added on every hardware wait and the Wi-Fi-only steps left out (RX IQ, the 187 save, the prints). + * + * The spec is docs/bt/RF-CALIBRATION.md ("§n" below). Included by fm1_ble.h after fm1_ble_rf.h, whose helpers it uses: + * fm1_bbp (one BBP port transaction), fm1_bbp_win_wr / _rd (the windows), FM1_RF_REG, fm1_delay_us, fm1_ticks. + * + * What the replay (fm1_ble_rf.h) calls, in boot order: + * fm1_rf_cal_scan where its VCO scan op is (§16.1 group 7): the VCO bank scan as wfa_pll_bank_scan(121) + * does it (§3.2). Keeps the bank table for the RF-die patch (§6). + * fm1_rf_cal_trim after group 8's PLL set-up for 2442 MHz, before the first write that carries a 187 field: + * wf_rf_trim without RX IQ (§4), then the 187 record built from what it measured (§9 item 5). + * fm1_rf_cal_reg instead of the captured 187 fields: a register write with the record's fields put in at + * fm1_rf_cal_win their true widths (quick_start_wifi_trim's writes, §4.5); the same for a window write. + * fm1_rf_cal_rfd_w0 the RF-die table: word 0 of entries 128-223 (RX DC, §6) and word 1 of entries 0-127 + * fm1_rf_cal_rfd_w1 (the VCO bank of each entry's frequency code, §6, through fm1_rf_cal_bank). + * fm1_rf_cal_bt_trims the BT modem's TX IQ / DC compensation from the record (§5). + * + * Where the library's code and the spec differ, the code wins (all checked against the IR, 2026-10-26): + * - the BBP port (§3.5): the library's bbp_set polls bit 17 before its two writes, and bbp_rd does not poll at all; + * fm1_bbp polls after each command. The words written and their order are the same, so fm1_bbp is used; it only + * never starts a command while one is running. + * - wf_rx_tune_test (§4.1b): bit 0 of 0x11968 is not cleared with [9:1]; the codes are written into [9:1] with the + * mask 0x3FE. The result is a second wlrf_get_(1) after the done bit, not the word that showed it. + * - the midbank search (§3.2 step 2) sets fbds 73 once, before the first mid. + * - get_wfa_pll_bank (§3.2 step 4) also compares limit[47] (= top) for i = 47. + * - the RF-die word-0 patch (§6) puts in rx_dc_tune[g][1] << 22 unmasked (16 bits shifted: only its low 10 stay). + * + * Library behaviour we take as bugs, and what this file does: + * - get_wfa_pll_midbank: when no mid shows a change, it returns the last comparator result | 15, which is 15 (the + * scan then walks banks 15 down to 225 & 127). Here: top FM1_RF_CAL_TOP_FALLBACK (63), and the scan returns + * FM1_RF_CAL_E_MIDBANK after finishing. + * - txiq_tune_soft steps 5 and 6 (FM1_RF_CAL_FULL only): the best gain offset (-423..423) and phase (-200..200) + * are kept in a signed byte, so one beyond +-127 wraps (and the wrapped gain offset picks the wrong side). Here + * they keep their full value. The TX DC sweeps keep the library's byte: they only visit -128..127. + * - the library's waits (the RC tune engine, the estimator) have no timeout: here each is bounded by TIMER4 and + * counted; a step that times out stops, puts back its neutral values and the trim returns its code. + * + * Interrupts: the SDK runs all of this with interrupts on (§8); so does this file. Nothing else may drive the radio + * meanwhile (the trim transmits into its own receiver). */ +#pragma once +#include + +#ifndef FM1_RF_CAL_FULL +#define FM1_RF_CAL_FULL 0 /* 1: also TX DC, gain and phase (§4.2 steps 4-6, ~2,000 more reads) */ +#endif +#ifndef FM1_RF_CAL_TUNE_US +#define FM1_RF_CAL_TUNE_US 5000u /* the RC tune engine, a run (§4.1b; "well under a millisecond" [L]) */ +#endif +#ifndef FM1_RF_CAL_DEM_US +#define FM1_RF_CAL_DEM_US 5000u /* the estimator of one metric read (§4.6; its length unknown, R2) */ +#endif +#define FM1_RF_CAL_TOP_FALLBACK 63u /* the scan's top when no mid bank shows a change (see the bugs above) */ + +enum { + FM1_RF_CAL_OK = 0, + FM1_RF_CAL_E_MIDBANK = -1, /* the scan found no mid bank; it ran from FM1_RF_CAL_TOP_FALLBACK */ + FM1_RF_CAL_E_FILTER = -2, /* the RC tune engine never finished: the filter registers left as found */ + FM1_RF_CAL_E_TXLO = -3, /* an estimator read timed out in the TX LO search: txlo 64 / 64 */ + FM1_RF_CAL_E_TXIQ = -4, /* the same in TX DC / gain / phase (FM1_RF_CAL_FULL): neutral values */ + FM1_RF_CAL_E_RXDC = -5 /* the same in RX DC: the rest of the steps 0 (0x200) */ +}; + +struct fm1_rf_cal { + /* the scan (§3.2) */ + uint8_t limit[48]; /* wfa_pll_bank_limit: [i] the fbds where bank top - i starts; [47] = top */ + uint8_t top; /* mid | 15 (our unit: 0x3F) */ + uint8_t mid; /* the mid bank found (` 2394 bank: 37`); 0 when none */ + uint8_t mid_found; + uint8_t bank121; /* the bank set with fbds 121 (`setbak:33`) */ + /* the trim (§4) */ + uint8_t flt[3]; /* the RC tune codes for 6, 10, 20 MHz (§4.1b) */ + uint8_t txlo_i, txlo_q; /* the TX LO search's best (§4.2 step 3) */ + uint8_t abort; /* (internal: an estimator timeout stops the running step) */ + uint16_t rx_dc[4][2]; /* per gain step, I then Q: bit 9 = non-negative, [8:0] magnitude (§4.3) */ + int32_t tx[6]; /* what is in window D: I gain, I phase, Q gain, Q phase, I DC, Q DC */ + /* microseconds per step (TIMER4) */ + uint32_t us_scan, us_filter, us_txlo, us_txiq, us_rxdc, us_total; + /* failures */ + uint32_t to_filter, to_dem; /* RC tune engine / estimator timeouts */ + uint32_t bbp_timeouts; /* fm1_bbp's timeouts during the trim */ + uint32_t dem_reads; /* estimator reads made by the trim */ + int32_t err; /* the trim's first error (FM1_RF_CAL_E_*) */ +}; + +/* ---- small register helpers ---- */ + +static void fm1_rfc_rmw(uint32_t a, uint32_t mask, uint32_t v) +{ + FM1_RF_REG(a) = (FM1_RF_REG(a) & ~mask) | (v & mask); +} +static void fm1_rfc_bit(uint32_t a, uint32_t bit, uint32_t on) +{ + fm1_rfc_rmw(a, 1u << bit, (on & 1u) << bit); +} +static uint32_t fm1_rfc_us_since(uint32_t t0) { return (fm1_ticks() - t0) / FM1_TICKS_PER_US; } + +/* the windows by the library's names (§3.5, HW §16.3) */ +#define FM1_RFC_C 0u /* "cca" */ +#define FM1_RFC_D 2u /* "tx_backend" */ +#define FM1_RFC_DP 3u /* "rx_frontend" */ +#define fm1_rfc_c_wr(e, v) fm1_bbp_win_wr(FM1_RFC_C, (e), (v)) +#define fm1_rfc_c_rd(e) fm1_bbp_win_rd(FM1_RFC_C, (e)) +#define fm1_rfc_d_wr(e, v) fm1_bbp_win_wr(FM1_RFC_D, (e), (v)) +#define fm1_rfc_d_rd(e) fm1_bbp_win_rd(FM1_RFC_D, (e)) +#define fm1_rfc_dp_wr(e, v) fm1_bbp_win_wr(FM1_RFC_DP, (e), (v)) +#define fm1_rfc_dp_rd(e) fm1_bbp_win_rd(FM1_RFC_DP, (e)) + +/* the record's fields, little-endian (§4.1) */ +static uint32_t fm1_rfc_u32(const uint8_t *p) { return p[0] | p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; } +static void fm1_rfc_put32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); + p[2] = (uint8_t)(v >> 16); + p[3] = (uint8_t)(v >> 24); +} +static int32_t fm1_rfc_sext10(uint32_t v) /* a 10-bit field as the library reads it back (ashr 22) */ +{ + v &= 0x3FFu; + return (v & 0x200u) ? (int32_t)v - 0x400 : (int32_t)v; +} + +/* ---- the analog side (wf_rf_init.c) ---- */ + +/* wlrf_get_: the analog read port (§3.2): 0x11968 [31:28] = sel, 0x11978 written 1 eight times then 0, read back */ +static uint32_t fm1_rfc_get(uint32_t sel) +{ + uint32_t i; + FM1_RF_REG(0x11968u) = (FM1_RF_REG(0x11968u) & 0x0FFFFFFFu) | sel << 28; + for (i = 0; i < 8u; i++) + FM1_RF_REG(0x11978u) = 1; + FM1_RF_REG(0x11978u) = 0; + return FM1_RF_REG(0x11978u); +} + +/* wf_rf_en_set (§3.6): a group of enables, each set to one of six flags, in the library's order. + * Entry: (register - 0x11900) / 4 << 8 | bit << 3 | flag. Flags: A = receive | RX cal | TX cal | RX DC cal, + * RX = receive, R = receive | RX cal | RX DC cal, T = transmit | RX cal | TX cal, TXC = TX cal, RXC = RX cal. */ +enum { FM1_RFC_F_A, FM1_RFC_F_RX, FM1_RFC_F_R, FM1_RFC_F_T, FM1_RFC_F_TXC, FM1_RFC_F_RXC }; +#define FM1_RFC_EN(off, bit, f) ((off) / 4u << 8 | (bit) << 3 | (f)) +static const uint16_t fm1_rfc_en_tab[29] = { + FM1_RFC_EN(0x00, 23, FM1_RFC_F_A), FM1_RFC_EN(0x04, 15, FM1_RFC_F_RX), FM1_RFC_EN(0x0C, 4, FM1_RFC_F_R), + FM1_RFC_EN(0x0C, 5, FM1_RFC_F_R), FM1_RFC_EN(0x0C, 20, FM1_RFC_F_R), FM1_RFC_EN(0x10, 12, FM1_RFC_F_A), + FM1_RFC_EN(0x10, 27, FM1_RFC_F_A), FM1_RFC_EN(0x14, 11, FM1_RFC_F_A), FM1_RFC_EN(0x14, 18, FM1_RFC_F_A), + FM1_RFC_EN(0x18, 0, FM1_RFC_F_A), FM1_RFC_EN(0x18, 1, FM1_RFC_F_A), FM1_RFC_EN(0x14, 26, FM1_RFC_F_A), + FM1_RFC_EN(0x08, 6, FM1_RFC_F_T), FM1_RFC_EN(0x18, 19, FM1_RFC_F_T), FM1_RFC_EN(0x1C, 0, FM1_RFC_F_T), + FM1_RFC_EN(0x1C, 4, FM1_RFC_F_T), FM1_RFC_EN(0x20, 9, FM1_RFC_F_T), FM1_RFC_EN(0x24, 5, FM1_RFC_F_T), + FM1_RFC_EN(0x24, 7, FM1_RFC_F_T), FM1_RFC_EN(0x24, 8, FM1_RFC_F_T), FM1_RFC_EN(0x24, 27, FM1_RFC_F_T), + FM1_RFC_EN(0x28, 12, FM1_RFC_F_T), FM1_RFC_EN(0x28, 26, FM1_RFC_F_T), FM1_RFC_EN(0x38, 26, FM1_RFC_F_R), + FM1_RFC_EN(0x38, 27, FM1_RFC_F_T), FM1_RFC_EN(0x10, 13, FM1_RFC_F_TXC), FM1_RFC_EN(0x2C, 14, FM1_RFC_F_TXC), + FM1_RFC_EN(0x2C, 11, FM1_RFC_F_RXC), FM1_RFC_EN(0x08, 29, FM1_RFC_F_RXC), +}; +/* mode: 0 receive (and any other value), 1 transmit, 2 TX cal, 3 RX cal, 4 RX DC cal, 5 none (synthesizer only) */ +static void fm1_rfc_en_set(uint32_t mode) +{ + uint32_t rx = mode == 0 || mode > 5, tx = mode == 1, txc = mode == 2, rxc = mode == 3, rxdc = mode == 4, i, e; + uint32_t f[6]; + f[FM1_RFC_F_A] = rxc | rx | txc | rxdc; + f[FM1_RFC_F_RX] = rx; + f[FM1_RFC_F_R] = rxc | rx | rxdc; + f[FM1_RFC_F_T] = rxc | tx | txc; + f[FM1_RFC_F_TXC] = txc; + f[FM1_RFC_F_RXC] = rxc; + for (i = 0; i < sizeof fm1_rfc_en_tab / sizeof fm1_rfc_en_tab[0]; i++) { + e = fm1_rfc_en_tab[i]; + fm1_rfc_bit(0x11900u + 4u * (e >> 8), e >> 3 & 31u, f[e & 7u]); + } +} + +/* rx_flt_vga_gain (wf_rf_init.c): the RX filter / VGA gain steps, 4 bytes each: + * byte 0 -> 0x11910 [24:22], byte 1 -> 0x11910 [26:25], byte 2 -> 0x11914 [17:15] (bits 0-2) and [14:12] + * (bits 4-6), byte 3 -> 0x11914 [7:5] */ +static const uint8_t fm1_rfc_vga[42][4] = { + {1, 0, 0x10, 0}, {1, 0, 0x11, 0}, {1, 0, 0x12, 0}, {1, 0, 0x13, 0}, {1, 0, 0x14, 0}, {1, 0, 0x15, 0}, + {1, 0, 0x20, 1}, {1, 0, 0x21, 1}, {1, 0, 0x22, 1}, {1, 0, 0x23, 1}, {1, 0, 0x24, 1}, {1, 0, 0x25, 1}, + {1, 1, 0x20, 2}, {1, 1, 0x21, 2}, {1, 1, 0x22, 2}, {1, 1, 0x23, 2}, {1, 1, 0x24, 2}, {1, 1, 0x25, 2}, + {2, 1, 0x20, 3}, {2, 1, 0x21, 3}, {2, 1, 0x22, 3}, {2, 1, 0x23, 3}, {2, 1, 0x24, 3}, {2, 1, 0x25, 3}, + {2, 1, 0x40, 4}, {2, 1, 0x41, 4}, {2, 1, 0x42, 4}, {2, 1, 0x43, 4}, {2, 1, 0x44, 4}, {2, 1, 0x45, 4}, + {2, 2, 0x40, 5}, {2, 2, 0x41, 5}, {2, 2, 0x42, 5}, {2, 2, 0x43, 5}, {2, 2, 0x44, 5}, {2, 2, 0x45, 5}, + {4, 2, 0x40, 6}, {4, 2, 0x41, 6}, {4, 2, 0x42, 6}, {4, 2, 0x43, 6}, {4, 2, 0x44, 6}, {4, 2, 0x45, 6}, +}; +/* wfrf_flt_vga_gain: one bit or field at a time, as the library writes them */ +static void fm1_rfc_vga_gain(uint32_t g) +{ + const uint8_t *v = fm1_rfc_vga[g < 42u ? g : 41u]; + fm1_rfc_bit(0x11910u, 22, v[0]); + fm1_rfc_bit(0x11910u, 23, v[0] >> 1); + fm1_rfc_bit(0x11910u, 24, v[0] >> 2); + fm1_rfc_bit(0x11910u, 25, v[1]); + fm1_rfc_bit(0x11910u, 26, v[1] >> 1); + fm1_rfc_rmw(0x11914u, 7u << 15, (uint32_t)v[2] << 15); + fm1_rfc_bit(0x11914u, 12, v[2] >> 4); + fm1_rfc_bit(0x11914u, 13, v[2] >> 5); + fm1_rfc_bit(0x11914u, 14, v[2] >> 6); + fm1_rfc_rmw(0x11914u, 7u << 5, (uint32_t)v[3] << 5); +} + +/* wfrf_hp_open / _close: 0x11914 [2:0] = 1, bits 3 and 4 set / all cleared */ +static void fm1_rfc_hp_open(void) +{ + fm1_rfc_rmw(0x11914u, 7u, 1u); + FM1_RF_REG(0x11914u) |= 1u << 3; + FM1_RF_REG(0x11914u) |= 1u << 4; +} +static void fm1_rfc_hp_close(void) +{ + FM1_RF_REG(0x11914u) &= ~7u; + FM1_RF_REG(0x11914u) &= ~(1u << 3); + FM1_RF_REG(0x11914u) &= ~(1u << 4); +} + +/* rx_tx_cal_attenuation (§3.6): the loop-back attenuators; t = 1 for the TX trim, 0 after it */ +static void fm1_rfc_cal_att(uint32_t t) +{ + FM1_RF_REG(0x11920u) &= ~(1u << 20); + FM1_RF_REG(0x11920u) |= 1u << 21; + if (t == 1u) { + FM1_RF_REG(0x11920u) &= ~(1u << 22); + FM1_RF_REG(0x11920u) |= 1u << 23; + } else { + FM1_RF_REG(0x11920u) |= 1u << 22; + FM1_RF_REG(0x11920u) &= ~(1u << 23); + } + fm1_rfc_rmw(0x11924u, 7u << 28, 5u << 28); + FM1_RF_REG(0x11928u) |= 3u << 13; + fm1_rfc_rmw(0x11928u, 3u << 27, (t == 1u ? 3u : 1u) << 27); + fm1_rfc_rmw(0x11910u, 0xFu << 8, 9u << 8); +} + +/* ---- the PLL and the VCO bank scan (wf_rf_cal.c, §3.2) ---- */ + +static void fm1_rfc_fbds(uint32_t fbds) { fm1_rfc_rmw(0x1193Cu, 0xFFu << 5, fbds << 5); } /* set_pll_fbds */ +static void fm1_rfc_cap(uint32_t cap) { fm1_rfc_rmw(0x11938u, 0x7Fu << 19, (cap & 0x7Fu) << 19); } /* set_pll_cap */ + +/* set_pll_rn_en: restart the loop, then 100 us to settle */ +static void fm1_rfc_rn_en(void) +{ + FM1_RF_REG(0x11938u) &= ~(1u << 16); + FM1_RF_REG(0x11938u) &= ~(1u << 18); + FM1_RF_REG(0x11934u) &= ~(1u << 24); + fm1_delay_us(5); + FM1_RF_REG(0x11938u) |= 1u << 16; + fm1_delay_us(5); + FM1_RF_REG(0x11934u) |= 1u << 24; + FM1_RF_REG(0x11938u) |= 1u << 18; + fm1_delay_us(100); +} + +/* get_pll_vc_res: the control-voltage detector, bit 18 -> 1, bit 17 -> 2 */ +static uint32_t fm1_rfc_vc_res(void) +{ + uint32_t r = fm1_rfc_get(1); + return (r >> 18 & 1u) | (r >> 16 & 2u); +} + +static void fm1_rfc_vc_det(uint32_t on) { fm1_rfc_bit(0x11940u, 24, on); } /* open_ / close_rf_pll_vc_det */ + +/* get_wfa_pll_midbank: at fbds 73, the first mid (7, 23, ..., 119) whose neighbours mid - 7 and mid + 8 read + * otherwise than mid itself -> mid | 15 */ +static uint32_t fm1_rfc_midbank(struct fm1_rf_cal *c) +{ + uint32_t mid, m, l, h; + fm1_rfc_fbds(73); + for (mid = 7; mid < 120u; mid += 16u) { + fm1_rfc_cap(mid); + fm1_rfc_rn_en(); + m = fm1_rfc_vc_res(); + fm1_rfc_cap(mid - 7u); + fm1_rfc_rn_en(); + l = fm1_rfc_vc_res(); + fm1_rfc_cap(mid + 8u); + fm1_rfc_rn_en(); + h = fm1_rfc_vc_res(); + if (h != m || l != m) { + c->mid = (uint8_t)mid; + c->mid_found = 1; + return mid | 15u; + } + } + c->mid = 0; /* (the library: the last result | 15 = 15) */ + c->mid_found = 0; + return FM1_RF_CAL_TOP_FALLBACK; +} + +/* get_wfa_pll_bank: the bank for an fbds code from the scan's table */ +static uint32_t fm1_rf_cal_bank(const struct fm1_rf_cal *c, uint32_t fbds) +{ + uint32_t i, f = fbds & 0xFFu; + for (i = 1; i < 48u; i++) + if (c->limit[i] > f) + return (uint8_t)(c->limit[47] - (i - 1u)); + return (uint8_t)(c->limit[47] - 47u); +} + +/* wfa_pll_bank_scan(121) (§3.2 steps 1-5): for each bank from top down, step fbds up from the last "below" (2) + * until "above" (1) or past 171; the bank's limit is (the previous bank's "above" + this one's last "below" - 3) / 2. + * Then fbds 121 with its bank. The comparator needs no wait (the loop restart has its delays), so + * nothing here can time out. -> 0, or FM1_RF_CAL_E_MIDBANK (the scan still ran, from the fallback top) */ +static int fm1_rf_cal_scan(struct fm1_rf_cal *c) +{ + uint32_t t0 = fm1_ticks(), top, prev_h = 73, lo = 73, cur_lo, h, f, r, i; + fm1_rfc_vc_det(1); + top = fm1_rfc_midbank(c); + c->top = (uint8_t)top; + c->limit[47] = (uint8_t)top; + for (i = 0; i < 47u; i++) { + fm1_rfc_cap((top - i) & 0xFFu); + f = cur_lo = lo; + for (;;) { + fm1_rfc_fbds(f); + fm1_rfc_rn_en(); + r = fm1_rfc_vc_res(); + if (r == 1u) { + h = f; + break; + } + if (r == 2u) + cur_lo = f; + if (f + 1u > 171u) { + h = 171; /* (after a 2 at 171, cur_lo is 171 too) */ + break; + } + f++; + } + c->limit[i] = (uint8_t)((prev_h + cur_lo - 3u) / 2u); + prev_h = h; + lo = cur_lo; + } + fm1_rfc_fbds(121); + c->bank121 = (uint8_t)fm1_rf_cal_bank(c, 121); + fm1_rfc_cap(c->bank121); + fm1_rfc_vc_det(0); + c->us_scan = fm1_rfc_us_since(t0); + return c->mid_found ? FM1_RF_CAL_OK : FM1_RF_CAL_E_MIDBANK; +} + +/* ---- the PHY (wf_phy_mac_lib.c, §3.5) ---- */ + +#define FM1_RFC_MAC_1004 0x31004u /* MAC register 0x1004 (the MAC at 0x30000) */ + +static void fm1_rfc_phy_rst(void) /* wf_phy_rst */ +{ + FM1_RF_REG(FM1_RFC_MAC_1004) = 12; + fm1_bbp(0x16, 0, 0); + fm1_bbp(0x15, 0x31, 0); + fm1_bbp(0x15, 0x30, 0); + fm1_bbp(0x19, 0, 0); +} +static void fm1_rfc_loop_test(void) /* wf_phy_loop_always_test: TX into RX */ +{ + fm1_rfc_phy_rst(); + FM1_RF_REG(FM1_RFC_MAC_1004) = 12; + fm1_bbp(0x19, 0x18, 0); +} +static void fm1_rfc_cca_for_trim(void) /* confg_cca_for_trim */ +{ + fm1_rfc_c_wr(0x40, fm1_rfc_c_rd(0x40) & 0x7Fu); + fm1_rfc_c_wr(0x41, fm1_rfc_c_rd(0x41) & 0x7Fu); + fm1_rfc_c_wr(0x28, 0); + fm1_rfc_c_wr(0x27, 5); + fm1_bbp(0x04, fm1_bbp(0x04, 0, 1) & ~0x18u, 0); +} + +/* dem_filter_dc (§4.6): start the estimator, wait for it, read the result for sel: + * 0, 3: I^2 + Q^2 (16-bit I at D' 0x81:0x82, Q at 0x84:0x85); 1: the 24-bit I mean (0x81-0x83); 2: the Q mean + * (0x8A-0x8C); other: I^2 + Q^2 from 0x87:0x88 and 0x8A:0x8B. A timeout sets c->abort and returns 0. */ +static int32_t fm1_rfc_dem(struct fm1_rf_cal *c, uint32_t sel) +{ + uint32_t t0, a, b, hi, mid; + int32_t i, q; + c->dem_reads++; + fm1_rfc_dp_wr(0x15, 1); + fm1_rfc_dp_wr(0x16, 1); + fm1_rfc_dp_wr(0x15, 3); + fm1_rfc_dp_wr(0x16, 3); + t0 = fm1_ticks(); + while (fm1_rfc_dp_rd(0x8D) & 3u) + if (fm1_ticks() - t0 > FM1_RF_CAL_DEM_US * FM1_TICKS_PER_US) { + c->to_dem++; + c->abort = 1; + return 0; + } + if (sel == 1u || sel == 2u) { + a = sel == 1u ? 0x81u : 0x8Au; + hi = fm1_rfc_dp_rd(a); + mid = fm1_rfc_dp_rd(a + 1u); + b = fm1_rfc_dp_rd(a + 2u); + return (int32_t)(hi << 24 | mid << 16 | b << 8) / 256; + } + a = sel == 0u || sel == 3u ? 0x81u : 0x87u; + b = sel == 0u || sel == 3u ? 0x84u : 0x8Au; + hi = fm1_rfc_dp_rd(a); + i = (int16_t)(hi << 8 | fm1_rfc_dp_rd(a + 1u)); + hi = fm1_rfc_dp_rd(b); + q = (int16_t)(hi << 8 | fm1_rfc_dp_rd(b + 1u)); + return (int32_t)((uint32_t)(i * i) + (uint32_t)(q * q)); /* (as the library: a full-scale pair wraps) */ +} + +/* rd_adc_peak: the ADC peak over 1 ms */ +static uint32_t fm1_rfc_adc_peak(void) +{ + uint32_t p; + fm1_rfc_dp_wr(0x17, 0x82); + fm1_delay_us(1000); + p = fm1_rfc_dp_rd(0x80); + fm1_rfc_dp_wr(0x17, 2); + return p; +} + +/* adc_pp_tune(0): raise the VGA gain step until the peak (the second of two reads) is above 47, at most step 36 */ +static uint32_t fm1_rfc_adc_pp_tune(void) +{ + uint32_t g = 0, p; + fm1_rfc_vga_gain(0); + fm1_rfc_adc_peak(); + p = fm1_rfc_adc_peak(); + while (p <= 47u && g <= 35u) { + g++; + fm1_rfc_vga_gain(g); + fm1_rfc_adc_peak(); + p = fm1_rfc_adc_peak(); + } + fm1_rfc_vga_gain(g); + return g; +} + +/* txlo_cali_set / txlo_calq_set: the TX LO leakage trims, 0x1191C [14:8] and 0x11920 [6:0] */ +static void fm1_rfc_txlo_i(uint32_t v) { fm1_rfc_rmw(0x1191Cu, 0x7Fu << 8, (v & 0x7Fu) << 8); } +static void fm1_rfc_txlo_q(uint32_t v) { fm1_rfc_rmw(0x11920u, 0x7Fu, v & 0x7Fu); } + +/* set_anl_rxdc_i / _q: the analog RX DC trims in 0x11908, I [15:7] with bit 16 = non-negative, Q [25:17] with + * bit 26 -> the encoded value: v | 0x200 when v >= 0, else -v (the library does not mask it) */ +static uint32_t fm1_rfc_anl_rxdc(uint32_t shift, uint32_t sbit, int32_t dc) +{ + int16_t d = (int16_t)dc; + if (d >= 0) { + fm1_rfc_rmw(0x11908u, 0x1FFu << shift, (uint32_t)d << shift); + FM1_RF_REG(0x11908u) |= 1u << sbit; + return (uint16_t)(d | 0x200); + } + fm1_rfc_rmw(0x11908u, 0x1FFu << shift, (uint32_t)(-d) << shift); + FM1_RF_REG(0x11908u) &= ~(1u << sbit); + return (uint16_t)-d; +} +#define fm1_rfc_anl_rxdc_i(dc) fm1_rfc_anl_rxdc(7, 16, (dc)) +#define fm1_rfc_anl_rxdc_q(dc) fm1_rfc_anl_rxdc(17, 26, (dc)) + +/* set_dig_tx_i_gain .. set_dig_tx_q_dc: k = 0 I gain, 1 I phase, 2 Q gain, 3 Q phase, 4 I DC, 5 Q DC. The 10-bit + * value's [9:2] into D 0x04 + k, its [1:0] into a pair of D 0x61 (k 0-3) or 0x62 (k 4-5), read-modify-write. */ +static void fm1_rfc_tx_set(struct fm1_rf_cal *c, uint32_t k, int32_t v) +{ + uint32_t e = k < 4u ? 0x61u : 0x62u, s = 2u * (k & 3u), u = (uint32_t)v, r; + fm1_rfc_d_wr(0x04u + k, u >> 2 & 0xFFu); + r = fm1_rfc_d_rd(e); + fm1_rfc_d_wr(e, (r & ~(3u << s)) | (u & 3u) << s); + c->tx[k] = v; +} +enum { FM1_RFC_TX_IG, FM1_RFC_TX_IP, FM1_RFC_TX_QG, FM1_RFC_TX_QP, FM1_RFC_TX_IDC, FM1_RFC_TX_QDC }; + +/* ---- the trim (§4) ---- */ + +/* wf_rx_tune_test (§4.1b): the RC tuning engine three times (6, 10, 20 MHz), the codes into the filter registers. + * A run that does not finish stops the step before any filter register is written. */ +static int fm1_rfc_rx_tune(struct fm1_rf_cal *c) +{ + static const uint16_t code[3] = {0x1FC, 0x122, 0x0A0}; + uint32_t k, t0, r6, r10, r20; + fm1_rfc_rmw(0x11904u, 0xFu << 8, 8u << 8); + FM1_RF_REG(0x11950u) |= 1u << 27; + for (k = 0; k < 3u; k++) { + fm1_rfc_rmw(0x11968u, 0x3FEu, code[k]); + fm1_rfc_rmw(0x11968u, 0x7Fu << 11, 15u << 11); + FM1_RF_REG(0x11968u) &= ~(0x1Fu << 18); + FM1_RF_REG(0x11968u) &= ~(1u << 23); + FM1_RF_REG(0x11968u) |= 1u; /* start */ + t0 = fm1_ticks(); + while (!(fm1_rfc_get(1) & 0x20u)) + if (fm1_ticks() - t0 > FM1_RF_CAL_TUNE_US * FM1_TICKS_PER_US) { + c->to_filter++; + FM1_RF_REG(0x11968u) &= ~1u; + FM1_RF_REG(0x11950u) &= ~(1u << 27); + return FM1_RF_CAL_E_FILTER; + } + c->flt[k] = (uint8_t)(fm1_rfc_get(1) >> 8); + FM1_RF_REG(0x11968u) &= ~1u; + } + r6 = c->flt[0]; + r10 = c->flt[1]; + r20 = c->flt[2]; + FM1_RF_REG(0x11950u) &= ~(1u << 27); + fm1_rfc_rmw(0x11920u, 0xFFu << 10, r10 << 10); + fm1_rfc_rmw(0x11910u, 0xFFu << 14, r10 << 14); + FM1_RF_REG(0x1195Cu) |= 0xFFu; + fm1_rfc_rmw(0x1195Cu, 0xFFu << 8, r6 << 8); + fm1_rfc_rmw(0x1195Cu, 0xFFu << 16, r10 << 16); + fm1_rfc_rmw(0x1195Cu, 0xFFu << 24, r20 << 24); + FM1_RF_REG(0x11960u) |= 0xFFu; + fm1_rfc_rmw(0x11960u, 0xFFu << 8, r6 << 8); + fm1_rfc_rmw(0x11960u, 0xFFu << 16, r10 << 16); + fm1_rfc_rmw(0x11960u, 0xFFu << 24, r20 << 24); + return FM1_RF_CAL_OK; +} + +/* the TX LO search (§4.2 step 3): best of 0..127 for one trim, starting from 64 at metric(0); only a strictly + * smaller metric wins -> the best, or -1 on an estimator timeout */ +static int32_t fm1_rfc_txlo_search(struct fm1_rf_cal *c, void (*set)(uint32_t)) +{ + int32_t best, m; + uint32_t i, b = 64; + set(64); + best = fm1_rfc_dem(c, 0); + for (i = 0; i < 128u && !c->abort; i++) { + set(i); + m = fm1_rfc_dem(c, 0); + if (m < best) { + best = m; + b = i; + } + } + if (c->abort) + return -1; + set(b); + return (int32_t)b; +} + +#if FM1_RF_CAL_FULL +/* a TX search for FM1_RF_CAL_FULL (§4.2 steps 4-6): sweep x = lo..hi through put(c, x), metric(0), the best (from + * best0 at the current setting) -> the best x, or INT32_MIN on a timeout */ +static int32_t fm1_rfc_tx_search(struct fm1_rf_cal *c, int32_t lo, int32_t hi, int32_t b, + void (*put)(struct fm1_rf_cal *, int32_t)) +{ + int32_t best = fm1_rfc_dem(c, 0), m, x; + for (x = lo; x <= hi && !c->abort; x++) { + put(c, x); + m = fm1_rfc_dem(c, 0); + if (m < best) { + best = m; + b = x; + } + } + return c->abort ? INT32_MIN : b; +} +/* the TX DC sweeps visit (int8)x, as the library's do (x -200..200: -128..127, some twice) */ +static void fm1_rfc_put_idc(struct fm1_rf_cal *c, int32_t x) { fm1_rfc_tx_set(c, FM1_RFC_TX_IDC, (int8_t)x); } +static void fm1_rfc_put_qdc(struct fm1_rf_cal *c, int32_t x) { fm1_rfc_tx_set(c, FM1_RFC_TX_QDC, (int8_t)x); } +static void fm1_rfc_put_gain(struct fm1_rf_cal *c, int32_t x) /* x < 0: I gain 1023 + x, else Q gain 1023 - x */ +{ + fm1_rfc_tx_set(c, FM1_RFC_TX_IG, x < 0 ? 1023 + x : 1023); + fm1_rfc_tx_set(c, FM1_RFC_TX_QG, x < 0 ? 1023 : 1023 - x); +} +static void fm1_rfc_put_iph(struct fm1_rf_cal *c, int32_t x) { fm1_rfc_tx_set(c, FM1_RFC_TX_IP, x); } +static void fm1_rfc_put_qph(struct fm1_rf_cal *c, int32_t x) { fm1_rfc_tx_set(c, FM1_RFC_TX_QP, x); } +#endif + +static void fm1_rfc_tx_neutral(struct fm1_rf_cal *c) /* gains 1023, phases and DCs 0 */ +{ + fm1_rfc_tx_set(c, FM1_RFC_TX_IG, 1023); + fm1_rfc_tx_set(c, FM1_RFC_TX_QG, 1023); + fm1_rfc_tx_set(c, FM1_RFC_TX_IP, 0); + fm1_rfc_tx_set(c, FM1_RFC_TX_QP, 0); + fm1_rfc_tx_set(c, FM1_RFC_TX_IDC, 0); + fm1_rfc_tx_set(c, FM1_RFC_TX_QDC, 0); +} + +/* txiq_tune_soft (§4.2): the loop-back set-up, then the TX LO search (steps 1-3); with FM1_RF_CAL_FULL also TX DC, + * gain balance and phase (steps 4-6) */ +static int fm1_rfc_txiq_tune(struct fm1_rf_cal *c) +{ + uint32_t t0 = fm1_ticks(); + int32_t r; + fm1_rfc_phy_rst(); + fm1_rfc_c_wr(0x15, 0); + fm1_rfc_c_wr(0x14, 0); + fm1_rfc_cca_for_trim(); + fm1_rfc_loop_test(); + fm1_rfc_d_wr(0x00, 3); /* a test tone [M] */ + fm1_rfc_d_wr(0x5F, 16); + fm1_rfc_d_wr(0x01, 20); + fm1_rfc_d_wr(0x02, 0); + fm1_rfc_d_wr(0x03, 0); + fm1_rfc_dp_wr(0x00, 62); + fm1_rfc_dp_wr(0x13, 30); + fm1_rfc_dp_wr(0x14, 56); + fm1_rfc_dp_wr(0x14, 52); + fm1_rfc_tx_neutral(c); + fm1_rfc_txlo_i(64); + fm1_rfc_txlo_q(64); + fm1_rfc_adc_pp_tune(); + c->abort = 0; + r = fm1_rfc_txlo_search(c, fm1_rfc_txlo_i); + if (r >= 0) { + c->txlo_i = (uint8_t)r; + r = fm1_rfc_txlo_search(c, fm1_rfc_txlo_q); + c->txlo_q = (uint8_t)r; + } + c->us_txlo = fm1_rfc_us_since(t0); + if (r < 0) { + fm1_rfc_txlo_i(64); + fm1_rfc_txlo_q(64); + c->txlo_i = c->txlo_q = 64; + return FM1_RF_CAL_E_TXLO; + } +#if FM1_RF_CAL_FULL + t0 = fm1_ticks(); + fm1_rfc_tx_set(c, FM1_RFC_TX_IDC, 0); /* step 4: TX DC */ + fm1_rfc_tx_set(c, FM1_RFC_TX_QDC, 0); + fm1_rfc_adc_pp_tune(); + fm1_rfc_tx_set(c, FM1_RFC_TX_IDC, 0); + r = fm1_rfc_tx_search(c, -200, 200, 0, fm1_rfc_put_idc); + if (r != INT32_MIN) { + fm1_rfc_tx_set(c, FM1_RFC_TX_IDC, (int8_t)r); + fm1_rfc_tx_set(c, FM1_RFC_TX_QDC, 0); + r = fm1_rfc_tx_search(c, -200, 200, 0, fm1_rfc_put_qdc); + } + if (r != INT32_MIN) { + fm1_rfc_tx_set(c, FM1_RFC_TX_QDC, (int8_t)r); + fm1_rfc_dp_wr(0x13, 60); /* step 5: gain balance, on the image [M] */ + fm1_rfc_tx_set(c, FM1_RFC_TX_IG, 1023); + fm1_rfc_tx_set(c, FM1_RFC_TX_QG, 1023); + r = fm1_rfc_tx_search(c, -423, 423, 0, fm1_rfc_put_gain); + } + if (r != INT32_MIN) { + int32_t q = r >= 0; /* the side the gain went to: phase on the same */ + fm1_rfc_put_gain(c, r); /* (the library: r cut to a signed byte) */ + fm1_rfc_tx_set(c, FM1_RFC_TX_IP, 0); /* step 6: phase */ + fm1_rfc_tx_set(c, FM1_RFC_TX_QP, 0); + r = fm1_rfc_tx_search(c, -200, 200, 0, q ? fm1_rfc_put_qph : fm1_rfc_put_iph); + if (r != INT32_MIN) + fm1_rfc_tx_set(c, q ? FM1_RFC_TX_QP : FM1_RFC_TX_IP, r); + } + c->us_txiq = fm1_rfc_us_since(t0); + if (r == INT32_MIN) { + fm1_rfc_tx_neutral(c); + return FM1_RF_CAL_E_TXIQ; + } +#endif + return FM1_RF_CAL_OK; +} + +/* rxdc_tune_soft (§4.3): for each of four front-end gain steps, a signed successive approximation of the analog RX + * DC trims against the I and Q means: twelve rounds, step 256 halving down to 1; the guard is checked before the + * step, so a trim stays within +-510. The last step's trims stay in 0x11908. */ +static int fm1_rfc_rxdc_tune(struct fm1_rf_cal *c) +{ + static const uint8_t gs[4][3] = {{0, 0, 127}, {1, 0, 127}, {1, 3, 69}, {1, 9, 14}}; /* 0x1190C [7:6], + * 0x11910 [11:8], 0x11910 [6:0] */ + uint32_t t0 = fm1_ticks(), g, j; + int32_t bi, bq, s, m; + fm1_rfc_phy_rst(); + fm1_rfc_c_wr(0x15, 0); + fm1_rfc_c_wr(0x14, 0); + fm1_rfc_cca_for_trim(); + fm1_rfc_loop_test(); + fm1_rfc_d_wr(0x00, 3); + fm1_rfc_d_wr(0x5F, 16); + fm1_rfc_dp_wr(0x00, 62); + fm1_rfc_dp_wr(0x1B, 56); + fm1_rfc_dp_wr(0x08, 0xC0); + fm1_rfc_dp_wr(0x13, 0); + fm1_rfc_dp_wr(0x14, 56); + fm1_rfc_dp_wr(0x14, 52); + fm1_rfc_vga_gain(40); + c->abort = 0; + for (g = 0; g < 4u && !c->abort; g++) { + fm1_rfc_rmw(0x1190Cu, 3u << 6, (uint32_t)gs[g][0] << 6); + fm1_rfc_rmw(0x11910u, 0xFu << 8, (uint32_t)gs[g][1] << 8); + fm1_rfc_rmw(0x11910u, 0x7Fu, gs[g][2]); + fm1_rfc_anl_rxdc_i(0); + fm1_rfc_anl_rxdc_q(0); + bi = bq = 0; + s = 256; + for (j = 0; j < 12u && !c->abort; j++) { + m = fm1_rfc_dem(c, 1); + if (c->abort) + break; + if (m > 0 && bi > -510) + bi -= s; + else if (m < 0 && bi < 510) + bi += s; + fm1_rfc_anl_rxdc_i(bi); + m = fm1_rfc_dem(c, 2); + if (m > 0 && bq > -510) + bq -= s; + else if (m < 0 && bq < 510) + bq += s; + fm1_rfc_anl_rxdc_q(bq); + s = s > 1 ? s >> 1 : 1; + } + if (c->abort) + break; + c->rx_dc[g][0] = (uint16_t)fm1_rfc_anl_rxdc_i(bi); + c->rx_dc[g][1] = (uint16_t)fm1_rfc_anl_rxdc_q(bq); + } + c->us_rxdc = fm1_rfc_us_since(t0); + if (c->abort) { + fm1_rfc_anl_rxdc_i(0); + fm1_rfc_anl_rxdc_q(0); + for (; g < 4u; g++) + c->rx_dc[g][0] = c->rx_dc[g][1] = 0x200; + return FM1_RF_CAL_E_RXDC; + } + return FM1_RF_CAL_OK; +} + +/* CRC-16/XMODEM (the library's CRC16 over bytes 0-63, §4.1) */ +static uint32_t fm1_rfc_crc16(const uint8_t *p, uint32_t n) +{ + uint32_t crc = 0, i, b; + for (i = 0; i < n; i++) { + crc ^= (uint32_t)p[i] << 8; + for (b = 0; b < 8u; b++) + crc = crc & 0x8000u ? (crc << 1 ^ 0x1021u) & 0xFFFFu : (crc << 1) & 0xFFFFu; + } + return crc; +} + +/* the 187 record (§4.1) from what the trim left: TX values as written to window D (exact: we wrote them), the TX LO, + * RX DC and filter registers read back as rd_tx_iq_set / rd_rx_iq_set / rd_bw_set do, RX IQ neutral (not measured: + * Wi-Fi only), rx_dc_tune as measured, then the check */ +static void fm1_rfc_record(const struct fm1_rf_cal *c, uint8_t x187[68]) +{ + uint32_t k, r, mag; + for (k = 0; k < 68u; k++) + x187[k] = 0; + for (k = 0; k < 6u; k++) { /* gains unsigned 10 bits, the rest signed */ + r = (uint32_t)c->tx[k] & 0x3FFu; + fm1_rfc_put32(x187 + 4u * k, (k == FM1_RFC_TX_IG || k == FM1_RFC_TX_QG) ? r : (uint32_t)fm1_rfc_sext10(r)); + } + x187[24] = (uint8_t)(FM1_RF_REG(0x1191Cu) >> 8 & 0x7Fu); + x187[25] = (uint8_t)(FM1_RF_REG(0x11920u) & 0x7Fu); + x187[26] = 255; /* dig_rx_i_gain, _q_gain; phases 0 */ + x187[27] = 255; + r = FM1_RF_REG(0x11908u); + mag = r >> 7 & 0x1FFu; + fm1_rfc_put32(x187 + 32, r & 1u << 16 ? mag : 0u - mag); + mag = r >> 17 & 0x1FFu; + fm1_rfc_put32(x187 + 36, r & 1u << 26 ? mag : 0u - mag); + fm1_rfc_put32(x187 + 40, FM1_RF_REG(0x1195Cu)); + fm1_rfc_put32(x187 + 44, FM1_RF_REG(0x11960u)); + for (k = 0; k < 8u; k++) { + x187[48u + 2u * k] = (uint8_t)c->rx_dc[k >> 1][k & 1u]; + x187[49u + 2u * k] = (uint8_t)(c->rx_dc[k >> 1][k & 1u] >> 8); + } + r = fm1_rfc_crc16(x187, 64); /* (0 would read as "no record" to the SDK: 1 in 65536) */ + x187[64] = (uint8_t)r; + x187[65] = (uint8_t)(r >> 8); +} + +/* wf_rf_trim without RX IQ (§4, the SDK's order): the RX filter, TX cal mode and attenuation, TX LO (and with + * FM1_RF_CAL_FULL the TX DC / IQ), RX DC in receive mode with bit 15 of 0x11904 cleared, then RX cal mode and + * attenuation as the library leaves them (wf_rf_init's wf_rf_en_set(0) after the trim is the replay's). Then x187 + * is filled. A step that times out puts back its neutral values and the rest still runs. + * -> 0, or the first step's FM1_RF_CAL_E_* */ +static int fm1_rf_cal_trim(struct fm1_rf_cal *c, uint8_t x187[68]) +{ + uint32_t t0 = fm1_ticks(), t, bbp0 = fm1_ble_rf_stat.bbp_timeouts, g; + int r; + c->err = FM1_RF_CAL_OK; + c->dem_reads = 0; + c->abort = 0; + c->txlo_i = c->txlo_q = 64; + for (g = 0; g < 4u; g++) + c->rx_dc[g][0] = c->rx_dc[g][1] = 0x200; + c->tx[FM1_RFC_TX_IG] = c->tx[FM1_RFC_TX_QG] = 1023; + c->tx[FM1_RFC_TX_IP] = c->tx[FM1_RFC_TX_QP] = c->tx[FM1_RFC_TX_IDC] = c->tx[FM1_RFC_TX_QDC] = 0; + c->us_txiq = 0; + + t = fm1_ticks(); + r = fm1_rfc_rx_tune(c); + c->us_filter = fm1_rfc_us_since(t); + if (r && !c->err) + c->err = r; + fm1_rfc_en_set(2); + fm1_rfc_cal_att(1); + r = fm1_rfc_txiq_tune(c); + if (r && !c->err) + c->err = r; + fm1_rfc_hp_close(); + fm1_rfc_en_set(0); + FM1_RF_REG(0x11904u) &= ~(1u << 15); + r = fm1_rfc_rxdc_tune(c); + if (r && !c->err) + c->err = r; + fm1_rfc_hp_open(); + fm1_rfc_en_set(3); + fm1_rfc_cal_att(0); + + fm1_rfc_record(c, x187); + c->bbp_timeouts = fm1_ble_rf_stat.bbp_timeouts - bbp0; + c->us_total = fm1_rfc_us_since(t0); + return (int)c->err; +} + +/* ---- the apply side: the replay's writes with the record's fields (quick_start_wifi_trim, §4.5) ---- */ + +/* the 0x11908 field pair as set_anl_rxdc_i / _q put a signed value in */ +static uint32_t fm1_rfc_anl_field(uint32_t v, uint32_t shift, uint32_t sbit, int32_t dc) +{ + int16_t d = (int16_t)dc; + v &= ~(0x1FFu << shift); + if (d >= 0) + return v | ((uint32_t)d & 0x1FFu) << shift | 1u << sbit; + return (v | ((uint32_t)(-d) & 0x1FFu) << shift) & ~(1u << sbit); +} + +/* a register write of the replay, with the record's fields at their true widths: 0x1191C [14:8] txlo_cali, + * 0x11920 [6:0] txlo_calq and [17:10] flt_bw_1 byte 2, 0x11910 [21:14] flt_bw_1 byte 2, 0x11908 anl_rxdc_i + * ([15:7], bit 16) and anl_rxdc_q ([25:17], bit 26), 0x1195C / 0x11960 the whole flt_bw_1 / _2. Other addresses: + * v unchanged. (The quick start also sets 0x11904 [11:8] = 8, a constant the replay carries.) */ +static uint32_t fm1_rf_cal_reg(uint32_t addr, uint32_t v, const uint8_t x187[68]) +{ + uint32_t bw2 = x187[42]; + switch (addr) { + case 0x1191Cu: + return (v & ~(0x7Fu << 8)) | (uint32_t)(x187[24] & 0x7Fu) << 8; + case 0x11920u: + return (v & ~(0x7Fu | 0xFFu << 10)) | (x187[25] & 0x7Fu) | bw2 << 10; + case 0x11910u: + return (v & ~(0xFFu << 14)) | bw2 << 14; + case 0x11908u: + v = fm1_rfc_anl_field(v, 7, 16, (int32_t)fm1_rfc_u32(x187 + 32)); + return fm1_rfc_anl_field(v, 17, 26, (int32_t)fm1_rfc_u32(x187 + 36)); + case 0x1195Cu: + return fm1_rfc_u32(x187 + 40); + case 0x11960u: + return fm1_rfc_u32(x187 + 44); + default: + return v; + } +} + +/* a window write of the replay, the same: D (w 2) entries 0x04-0x09 = the six TX values >> 2, 0x61 = their low + * bit pairs (I gain [1:0], I phase [3:2], Q gain [5:4], Q phase [7:6]), 0x62 [1:0] / [3:2] = the DCs' (bits 7-4 + * of v kept); D' (w 3) 0x09 / 0x0B = RX I / Q gain, 0x0A / 0x0C = RX I / Q phase. Others: v unchanged. */ +static uint32_t fm1_rf_cal_win(uint32_t w, uint32_t entry, uint32_t v, const uint8_t x187[68]) +{ + uint32_t k; + if (w == FM1_RFC_D) { + if (entry >= 0x04u && entry <= 0x09u) + return fm1_rfc_u32(x187 + 4u * (entry - 4u)) >> 2 & 0xFFu; + if (entry == 0x61u) { + for (v = 0, k = 0; k < 4u; k++) + v |= (fm1_rfc_u32(x187 + 4u * k) & 3u) << 2u * k; + return v; + } + if (entry == 0x62u) + return (v & ~0xFu) | (fm1_rfc_u32(x187 + 16) & 3u) | (fm1_rfc_u32(x187 + 20) & 3u) << 2; + } else if (w == FM1_RFC_DP) { + if (entry == 0x09u) + return x187[26]; + if (entry == 0x0Bu) + return x187[27]; + if (entry == 0x0Au) + return x187[28]; + if (entry == 0x0Cu) + return x187[29]; + } + return v; +} + +/* the RF-die table (wl_rfd_actl_ram_init, §6): word 0 of entries 128-223 keeps [11:0] and takes rx_dc_tune[g]: + * I in [21:12], Q << 22; g = 0 for 128-132, 1 for 133-179, 2 for 180-185, 3 for 186-223. Others: w0 unchanged. */ +static uint32_t fm1_rf_cal_rfd_w0(uint32_t entry, uint32_t w0, const uint8_t x187[68]) +{ + uint32_t g, i, q; + if (entry < 128u || entry > 223u) + return w0; + g = entry < 133u ? 0u : entry < 180u ? 1u : entry < 186u ? 2u : 3u; + i = x187[48u + 4u * g] | (uint32_t)x187[49u + 4u * g] << 8; + q = x187[50u + 4u * g] | (uint32_t)x187[51u + 4u * g] << 8; + return (w0 & 0xFFFu) | (i & 0x3FFu) << 12 | q << 22; +} + +/* word 1 of entries 0-127: OR in the bank of the entry's fbds code (word 1 [28:21]) << 9. Others: w1 unchanged. */ +static uint32_t fm1_rf_cal_rfd_w1(const struct fm1_rf_cal *c, uint32_t entry, uint32_t w1) +{ + if (entry >= 128u) + return w1; + /* (the SDK's table has [15:9] zero and ORs the bank in; the replay's words carry the emulator's bank there: + * replaced, not ORed) */ + return (w1 & ~(0x7Fu << 9)) | fm1_rf_cal_bank(c, w1 >> 21 & 0xFFu) << 9; +} + +/* ---- the BT TX trims (keep_tx_iq_set and analog.c's update_mdm_txiq_cmp, §5) ---- */ + +/* from a 187 record: CMPUK1 / 2 = I / Q gain >> 3, CMPUK3 = (I phase + Q phase) / 8, OFSI / OFSQ = I / Q DC / 4 + * (divisions toward zero). Read-modify-write of the caller's values (bt_rf_analog_init's base: 0x2FC08 = + * 0x03100000, 0x2FC10 = 0x80008080): 0x2FC10 [7:0] CMPUK1, [15:8] CMPUK2, [23:16] -CMPUK3; 0x2FC08 [9:0] OFSI, + * [19:10] OFSQ. Our unit (` BT_TX_IQ: 127 123 -3`, ` BT_OF: 0 -1`): 0x80037B7F, 0x031FFC00. */ +static void fm1_rf_cal_bt_trims(const uint8_t x187[68], uint32_t *w2fc08, uint32_t *w2fc10) +{ + uint32_t k1 = fm1_rfc_u32(x187 + 0) >> 3 & 0xFFu, k2 = fm1_rfc_u32(x187 + 8) >> 3 & 0xFFu; + int32_t k3 = ((int32_t)fm1_rfc_u32(x187 + 4) + (int32_t)fm1_rfc_u32(x187 + 12)) / 8; + int32_t ofsi = (int32_t)fm1_rfc_u32(x187 + 16) / 4, ofsq = (int32_t)fm1_rfc_u32(x187 + 20) / 4; + uint32_t v = *w2fc10; + v = (v & ~0xFFu) | k1; + v = (v & ~0xFF00u) | k2 << 8; + v = (v & ~0xFF0000u) | ((0u - ((uint32_t)k3 & 0xFFu)) & 0xFFu) << 16; + *w2fc10 = v; + v = *w2fc08; + v = (v & ~0x3FFu) | ((uint32_t)ofsi & 0x3FFu); + v = (v & ~(0x3FFu << 10)) | ((uint32_t)ofsq & 0x3FFu) << 10; + *w2fc08 = v; +} diff --git a/src/main.c b/src/main.c index 482f90e..61b1ba0 100644 --- a/src/main.c +++ b/src/main.c @@ -7,7 +7,7 @@ * USB-MIDI notes in play too (and the TRS jack's) * PLAY starts / stops a 120 BPM MIDI clock, sent over USB-MIDI; its light blinks on the beat * USB audio a computer playing to the FM-1 comes out of it - * Bluetooth ("platform": "mvave") BLE MIDI notes play too, and a phone playing to the FM-1 comes out of it + * Bluetooth (the bluetooth option) BLE MIDI notes play too (and on "mvave", a phone playing to the FM-1 comes out of it) * * What you can call: platform/fm1.h. The rules (no float, keep audio() short): README.md. */ #include "fm1.h" diff --git a/tools/build.py b/tools/build.py index 0cffa47..b35d4dc 100644 --- a/tools/build.py +++ b/tools/build.py @@ -81,7 +81,7 @@ def tc_all(*cmds): # firmware.json "options": the platform's parts you can leave out (all in unless set false), as FOMA_* in fm1.h. -# bluetooth needs the "mvave" platform (and is on there unless set false) +# bluetooth (BLE MIDI) is off unless set true on "felucca" (platform/bt.c, the own stack), on unless set false on "mvave" OPTIONS = {"usb_audio": "FOMA_USB_AUDIO", "trs_midi": "FOMA_TRS_MIDI", "midi_clock": "FOMA_MIDI_CLOCK", "bluetooth": "FOMA_BLUETOOTH"} # firmware.json "platform": what runs under your code on the FM-1 # felucca Felucca's platform (the default): all source, Felucca's flash layout and updater, the USB rescue @@ -116,8 +116,6 @@ def config(): raise BuildError(f"firmware.json: unknown option {', '.join(bad)} (there are: {', '.join(OPTIONS)})") mv = c["platform"] == "mvave" c["user_bytes"] = mvpack.USER_SIZE # M-VAVE's layout (the SDK's flash API takes no other) - if opts.get("bluetooth") and not mv: - raise BuildError('firmware.json: the "bluetooth" option needs "platform": "mvave"') on = {k: bool(opts.get(k, mv if k == "bluetooth" else True)) for k in OPTIONS} c["defines"] = [f"-D{OPTIONS[k]}={int(on[k])}" for k in OPTIONS] + [f"-DFOMA_MVAVE={int(mv)}"] return c From 108bd5d176ef29bd98577a2e0c7b7f05e248684f Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Sat, 31 Oct 2026 06:32:14 -0700 Subject: [PATCH 2/2] Pause audio while the radio starts --- README.md | 4 +++- platform/bt.c | 6 ++++++ platform/fm1.c | 12 ++++++++++++ platform/hal/fm1_audio.h | 2 ++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 43aa453..67a65d4 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,9 @@ has no USB audio input (`audio_in()` gives 0) and no Bluetooth (the calls answer ### Bluetooth MIDI `"options": { "bluetooth": true }` makes the FM-1 a Bluetooth MIDI device that a computer, phone or tablet connects -to. `bt_enable(BT_MIDI)` (from `loop()`) starts it; until then none of it runs. It shows up as your firmware's name +to. `bt_enable(BT_MIDI)` (from `loop()`) starts it; until then none of it runs. The first one pauses the sound +while the radio starts (its start-up has timing a long `audio()` would break), so call it early, from `setup()` or +the first `loop()`. It shows up as your firmware's name and four hex digits (`FOMA FC75`), the same on every boot. MIDI from it comes in through `midi_read` (`MIDI_BLE`), clock and start / stop through the clock helper (`clock_follow(MIDI_BLE)`), and `midi_send` goes out over it too. `bt_status()` says whether it's advertising, connected or ready for MIDI. Notes held when the link drops get their diff --git a/platform/bt.c b/platform/bt.c index f5d4e79..2cbb993 100644 --- a/platform/bt.c +++ b/platform/bt.c @@ -20,6 +20,8 @@ * bt_own.c. The radio's own record (187) is measured at every start (fm1_rf_cal.h) */ static const struct ble_rf_trims BT_TRIMS = {{0x0B, 0x0B}, {1, 7, 4, 7, 11, 1, 7}, {0}, {0}}; +static void bt_audio_hold(int hold); /* fm1.c: the audio stopped (1) or going again (0) */ + #define BQ 64u static struct { uint32_t pkt, t; @@ -157,7 +159,11 @@ static void bt_start(void) { irq_restore(f); ble_init(bt_addr, 1); fm1_rf_cal_on = 1; + fm1_wdt_arm(0x0F); /* (the radio's start-up and calibration take a while) */ + bt_audio_hold(1); /* the audio interrupt paused: a long audio() in the start-up's timed sequences hangs it */ ble_hw_wl82_start(&BT_TRIMS); + bt_audio_hold(0); + fm1_wdt_arm(0x0D); /* (as fm1_cstart arms it) */ bt_up = 1; } diff --git a/platform/fm1.c b/platform/fm1.c index 84e3185..be8cd56 100644 --- a/platform/fm1.c +++ b/platform/fm1.c @@ -367,6 +367,18 @@ void fm1_alnk0_irq(void) { /* via isr_alnk0 (hal/fm1_isr.S) */ in_audio = 0; } extern void isr_alnk0(void); +#if FOMA_BLUETOOTH +static void bt_audio_hold(int hold) { /* bt.c: around the radio's start-up, a short silence */ + if (hold) { + fm1_audio_stop(); + } else { + for (uint32_t i = 0; i < 2u * HALF_WORDS; i++) { + abuf[i] = 0; + } + fm1_audio_resume(); + } +} +#endif /* ---- the main loop's duties: watchdog, USB, the installer's update request, the MASTER knob */ static void platform_poll(void) { diff --git a/platform/hal/fm1_audio.h b/platform/hal/fm1_audio.h index 02e2cc3..95611cf 100644 --- a/platform/hal/fm1_audio.h +++ b/platform/hal/fm1_audio.h @@ -10,6 +10,7 @@ * if (p & FM1_AUDIO_HALF) { fill fm1_audio_free_half(); * fm1_audio_ack_half(); } * fm1_audio_stop() DMA off (crash screen, UBOOT): no looping buzz + * fm1_audio_resume() DMA on again after fm1_audio_stop (the Bluetooth radio's start-up) */ #pragma once #include @@ -87,3 +88,4 @@ FM1_INLINE void fm1_audio_ack_aux(uint8_t p) /* the other three pendings */ FM1_INLINE uint32_t fm1_audio_free_half(void) { return ((FM1_ALNK_CON0 >> 15) & 1u) ^ 1u; } /* 0 / 1 */ FM1_INLINE void fm1_audio_ack_half(void) { FM1_ALNK_CON2 |= 0x08u; } FM1_INLINE void fm1_audio_stop(void) { FM1_ALNK_CON0 &= ~0x800u; } +FM1_INLINE void fm1_audio_resume(void) { FM1_ALNK_CON0 |= 0x800u; } /* after fm1_audio_stop */