Share T096 Full mOTA memory with the offline queue

This commit is contained in:
mikecarper committed 2026-09-08 01:15:19 -07:00
1 parent d28535f503
commit 2ea493994e
26 files changed
+1198 -23

No files matched your search

+15 -9
View File
@@ -188,7 +188,7 @@ bool Mesh::otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool /*fl
// Runtime OTA flood reach (`ota config hops`, persisted in NodePrefs): accept packets up to N hops away and
// relay those still under N hops. 0 = direct only. Overridable per-role by subclassing.
uint8_t Mesh::getOtaHopLimit() const { return ota::ota_ctx().manager.max_hops(); }
uint8_t Mesh::getOtaHopLimit() const { return ota::ota_hop_limit(); }
#endif
void Mesh::begin() {
@@ -263,8 +263,7 @@ void Mesh::begin() {
#ifdef MOTA_HW_ID
my_hw = MOTA_HW_ID; // human-readable hardware tag (per-variant), for the apply hw gate
#endif
ota::ota_ctx().begin(my_tid, Mesh::otaSendAdapter, this, my_hw); // also sets the platform apply codec
ota::ota_ctx().manager.set_seeder_id(self_id.pub_key); // node id (pubkey[0:4]) for advert seeder count
ota::ota_begin_context(my_tid, Mesh::otaSendAdapter, this, my_hw, self_id.pub_key);
#endif
}
@@ -357,6 +356,12 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
}
}
}
#endif
#if defined(OTA_SHARED_COMPANION_QUEUE)
if (!ota::ota_context_if_active()) {
_ota_temp_was_active = false;
return;
}
#endif
const bool ota_active = isTempRadioActive();
if (!ota_active) {
@@ -1093,12 +1098,13 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
const uint8_t ota_priority = otaTrafficPriority(pkt->payload, pkt->payload_len);
bool terminal_ota = false;
#if defined(ENABLE_OTA)
ota::ota_ctx().manager.set_clock(_ms->getMillis()); // discovery jitter/ages
ota::ota_ctx().manager.note_rx_path_hops(n); // adaptive fetch timing
terminal_ota = ota::ota_ctx().manager.on_message(pkt->payload, pkt->payload_len);
// central OTA receive (all roles)
ota::ota_ctx().track_session(ota::ota_ctx().manager.fetchState(), _ms->getMillis());
onOtaRecv(pkt); // optional per-example hook
if (ota::OtaContext* context = ota::ota_context_if_active()) {
context->manager.set_clock(_ms->getMillis());
context->manager.note_rx_path_hops(n);
terminal_ota = context->manager.on_message(pkt->payload, pkt->payload_len);
context->track_session(context->manager.fetchState(), _ms->getMillis());
onOtaRecv(pkt);
}
#endif
// Re-flood discovery at background priority, but keep an active transfer primary at every relay hop.
// The free-pool reserve still sheds periodic discovery under pressure; requested transfer packets are
+22 -2
View File
@@ -4,6 +4,16 @@
#include <FreeRTOS.h>
#include <task.h>
#include <string.h>
#include <helpers/nrf52/BleTaskStartup.h>
namespace mesh {
namespace nrf52 {
static uint8_t ble_task_mask;
void resetBleTaskStartup() { ble_task_mask = 0; }
bool bleTasksStarted() { return ble_task_mask == 3; }
} // namespace nrf52
} // namespace mesh
#ifndef MESH_NRF52_LOOP_STACK_WORDS
#define MESH_NRF52_LOOP_STACK_WORDS 2048
@@ -32,8 +42,18 @@ extern "C" BaseType_t __wrap_xTaskCreate(
&& stack_depth == 1024) {
adjusted_depth = MESH_NRF52_LOOP_STACK_WORDS;
}
return __real_xTaskCreate(task_code, task_name, adjusted_depth, parameters,
priority, created_task);
const BaseType_t result = __real_xTaskCreate(
task_code, task_name, adjusted_depth, parameters, priority, created_task);
if (task_name != NULL) {
const uint8_t mask = strcmp(task_name, "BLE") == 0 ? 1
: strcmp(task_name, "SOC") == 0 ? 2 : 0;
if (result == pdPASS) {
mesh::nrf52::ble_task_mask |= mask;
} else {
mesh::nrf52::ble_task_mask &= ~mask;
}
}
return result;
}
#endif
+78
View File
@@ -0,0 +1,78 @@
#pragma once
#include <new>
#include <stddef.h>
#include <string.h>
namespace mesh {
// One owner at a time: an offline FIFO borrows the workspace's storage while
// idle. Switching owners compacts the ring in place, without allocating RAM or
// dropping unread frames. The caller owns the FIFO's length and head index.
template<class Frame, size_t Capacity, size_t Reserved, class Workspace>
class BorrowableFrameBuffer {
static_assert(Reserved > 0 && Reserved < Capacity, "Invalid shared queue capacities");
struct ExtraFrames { Frame frames[Capacity - Reserved]; };
static_assert(sizeof(Workspace) <= sizeof(ExtraFrames), "mOTA exceeds borrowed queue storage");
Frame _retained[Reserved];
union Extra {
ExtraFrames queue;
Workspace workspace;
Extra() : queue() {}
~Extra() {}
} _extra;
bool _borrowed = false;
void reverse(size_t first, size_t end) {
while (first < end && first < --end) {
unsigned char saved[sizeof(Frame)];
memcpy(saved, &at(first), sizeof(Frame));
memcpy(&at(first), &at(end), sizeof(Frame));
memcpy(&at(end), saved, sizeof(Frame));
++first;
}
}
void compact(int& head) {
if (head == 0) return;
// Rotate the entire ring, including unused slots, using one frame of stack.
reverse(0, head);
reverse(head, capacity());
reverse(0, capacity());
head = 0;
}
public:
BorrowableFrameBuffer() = default;
BorrowableFrameBuffer(const BorrowableFrameBuffer&) = delete;
BorrowableFrameBuffer& operator=(const BorrowableFrameBuffer&) = delete;
~BorrowableFrameBuffer() {
if (_borrowed) _extra.workspace.~Workspace();
}
size_t capacity() const { return _borrowed ? Reserved : Capacity; }
Frame& at(size_t physical_index) {
return physical_index < Reserved ? _retained[physical_index]
: _extra.queue.frames[physical_index - Reserved];
}
Workspace* acquire(int length, int& head) {
if (_borrowed) return &_extra.workspace;
if (length > static_cast<int>(Reserved)) return nullptr;
compact(head);
Workspace* workspace = new (&_extra.workspace) Workspace();
_borrowed = true;
return workspace;
}
void release(int& head) {
if (!_borrowed) return;
compact(head);
_extra.workspace.~Workspace();
new (&_extra.queue) ExtraFrames();
_borrowed = false;
}
};
} // namespace mesh
+3 -1
View File
@@ -856,6 +856,7 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
#if defined(ENABLE_OTA)
// Push the persisted OTA policy + signer allowlist into the running OtaContext (called after load).
void CommonCLI::syncOtaConfigFromPrefs() {
if (!mesh::ota::ota_acquire_context(nullptr, 0)) return;
mesh::ota::OtaContext& c = mesh::ota::ota_ctx();
c.manager.set_autofetch(_prefs->ota_autofetch);
c.manager.set_checkpoint_blocks(_prefs->ota_checkpoint_blocks);
@@ -2638,7 +2639,8 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
strcpy(reply, "LoRa OTA needs temp radio on every node. Run: tempradio 909.950,250,5,5,120");
} else {
mesh::ota::handle_ota_command(command, reply, *_board);
if (mesh::ota::ota_ctx().config_dirty) { // a policy/key changed via the CLI -> persist it
if (mesh::ota::ota_context_if_active()
&& mesh::ota::ota_ctx().config_dirty) { // a policy/key changed via the CLI -> persist it
mesh::ota::OtaContext& c = mesh::ota::ota_ctx();
_prefs->ota_autofetch = c.manager.autofetch();
_prefs->ota_checkpoint_blocks = c.manager.checkpoint_blocks();
+13
View File
@@ -0,0 +1,13 @@
#pragma once
namespace mesh {
namespace nrf52 {
// The pinned Bluefruit core does not check xTaskCreate's return value for its
// BLE and SOC workers. Nrf52LoopStack.cpp observes those calls through the
// existing linker wrapper so a nominally successful begin cannot hide OOM.
void resetBleTaskStartup();
bool bleTasksStarted();
} // namespace nrf52
} // namespace mesh
+25 -4
View File
@@ -1,4 +1,5 @@
#include "SerialBLEInterface.h"
#include "BleTaskStartup.h"
#include "../BluetoothMac.h"
#include "../CompanionFrameQueue.h"
#include <stdio.h>
@@ -401,6 +402,12 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
bool clear_bonds, bool stealth_pair_once,
const mesh::companion::BluetoothPeerIdentity*
bonded_only_peer) {
// Bluefruit cannot safely reinitialize a partly started SoftDevice: doing
// so leaks worker tasks, FIFOs and GATT registrations on every retry. Keep
// USB/UI usable after a failed start; recovery requires a corrected build
// or configuration and a reboot.
if (_begin_attempted) return _begin_ready;
_begin_attempted = true;
instance = this;
_successfulConnectionPending.store(false, std::memory_order_release);
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
@@ -417,9 +424,11 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
// If we want to control BLE LED ourselves, uncomment this:
// Bluefruit.autoConnLed(false);
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
if (!Bluefruit.begin()) {
mesh::nrf52::resetBleTaskStartup();
if (!Bluefruit.begin() || !mesh::nrf52::bleTasksStarted()) {
instance = nullptr;
BLE_DEBUG_PRINTLN("Bluefruit.begin failed");
mesh::usbLoggingPort().println(
"Bluetooth startup failed (SoftDevice/tasks); check runtime heap and reboot");
return false;
}
@@ -501,7 +510,11 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
Bluefruit.setEventCallback(onBLEEvent);
bleuart.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM);
bleuart.begin();
if (bleuart.begin() != ERROR_NONE) {
instance = nullptr;
BLE_DEBUG_PRINTLN("Bluetooth UART service begin failed");
return false;
}
bleuart.setRxCallback(onBleUartRX);
#if COMPANION_FEATURE_BLE_MOTA_SOURCE
@@ -511,6 +524,7 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
_mota_service.setPermission(SECMODE_ENC_WITH_MITM,
SECMODE_ENC_WITH_MITM);
if (_mota_service.begin() != ERROR_NONE) {
instance = nullptr;
BLE_DEBUG_PRINTLN("Bluetooth mOTA service begin failed");
return false;
}
@@ -521,6 +535,7 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
_mota_request.setMaxLen(mesh::ota::BLE_MOTA_REQUEST_MAX);
_mota_request.setUserDescriptor("mOTA device request");
if (_mota_request.begin() != ERROR_NONE) {
instance = nullptr;
BLE_DEBUG_PRINTLN("Bluetooth mOTA request characteristic begin failed");
return false;
}
@@ -532,6 +547,7 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
_mota_response.setUserDescriptor("mOTA host response");
_mota_response.setWriteCallback(onMotaResponse);
if (_mota_response.begin() != ERROR_NONE) {
instance = nullptr;
BLE_DEBUG_PRINTLN("Bluetooth mOTA response characteristic begin failed");
return false;
}
@@ -541,7 +557,11 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
// Register DFU on the main BLE stack so paired clients can discover it
// without switching the device into a separate OTA-only BLE mode first.
bledfu.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM);
bledfu.begin();
if (bledfu.begin() != ERROR_NONE) {
instance = nullptr;
BLE_DEBUG_PRINTLN("Bluetooth DFU service begin failed");
return false;
}
Bluefruit.Advertising.setType(
BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED);
@@ -560,6 +580,7 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
configureBondedOnlyAdvertising(*bonded_only_peer, true);
}
_begin_ready = true;
return true;
}
+2
View File
@@ -28,6 +28,8 @@ class SerialBLEInterface : public BaseSerialInterface {
mesh::ota::BleMotaStream _mota_stream;
#endif
bool _isEnabled;
bool _begin_attempted = false;
bool _begin_ready = false;
bool _isDeviceConnected;
uint16_t _conn_handle;
unsigned long _last_health_check;
+1
View File
@@ -155,6 +155,7 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
const char* a = command + 3;
if (*a != 0 && *a != ' ') return false;
while (*a == ' ') a++;
if (!ota_acquire_context(reply, 160)) return true;
OtaContext& c = ota_ctx();
const char* rest = a;
+104
View File
@@ -1,12 +1,116 @@
#include "OtaContext.h"
#include <assert.h>
namespace mesh {
namespace ota {
#if defined(OTA_SHARED_COMPANION_QUEUE)
namespace {
OtaContext* active_context = nullptr;
void* storage_owner = nullptr;
OtaContext* (*acquire_storage)(void*) = nullptr;
void (*release_storage)(void*) = nullptr;
OtaSend saved_send = nullptr;
void* saved_send_ctx = nullptr;
uint32_t saved_target = 0;
char saved_hw[33] = {0};
uint8_t saved_seeder_id[4] = {0};
// Keep user policy across workspace reuse; discovered catalogs and transfers
// belong to the temporary mOTA session. No allocation is needed while idle.
SignerAllowlist saved_allow;
uint8_t saved_autofetch = OtaManager::AUTOFETCH_OFF;
uint8_t saved_autoinstall = OtaContext::AUTOINSTALL_OFF;
uint8_t saved_hops = OTA_HOP_LIMIT_DEFAULT;
uint16_t saved_checkpoint = OTA_CHECKPOINT_BLOCKS;
uint16_t saved_advert = OTA_ADVERT_INTERVAL_MINS;
}
void ota_set_context_storage(void* owner, OtaContext* (*acquire)(void*),
void (*release)(void*)) {
assert(!active_context);
storage_owner = owner;
acquire_storage = acquire;
release_storage = release;
}
OtaContext& ota_ctx() {
assert(active_context); // Only explicit OTA entry points acquire storage.
return *active_context;
}
OtaContext* ota_context_if_active() { return active_context; }
void ota_begin_context(uint32_t target, OtaSend send, void* ctx,
const char* hw, const uint8_t* seeder_id) {
saved_target = target;
saved_send = send;
saved_send_ctx = ctx;
strncpy(saved_hw, hw ? hw : "", sizeof(saved_hw) - 1);
saved_hw[sizeof(saved_hw) - 1] = 0;
if (seeder_id) memcpy(saved_seeder_id, seeder_id, sizeof(saved_seeder_id));
}
bool ota_acquire_context(char* reply, size_t cap) {
if (active_context) return true;
if (!acquire_storage || !release_storage || !saved_send) {
if (reply && cap) snprintf(reply, cap, "ERR mOTA storage is not ready");
return false;
}
active_context = acquire_storage(storage_owner);
if (!active_context) {
if (reply && cap) snprintf(reply, cap,
"ERR mOTA needs 128 free queue slots; sync unread messages with an app first");
return false;
}
OtaContext& c = *active_context;
c.begin(saved_target, saved_send, saved_send_ctx, saved_hw);
c.manager.set_seeder_id(saved_seeder_id);
c.manager.set_autofetch(saved_autofetch);
c.manager.set_checkpoint_blocks(saved_checkpoint);
c.manager.set_advert_mins(saved_advert);
c.manager.set_max_hops(saved_hops);
c.autoinstall = saved_autoinstall;
c.allow = saved_allow;
return true;
}
uint8_t ota_hop_limit() {
return active_context ? active_context->manager.max_hops() : saved_hops;
}
void ota_release_context_if_idle(bool temporary_radio_active) {
if (!active_context) return;
OtaContext& c = *active_context;
if (c.folder_active || c.folder_dest || c.serving || c.apply_pending) return;
if (temporary_radio_active && !c.release_when_idle) return;
// No host source/destination remains. Discard pending transfer work before
// the queue reuses these bytes, including dynamic discovery/diff buffers.
saved_autofetch = c.manager.autofetch();
saved_checkpoint = c.manager.checkpoint_blocks();
saved_advert = c.manager.advert_mins();
saved_hops = c.manager.max_hops();
saved_autoinstall = c.autoinstall;
saved_allow = c.allow;
c.manager.clearPendingEgress();
c.manager.reset_session();
active_context = nullptr;
release_storage(storage_owner);
}
#else
OtaContext& ota_ctx() {
static OtaContext ctx;
return ctx;
}
OtaContext* ota_context_if_active() { return &ota_ctx(); }
bool ota_acquire_context(char*, size_t) { return true; }
void ota_begin_context(uint32_t target, OtaSend send, void* ctx,
const char* hw, const uint8_t* seeder_id) {
ota_ctx().begin(target, send, ctx, hw);
ota_ctx().manager.set_seeder_id(seeder_id);
}
uint8_t ota_hop_limit() { return ota_ctx().manager.max_hops(); }
#endif
} // namespace ota
} // namespace mesh
+27
View File
@@ -82,6 +82,10 @@ class FolderMotaStore; // pull destination over the seeder link (full type onl
#endif
struct OtaContext {
#if defined(OTA_SHARED_COMPANION_QUEUE)
// Release at a main-loop boundary, after callers finish using this context.
bool release_when_idle = false;
#endif
OtaManager manager;
#if defined(OTA_SEEDER_ONLY)
// A seeder-only node never stages an image for itself. Keep a valid default
@@ -405,6 +409,9 @@ struct OtaContext {
return false;
}
folder_active = true;
#if defined(OTA_SHARED_COMPANION_QUEUE)
release_when_idle = false;
#endif
_folder_link = link;
_folder_source = source;
uint16_t offered = 0, advertised = 0;
@@ -432,6 +439,9 @@ struct OtaContext {
folder_active = false;
_folder_link = FOLDER_LINK_NONE;
_folder_source = nullptr;
#if defined(OTA_SHARED_COMPANION_QUEUE)
release_when_idle = true;
#endif
}
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
@@ -618,5 +628,22 @@ private:
OtaContext& ota_ctx(); // process-wide singleton
// On constrained source-only Companions, the context exists only while its
// queue-backed workspace is owned by mOTA. Other builds keep the singleton.
OtaContext* ota_context_if_active();
bool ota_acquire_context(char* reply, size_t cap);
void ota_begin_context(uint32_t target, OtaSend send, void* ctx,
const char* hw, const uint8_t* seeder_id);
uint8_t ota_hop_limit();
#if defined(OTA_SHARED_COMPANION_QUEUE)
#if !defined(NRF52_PLATFORM) || !defined(OTA_SEEDER_ONLY) || !defined(COMPANION_RADIO_FULL)
#error "Shared mOTA queue storage requires an nRF52 Full source-only Companion"
#endif
void ota_set_context_storage(void* owner, OtaContext* (*acquire)(void*),
void (*release)(void*));
void ota_release_context_if_idle(bool temporary_radio_active);
#endif
} // namespace ota
} // namespace mesh