From b7f138f2dafe8f8c58f395500e519a72e7de3ad2 Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Wed, 16 Sep 2026 23:12:21 +0200 Subject: [PATCH 1/8] Let uploads of any size finish (EPIC-13 STORY-01, STORY-02) Three bugs kept a PUT larger than a couple of hundred kilobytes from ever completing. The idle sweeper closed live transfers. srv_poll_cb closed every connection but the debug stream on its first poll tick, and lwIP restarts a pcb's poll timer only when the peer acknowledges data the server sent -- during an upload the server sends nothing, so the timer ran however fast the data arrived. Connections now carry a last-activity stamp, set on accept and in the receive and sent callbacks, and are closed only after 20 s with no traffic either way. The HTTP_POLL_INTERVAL comment claimed 16 s per tick; it is 4 s. Every upload silently lost the body bytes that shared the first TCP segment with the headers. The header branch copied the segment into c->hdr clamped to 1024 bytes but called tcp_recved() for the whole pbuf, so with curl's 1460-byte first segment exactly 437 bytes were dropped while TCP told the client they had arrived -- the client had nothing to retransmit and the upload could never reach Content-Length. The body bytes now stay in the pbuf: the header branch hands (pbuf, offset) to parse_and_dispatch, which passes them to upload_drain_pbuf(), adv_load_drain_pbuf() or straight into c->body. This also fixes the Runner advanced-load body and any JSON body behind headers approaching 1 KB. A 4 MB upload then hit the watchdog: extending a multi-megabyte file makes FatFs walk the cluster chain and a single f_write outlasts the 8 s watchdog. upload_drain_pbuf() feeds it either side of each write and names the phase, as the GEMDRIVE write path does. On the error path, conn_close is split into conn_release_resources (FatFs handles, the partial-upload unlink, the body-stream lock) and the pcb teardown, and srv_err_cb calls the release. It used to drop the slot only, leaving the body lock set so every later transfer answered 503 busy until a reset. Verified on hardware, debug and release: 64 KB, 256 KB and 4 MB uploads return 200/201 and cmp identical after a round trip, a 4 MB download takes 15 s, 10 aborted uploads leave no partial file and the next upload returns 201, and smoke.py passes 8/8 on debug and 7/7 on release. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/http_server.c | 213 +++++++++++++++++++++++++++---------------- tools/dev/smoke.py | 3 +- 2 files changed, 136 insertions(+), 80 deletions(-) diff --git a/rp/src/http_server.c b/rp/src/http_server.c index d4d20ce..e08e882 100644 --- a/rp/src/http_server.c +++ b/rp/src/http_server.c @@ -69,11 +69,21 @@ extern unsigned char __rom_in_ram_start__[]; // Hard cap on a single upload (PUT) body. Per the locked spec. #define HTTP_MAX_UPLOAD_BYTES (4u * 1024u * 1024u) -// Idle-connection sweeper: tcp_poll fires every (4 × tcp_poll_interval) / -// 2 seconds. With interval 8, that's 16 seconds per tick; we close on -// the first tick, so a connection that never sends a complete request -// is closed in ~16 s. +// Idle-connection sweeper. tcp_poll fires every HTTP_POLL_INTERVAL slow +// ticks, and a slow tick is 500 ms, so interval 8 is one call every 4 s -- +// not the 16 s an earlier comment here claimed. +// +// A poll is not evidence of an idle connection. lwIP restarts a pcb's poll +// timer only when the peer acknowledges data the server sent +// (core/tcp_in.c), and during an upload or a Runner advanced-load body the +// server sends nothing, so the timer keeps running however fast the data +// arrives. Closing on the first tick therefore killed every transfer that +// lasted more than about 4 s: a 4 MB upload, a slow client, or a fast one +// whose burst outran a reply. The sweeper now closes a connection only +// after HTTP_IDLE_TIMEOUT_MS with no traffic in either direction, which is +// what "idle" was meant to mean. #define HTTP_POLL_INTERVAL 8 +#define HTTP_IDLE_TIMEOUT_MS 20000u typedef enum { HC_FREE = 0, @@ -143,6 +153,7 @@ typedef struct http_conn { uint32_t stream_end; // one-past-last byte to send (file size or // Range slice end) bool holds_body_lock; // this conn holds the body-stream lock + uint32_t last_activity_ms; // last traffic either way; the sweeper's clock // Streaming file upload state. Active while state == HC_STREAM_UPLOAD; // FIL handle released by conn_close (and the partial file unlinked @@ -194,7 +205,8 @@ static http_conn_t *conn_alloc(void); static void conn_free(http_conn_t *c); static void conn_close(http_conn_t *c); -static void parse_and_dispatch(http_conn_t *c); +static void parse_and_dispatch(http_conn_t *c, struct pbuf *seg, + size_t body_off); static void route(http_conn_t *c); static void __not_in_flash_func(send_buffered)(http_conn_t *c); @@ -226,12 +238,14 @@ static void stream_debug_drive(http_conn_t *c); static err_t __not_in_flash_func(stream_send_chunk)(http_conn_t *c, const char *body, size_t body_len); static err_t stream_send_terminator(http_conn_t *c); -static bool handle_file_upload_init(http_conn_t *c, const char *body_start, - size_t leftover); +static bool upload_drain_pbuf(http_conn_t *c, struct pbuf *seg, size_t off, + size_t n, FRESULT *fr_out); +static bool handle_file_upload_init(http_conn_t *c, struct pbuf *seg, + size_t body_off, size_t leftover); static void upload_finish_ok(http_conn_t *c); -static bool handle_runner_adv_load_init(http_conn_t *c, const char *body_start, - size_t leftover); -static void adv_load_drain_pbuf(http_conn_t *c, struct pbuf *p, size_t off, +static bool handle_runner_adv_load_init(http_conn_t *c, struct pbuf *seg, + size_t body_off, size_t leftover); +static bool adv_load_drain_pbuf(http_conn_t *c, struct pbuf *p, size_t off, size_t n); static bool adv_load_dispatch_chunk(http_conn_t *c); static void adv_load_finish_ok(http_conn_t *c); @@ -302,7 +316,48 @@ static void conn_free(http_conn_t *c) { c->state = HC_FREE; } -static void conn_close(http_conn_t *c) { +// Copy n body bytes out of seg (starting at off) into the upload file, +// in chunks of the response buffer. Returns false and the FatFs error on +// a short or failed write. +static bool upload_drain_pbuf(http_conn_t *c, struct pbuf *seg, size_t off, + size_t n, FRESULT *fr_out) { + size_t done = 0; + while (done < n) { + size_t chunk = n - done; + if (chunk > sizeof(c->resp)) chunk = sizeof(c->resp); + pbuf_copy_partial(seg, c->resp, (u16_t)chunk, (u16_t)(off + done)); + UINT written = 0; + // Extending a multi-megabyte file makes FatFs walk the cluster chain, so + // a single write can outlast the watchdog. Feed it either side, the way + // the GEMDRIVE write path does, and name the phase so a real hang here + // is still reported as one (CLAUDE.md). + health_setPhase(HEALTH_PHASE_HTTP_REQUEST); + health_feed(); + FRESULT fr = f_write(&c->upload_file, c->resp, (UINT)chunk, &written); + health_feed(); + if (fr != FR_OK || written != chunk) { + DPRINTF("http_server: upload f_write failed (%d, %u/%zu)\n", (int)fr, + (unsigned)written, chunk); + *fr_out = fr; + return false; + } + done += chunk; + } + return true; +} + +// Traffic in either direction keeps a connection alive for the sweeper. +static void conn_touch(http_conn_t *c) { + c->last_activity_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); +} + +// Everything this connection holds that is not the pcb. Split out of +// conn_close so the error path can release it too: lwIP frees the pcb itself +// and calls srv_err_cb, which used to drop the slot and leak the rest -- the +// body-stream lock (every later transfer answering 503 busy until a reset), +// FatFs handles counted against FF_FS_LOCK and shared with GEMDRIVE, and a +// half-written upload left on the card. +static void conn_release_resources(http_conn_t *c) { if (c->stream_dir_open) { f_closedir(&c->stream_dir); c->stream_dir_open = false; @@ -327,6 +382,10 @@ static void conn_close(http_conn_t *c) { g_body_stream_busy = false; c->holds_body_lock = false; } +} + +static void conn_close(http_conn_t *c) { + conn_release_resources(c); if (c->pcb != NULL) { struct tcp_pcb *pcb = c->pcb; tcp_arg(pcb, NULL); @@ -356,6 +415,7 @@ static err_t srv_accept_cb(void *arg, struct tcp_pcb *newpcb, err_t err) { return ERR_ABRT; } c->pcb = newpcb; + conn_touch(c); tcp_arg(newpcb, c); tcp_recv(newpcb, srv_recv_cb); tcp_sent(newpcb, srv_sent_cb); @@ -381,8 +441,15 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st conn_close(c); return ERR_OK; } + conn_touch(c); if (c->state == HC_READ_HEADERS) { + // Only the headers go into c->hdr. Body bytes that shared this + // segment with them stay in the pbuf and are handed to the + // dispatcher by offset: copying them into c->hdr would drop + // everything past HTTP_HEADER_BUF_BYTES while tcp_recved below + // still tells the peer they arrived. + size_t hdr_before = c->hdr_len; size_t to_copy = p->tot_len; size_t remaining = (c->hdr_len < HTTP_HEADER_BUF_BYTES - 1) @@ -397,13 +464,18 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st c->hdr[c->hdr_len] = '\0'; } tcp_recved(pcb, p->tot_len); - pbuf_free(p); - if (strstr(c->hdr, "\r\n\r\n") != NULL) { - parse_and_dispatch(c); + char *eoh = strstr(c->hdr, "\r\n\r\n"); + if (eoh != NULL) { + // The terminator completed in this segment, so the first body + // byte is that many bytes into it. + size_t header_bytes = (size_t)(eoh + 4 - c->hdr); + size_t body_off = header_bytes - hdr_before; + parse_and_dispatch(c, p, body_off); } else if (c->hdr_len >= HTTP_HEADER_BUF_BYTES - 1) { write_error(c, 400, "Bad Request", "bad_request", "Headers too large"); } + pbuf_free(p); } else if (c->state == HC_READ_BODY) { size_t need = c->content_length - c->body_received; size_t take = (p->tot_len < need) ? p->tot_len : need; @@ -422,25 +494,14 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st // success response and close. size_t want = c->content_length - c->upload_received; size_t take = (p->tot_len < want) ? p->tot_len : want; - size_t off = 0; - while (off < take) { - size_t chunk = take - off; - if (chunk > sizeof(c->resp)) chunk = sizeof(c->resp); - pbuf_copy_partial(p, c->resp, (u16_t)chunk, (u16_t)off); - UINT written = 0; - FRESULT fr = - f_write(&c->upload_file, c->resp, (UINT)chunk, &written); - if (fr != FR_OK || written != chunk) { - DPRINTF("http_server: upload f_write failed (%d, %u/%zu)\n", - (int)fr, (unsigned)written, chunk); - // Surface 500 to the client; conn_close closes the FIL and - // unlinks the partial file when the response has been drained. - write_fs_error(c, fr, "f_write failed mid-upload"); - tcp_recved(pcb, p->tot_len); - pbuf_free(p); - return ERR_OK; - } - off += chunk; + FRESULT fr = FR_OK; + if (!upload_drain_pbuf(c, p, 0, take, &fr)) { + // Surface 500 to the client; conn_close closes the FIL and + // unlinks the partial file when the response has been drained. + write_fs_error(c, fr, "f_write failed mid-upload"); + tcp_recved(pcb, p->tot_len); + pbuf_free(p); + return ERR_OK; } c->upload_received += take; tcp_recved(pcb, p->tot_len); @@ -456,7 +517,7 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st size_t want = (size_t)(c->adv_load_total - c->adv_load_received); size_t take = (p->tot_len < want) ? p->tot_len : want; if (take > 0) { - adv_load_drain_pbuf(c, p, 0, take); + (void)adv_load_drain_pbuf(c, p, 0, take); } tcp_recved(pcb, p->tot_len); pbuf_free(p); @@ -478,6 +539,7 @@ static err_t __not_in_flash_func(srv_sent_cb)(void *arg, struct tcp_pcb *pcb, u1 if (c == NULL) { return ERR_OK; } + conn_touch(c); c->resp_sent += len; if (c->state == HC_WRITE_RESPONSE && c->resp_sent >= c->resp_len) { c->state = HC_DRAINING; @@ -510,17 +572,29 @@ static err_t srv_poll_cb(void *arg, struct tcp_pcb *pcb) { stream_debug_drive(c); return ERR_OK; } - DPRINTF("http_server: idle timeout, closing connection\n"); + uint32_t idle_ms = + (uint32_t)to_ms_since_boot(get_absolute_time()) - c->last_activity_ms; + if (idle_ms < HTTP_IDLE_TIMEOUT_MS) { + return ERR_OK; + } + DPRINTF( + "http_server: idle for %lu ms, closing connection (state %d, " + "upload %lu/%lu)\n", + (unsigned long)idle_ms, (int)c->state, (unsigned long)c->upload_received, + (unsigned long)c->content_length); conn_close(c); return ERR_OK; } static void srv_err_cb(void *arg, err_t err) { - (void)err; http_conn_t *c = (http_conn_t *)arg; if (c != NULL) { - // pcb is already gone per lwIP contract; just release the slot. + // The pcb is already gone per lwIP's contract, but everything else this + // connection holds is ours to release. + DPRINTF("http_server: connection killed by lwIP (err %d), releasing\n", + (int)err); c->pcb = NULL; + conn_release_resources(c); conn_free(c); } } @@ -556,7 +630,8 @@ static hc_method_t parse_method(const char *s, size_t n) { return HM_UNKNOWN; } -static void parse_and_dispatch(http_conn_t *c) { +static void parse_and_dispatch(http_conn_t *c, struct pbuf *seg, + size_t body_off) { // Request line char *eol = strstr(c->hdr, "\r\n"); if (eol == NULL) { @@ -689,15 +764,12 @@ static void parse_and_dispatch(http_conn_t *c) { c->is_head = (c->method == HM_HEAD); - // Compute the body-segment bytes that fell after the headers in the - // same TCP segment. Used both by the upload streaming path (which - // writes them straight to the file) and by the generic JSON-body - // path (which buffers them into c->body). - char *body_start = p + 2; - size_t header_consumed_total = (size_t)(body_start - c->hdr); - size_t body_leftover = (c->hdr_len > header_consumed_total) - ? c->hdr_len - header_consumed_total - : 0; + // Body bytes that fell after the headers in the same TCP segment are + // still in the pbuf at body_off. Used both by the streaming paths + // (which drain them straight to their destination) and by the + // generic JSON-body path (which buffers them into c->body). + size_t body_leftover = + (seg != NULL && seg->tot_len > body_off) ? seg->tot_len - body_off : 0; // Special-case PUT-on-/api/v1/gemdrive/files/ for streaming upload — it // bypasses the small JSON-body buffer (which has a 256-byte cap) @@ -708,7 +780,7 @@ static void parse_and_dispatch(http_conn_t *c) { strncmp(c->path, files_prefix, files_prefix_len) == 0) { size_t leftover = body_leftover; if (leftover > c->content_length) leftover = c->content_length; - if (!handle_file_upload_init(c, body_start, leftover)) { + if (!handle_file_upload_init(c, seg, body_off, leftover)) { return; // upload_init already wrote the error response } if (c->upload_received >= c->content_length) { @@ -728,7 +800,7 @@ static void parse_and_dispatch(http_conn_t *c) { strcmp(c->path, "/api/v1/runner/adv/load") == 0) { size_t leftover = body_leftover; if (leftover > c->content_length) leftover = c->content_length; - if (!handle_runner_adv_load_init(c, body_start, leftover)) { + if (!handle_runner_adv_load_init(c, seg, body_off, leftover)) { return; // init wrote the error response } if (c->adv_load_received >= c->adv_load_total) { @@ -751,14 +823,10 @@ static void parse_and_dispatch(http_conn_t *c) { "Body too large for this route"); return; } - // body_start / body_leftover were computed above. The header - // parser nul-terminated each header it walked but c->hdr_len is - // the original byte count copied off the wire, so anything past - // body_start is body that arrived in the same segment. size_t leftover = body_leftover; if (leftover > c->content_length) leftover = c->content_length; if (leftover > 0) { - memcpy(c->body, body_start, leftover); + pbuf_copy_partial(seg, c->body, (u16_t)leftover, (u16_t)body_off); c->body_received = leftover; } if (c->body_received >= c->content_length) { @@ -2227,9 +2295,8 @@ static uint8_t *adv_load_buf_base(void) { // dispatch the chunk and reset the cursor for the next one. The // final partial chunk (chunk_pos > 0 at end-of-content) is flushed // by adv_load_finish_ok(). -static void adv_load_drain_pbuf(http_conn_t *c, - struct pbuf *p, - size_t off, size_t n) { +static bool adv_load_drain_pbuf(http_conn_t *c, struct pbuf *p, size_t off, + size_t n) { uint8_t *base = adv_load_buf_base(); // Walk pbuf segments to avoid an O(n) intermediate copy through // pbuf_copy_partial. Same shape as pbuf_get_at, but we can't use @@ -2252,10 +2319,11 @@ static void adv_load_drain_pbuf(http_conn_t *c, // will keep draining bytes into nowhere; the response is // already a 504 so the client sees the failure. if (!adv_load_dispatch_chunk(c)) { - return; + return false; } } } + return true; } // Publish (target, len) in shared-var slots 18/19, fire @@ -2318,8 +2386,8 @@ static void adv_load_finish_ok(http_conn_t *c) { // body bytes that arrived in the same TCP segment as the headers. // Returns false if any validation failed (an error response was // already written). -static bool handle_runner_adv_load_init( - http_conn_t *c, const char *body_start, size_t leftover) { +static bool handle_runner_adv_load_init(http_conn_t *c, struct pbuf *seg, + size_t body_off, size_t leftover) { if (!emul_isRunnerActive()) { write_error(c, 409, "Conflict", "runner_inactive", "Runner mode is not active; boot via [U] first"); @@ -2437,20 +2505,11 @@ static bool handle_runner_adv_load_init( c->adv_load_chunk_pos = 0; // Pump the leftover bytes that arrived in the same TCP segment as - // the headers directly into the chunk buffer. pbuf-free isn't - // available here (no pbuf to walk); instead loop byte-by-byte. + // the headers directly into the chunk buffer. size_t pump = leftover; if (pump > c->adv_load_total) pump = c->adv_load_total; - uint8_t *base = adv_load_buf_base(); - for (size_t i = 0; i < pump; i++) { - base[c->adv_load_chunk_pos ^ 1u] = (uint8_t)body_start[i]; - c->adv_load_chunk_pos++; - c->adv_load_received++; - if (c->adv_load_chunk_pos >= ADV_LOAD_CHUNK_SIZE) { - if (!adv_load_dispatch_chunk(c)) { - return false; - } - } + if (pump > 0 && !adv_load_drain_pbuf(c, seg, body_off, pump)) { + return false; // dispatch timed out; the 504 is already written } return true; } @@ -3825,8 +3884,8 @@ static void upload_finish_ok(http_conn_t *c) { // upload was already complete after the leftover write, calls // upload_finish_ok); false means upload_init wrote the error response // itself and the caller should just return. -static bool handle_file_upload_init( - http_conn_t *c, const char *body_start, size_t leftover) { +static bool handle_file_upload_init(http_conn_t *c, struct pbuf *seg, + size_t body_off, size_t leftover) { // Single-streamer lock. if (g_body_stream_busy) { char body[160]; @@ -3955,11 +4014,7 @@ static bool handle_file_upload_init( // Write any leftover bytes that arrived in the same TCP segment as // the headers. if (leftover > 0) { - UINT written = 0; - fr = f_write(&c->upload_file, body_start, (UINT)leftover, &written); - if (fr != FR_OK || written != leftover) { - DPRINTF("http_server: upload leftover f_write failed (%d, %u/%zu)\n", - (int)fr, (unsigned)written, leftover); + if (!upload_drain_pbuf(c, seg, body_off, leftover, &fr)) { // Close + unlink happens in conn_close. Surface the error to // the client first. write_fs_error(c, fr, "f_write failed"); diff --git a/tools/dev/smoke.py b/tools/dev/smoke.py index dc2ef44..b311885 100755 --- a/tools/dev/smoke.py +++ b/tools/dev/smoke.py @@ -23,7 +23,8 @@ release build they fall back to prompts. Limits that follow known bugs, raise them when those epics land: - uploads stay at 256 KB (EPIC-13 STORY-02: the idle sweeper closes longer uploads) + uploads stay at 256 KB (for run time, not a bug: EPIC-13 STORY-02 fixed + uploads up to the 4 MB cap) no folder creation (EPIC-11 STORY-03: mkdir panics on big-cluster cards) downloads stay at 256 KB (uploads are how the test file gets onto the card) """ From a458ac2f6a9d848bd136a6e224e31da5bc008058 Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Wed, 16 Sep 2026 23:26:06 +0200 Subject: [PATCH 2/8] Size the lwIP pools from measurements (EPIC-13 STORY-04) With DEVOPS_LWIP_STATS on a debug build, ran a 4 MB upload, a 4 MB download, a listing, a 40-request burst, two concurrent clients and 20 aborted transfers. No pool reported a single allocation failure, and only one was under real pressure. tcp_pcb measured 4 of 4 and stayed there between requests: the server closes every connection itself, so each request leaves a pcb in TIME_WAIT for 2 x TCP_MSL, and lwIP's default MSL of 60 s means 2 minutes per request. Nothing failed only because tcp_alloc evicts the oldest TIME_WAIT pcb when the pool is empty. TCP_MSL drops to 10 s, as in Booster, and the pool grows to 6 -- the 2 HTTP connections plus the debug stream plus headroom. Re-measured: 25 s after the same burst the pool is back to 1 of 6, where before it sat full indefinitely. tcp_seg peaked at 9 of 16 and pbuf_pool at 2 of 12, so both keep their size; each now carries the measurement that justifies it. pbuf_pool is the receive path -- the cyw43 driver allocates from it and in poll mode frees each pbuf before taking the next -- and a pool that runs dry there drops packets off the air, so its headroom stays. The two extra pcbs cost 312 bytes of .bss, which comes off the heap ceiling: total 46,224, minimum free 24,472, stack high water 2,544 of 16,384. Inside EPIC-12's budget. smoke.py passes 7/7 on release. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/lwipopts.h | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/rp/src/lwipopts.h b/rp/src/lwipopts.h index adc79e1..f26d1fe 100644 --- a/rp/src/lwipopts.h +++ b/rp/src/lwipopts.h @@ -36,9 +36,25 @@ #define MEM_OVERFLOW_CHECK 0 #define MEMP_NUM_PBUF 8 -#define MEMP_NUM_TCP_PCB 4 +// Measured on hardware with DEVOPS_LWIP_STATS (EPIC-13 STORY-04, 2026-09-16, +// build b7f138f): a 4 MB upload, a 4 MB download, a listing, a 40-request +// burst, two concurrent clients and 20 aborted transfers, with no pool +// reporting a single allocation failure. +// +// tcp_pcb peaked at 4 of 4 and stayed there: the server closes every +// connection itself, so each request leaves a pcb in TIME_WAIT for 2 x TCP_MSL +// and the pool is permanently full between requests. 6 slots is the 2 HTTP +// connections plus the debug stream plus headroom, and TCP_MSL below drains +// the rest six times faster. (Listening pcbs come from their own pool.) +#define MEMP_NUM_TCP_PCB 6 +// Peaked at 9 of 16 with two clients and aborted transfers. TCP_SND_QUEUELEN +// is 8 per connection, so 16 is what two senders can queue; left as is. #define MEMP_NUM_TCP_SEG 16 #define MEMP_NUM_ARP_QUEUE 2 +// Peaked at 2 of 12 even during 4 MB transfers: in poll mode a received pbuf +// is handled and freed before the driver allocates the next one, so the pool +// is only really used for out-of-order segments. Kept at 12 anyway -- this is +// the receive path, and a pool that runs dry drops packets off the air. #define PBUF_POOL_SIZE 12 #define LWIP_ARP 1 #define LWIP_ETHERNET 1 @@ -47,6 +63,15 @@ // IGMP is required by the mDNS responder for multicast group membership. #define LWIP_IGMP 1 #define TCP_MSS 1460 +// lwIP's default MSL is 60 s, so a closed connection holds its pcb for 2 +// minutes of TIME_WAIT and the 4-slot pool measured full after a handful of +// requests (EPIC-13 STORY-04). 10 s matches Booster and drains it in 20 s. The +// risk MSL guards against -- a delayed segment from an old connection landing +// on a new one with the same port pair -- needs a reused ephemeral port within +// the window, which a LAN client does not do. +#define TCP_MSL 10000UL +// Peak lwIP heap use (PBUF_RAM, from libc malloc here) was 12,920 bytes across +// the same scenarios; the 4 x MSS window costs nothing extra in .bss. #define TCP_WND (4 * TCP_MSS) #define TCP_SND_BUF (4 * TCP_MSS) #define TCP_SND_QUEUELEN ((2 * (TCP_SND_BUF) + (TCP_MSS - 1)) / (TCP_MSS)) From 3f1eee20555c91030971272b7f52effc16f8e7c1 Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Wed, 16 Sep 2026 23:37:44 +0200 Subject: [PATCH 3/8] Follow lwIP's callback contract (EPIC-13 STORY-03) Audited every raw-TCP callback against the pinned lwIP (2.2.1, not the 2.1 this story assumed), reading core/tcp.c, tcp_out.c and tcp_in.c rather than relying on the API docs. tcp_recved() could run on a closed pcb. Both streaming branches of srv_recv_cb called a response writer -- which closes the connection on a FatFs error or a Runner chunk timeout -- and then accounted for the segment. tcp_close() on a pcb whose window has not been returned sends an RST, purges the pcb and unlinks it from the active list before returning ERR_OK, so that tcp_recved() was touching a pcb already queued to be freed. It is now done once at the top of srv_recv_cb, before anything can close. The adv-load branch also continued into adv_load_finish_ok() after a failed dispatch, which re-fired the failed chunk and wrote a second response onto a connection that had already sent one; it now honours the drain's return value. send_buffered treated ERR_MEM as fatal and dropped the response. lwIP queues nothing on ERR_MEM and expects the application to wait for acks and try again, so a client lost a reply it was still waiting for. The write is split out as send_buffered_try: ERR_MEM leaves resp_queued false, srv_poll_cb retries every 4 s, and the idle sweep gives up after 20 s. stream_send_chunk wrote a chunk as three tcp_writes with no send-buffer check on the debug-log path, so a failure after the first put a chunk-size line on the wire with no body behind it. It now refuses to start a chunk the send buffer cannot hold whole. Two contract violations that are unreachable today but wrong next to correct code: srv_recv_cb's NULL-arg path freed the pbuf and returned ERR_VAL, which makes lwIP keep and re-deliver that pbuf (it now aborts and returns ERR_ABRT), and conn_close's tcp_abort fallback left the callback returning ERR_OK after an abort (it now reports through conn_takeAborted()). An empty-body download set HC_DRAINING without stream_body_done, so srv_sent_cb never closed it and a zero-length GET held one of the two connection slots for 20 s. It completes in 19 ms now. Verified on hardware, both builds: 4 MB round trips cmp identical, error responses unchanged, 15 listings against a concurrent download, 20 aborted transfers with no pool errors, smoke.py 8/8 debug and 7/7 release. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/http_server.c | 115 ++++++++++++++++++++++++++++++++----------- 1 file changed, 87 insertions(+), 28 deletions(-) diff --git a/rp/src/http_server.c b/rp/src/http_server.c index e08e882..39c4291 100644 --- a/rp/src/http_server.c +++ b/rp/src/http_server.c @@ -134,6 +134,7 @@ typedef struct http_conn { char resp[HTTP_RESPONSE_BUF_BYTES]; size_t resp_len; size_t resp_sent; + bool resp_queued; // resp is in lwIP's send queue; false means retry it // Streaming directory listing state. Active while state == // HC_STREAM_LISTING; the dir handle outlives a single TCP recv/sent @@ -209,6 +210,7 @@ static void parse_and_dispatch(http_conn_t *c, struct pbuf *seg, size_t body_off); static void route(http_conn_t *c); static void __not_in_flash_func(send_buffered)(http_conn_t *c); +static void __not_in_flash_func(send_buffered_try)(http_conn_t *c); static void write_response(http_conn_t *c, int status, const char *reason, const char *content_type, const char *body, @@ -384,6 +386,19 @@ static void conn_release_resources(http_conn_t *c) { } } +// Set when conn_close had to abort a pcb. lwIP requires the callback that +// caused the abort to return ERR_ABRT (core/tcp.c, tcp_abort docs), and +// conn_close is called from deep inside the response writers, so it reports +// through this flag rather than a return value threaded through every call +// site. Each callback clears it with conn_takeAborted() on the way out. +static bool g_conn_aborted; + +static bool conn_takeAborted(void) { + bool aborted = g_conn_aborted; + g_conn_aborted = false; + return aborted; +} + static void conn_close(http_conn_t *c) { conn_release_resources(c); if (c->pcb != NULL) { @@ -393,9 +408,13 @@ static void conn_close(http_conn_t *c) { tcp_sent(pcb, NULL); tcp_poll(pcb, NULL, 0); tcp_err(pcb, NULL); + // tcp_close only fails on a NULL pcb in this lwIP (ERR_MEM is deferred + // through TF_CLOSEPEND), so the abort is unreachable today -- but if it + // ever runs, the callback we are inside has to return ERR_ABRT. err_t err = tcp_close(pcb); if (err != ERR_OK) { tcp_abort(pcb); + g_conn_aborted = true; } } conn_free(c); @@ -428,10 +447,14 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st err_t err) { http_conn_t *c = (http_conn_t *)arg; if (c == NULL) { + // Nobody owns this pcb. Returning any other error would make lwIP keep + // the pbuf we just freed and deliver it again (core/tcp_in.c), so abort + // and report the abort, which is the one contract-legal way out. if (p != NULL) { pbuf_free(p); } - return ERR_VAL; + tcp_abort(pcb); + return ERR_ABRT; } if (err != ERR_OK || p == NULL) { // Peer closed or error; either way the connection is done. @@ -439,15 +462,20 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st pbuf_free(p); } conn_close(c); - return ERR_OK; + return conn_takeAborted() ? ERR_ABRT : ERR_OK; } conn_touch(c); + // Account for the segment here, once. A response writer can close the + // connection (a failed write, a FatFs error, a Runner timeout), and + // tcp_recved() on a closed pcb touches one lwIP has already purged and + // queued to be freed. + tcp_recved(pcb, p->tot_len); if (c->state == HC_READ_HEADERS) { // Only the headers go into c->hdr. Body bytes that shared this // segment with them stay in the pbuf and are handed to the // dispatcher by offset: copying them into c->hdr would drop - // everything past HTTP_HEADER_BUF_BYTES while tcp_recved below + // everything past HTTP_HEADER_BUF_BYTES while the tcp_recved above // still tells the peer they arrived. size_t hdr_before = c->hdr_len; size_t to_copy = p->tot_len; @@ -463,7 +491,6 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st c->hdr_len += to_copy; c->hdr[c->hdr_len] = '\0'; } - tcp_recved(pcb, p->tot_len); char *eoh = strstr(c->hdr, "\r\n\r\n"); if (eoh != NULL) { @@ -483,7 +510,6 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st pbuf_copy_partial(p, c->body + c->body_received, (u16_t)take, 0); c->body_received += take; } - tcp_recved(pcb, p->tot_len); pbuf_free(p); if (c->body_received >= c->content_length) { route(c); @@ -495,17 +521,15 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st size_t want = c->content_length - c->upload_received; size_t take = (p->tot_len < want) ? p->tot_len : want; FRESULT fr = FR_OK; - if (!upload_drain_pbuf(c, p, 0, take, &fr)) { + bool written = upload_drain_pbuf(c, p, 0, take, &fr); + pbuf_free(p); + if (!written) { // Surface 500 to the client; conn_close closes the FIL and // unlinks the partial file when the response has been drained. write_fs_error(c, fr, "f_write failed mid-upload"); - tcp_recved(pcb, p->tot_len); - pbuf_free(p); - return ERR_OK; + return conn_takeAborted() ? ERR_ABRT : ERR_OK; } c->upload_received += take; - tcp_recved(pcb, p->tot_len); - pbuf_free(p); if (c->upload_received >= c->content_length) { upload_finish_ok(c); } @@ -516,21 +540,22 @@ static err_t __not_in_flash_func(srv_recv_cb)(void *arg, struct tcp_pcb *pcb, st // client may have sent more than we'll honour. size_t want = (size_t)(c->adv_load_total - c->adv_load_received); size_t take = (p->tot_len < want) ? p->tot_len : want; - if (take > 0) { - (void)adv_load_drain_pbuf(c, p, 0, take); - } - tcp_recved(pcb, p->tot_len); + bool drained = (take == 0) || adv_load_drain_pbuf(c, p, 0, take); pbuf_free(p); + if (!drained) { + // A chunk dispatch timed out; the 504 is already written and the + // load is over. Finishing it here would re-fire the failed chunk. + return conn_takeAborted() ? ERR_ABRT : ERR_OK; + } if (c->adv_load_received >= c->adv_load_total) { adv_load_finish_ok(c); } } else { // Already writing the response (or draining); discard any extra // bytes the client sent. - tcp_recved(pcb, p->tot_len); pbuf_free(p); } - return ERR_OK; + return conn_takeAborted() ? ERR_ABRT : ERR_OK; } static err_t __not_in_flash_func(srv_sent_cb)(void *arg, struct tcp_pcb *pcb, u16_t len) { @@ -556,7 +581,7 @@ static err_t __not_in_flash_func(srv_sent_cb)(void *arg, struct tcp_pcb *pcb, u1 // ack'd; safe to close. conn_close(c); } - return ERR_OK; + return conn_takeAborted() ? ERR_ABRT : ERR_OK; } static err_t srv_poll_cb(void *arg, struct tcp_pcb *pcb) { @@ -570,7 +595,14 @@ static err_t srv_poll_cb(void *arg, struct tcp_pcb *pcb) { // Try to push any bytes that may have arrived since the last drive. if (c->state == HC_STREAM_DEBUG) { stream_debug_drive(c); - return ERR_OK; + return conn_takeAborted() ? ERR_ABRT : ERR_OK; + } + // A response lwIP had no room for is still owed to the client. Retry it + // here; if it never goes out, the idle timeout below closes the + // connection. + if (c->state == HC_WRITE_RESPONSE && !c->resp_queued) { + send_buffered_try(c); + return conn_takeAborted() ? ERR_ABRT : ERR_OK; } uint32_t idle_ms = (uint32_t)to_ms_since_boot(get_absolute_time()) - c->last_activity_ms; @@ -583,7 +615,7 @@ static err_t srv_poll_cb(void *arg, struct tcp_pcb *pcb) { (unsigned long)idle_ms, (int)c->state, (unsigned long)c->upload_received, (unsigned long)c->content_length); conn_close(c); - return ERR_OK; + return conn_takeAborted() ? ERR_ABRT : ERR_OK; } static void srv_err_cb(void *arg, err_t err) { @@ -3111,6 +3143,11 @@ static err_t __not_in_flash_func(stream_send_chunk)(http_conn_t *c, char hdr[16]; int hn = snprintf(hdr, sizeof(hdr), "%lX\r\n", (unsigned long)body_len); if (hn < 0 || hn >= (int)sizeof(hdr)) return ERR_VAL; + // A chunk is three writes, and a client cannot make sense of a size line + // with no body after it. Only start one the send buffer can hold whole. + if (tcp_sndbuf(c->pcb) < (u16_t)hn + body_len + 2) { + return ERR_MEM; + } err_t err = tcp_write(c->pcb, hdr, (u16_t)hn, TCP_WRITE_FLAG_COPY | TCP_WRITE_FLAG_MORE); if (err != ERR_OK) return err; @@ -3815,6 +3852,10 @@ static void handle_file_download(http_conn_t *c, g_body_stream_busy = false; c->holds_body_lock = false; } + // Nothing follows the headers, so the peer's ack of them is the end of + // the response. Without this srv_sent_cb's HC_DRAINING branch never + // fires and the connection sits on a slot until the idle sweep. + c->stream_body_done = true; c->state = HC_DRAINING; return; } @@ -4479,17 +4520,35 @@ static void route(http_conn_t *c) { // --- Response writers --- -static void __not_in_flash_func(send_buffered)(http_conn_t *c) { - c->state = HC_WRITE_RESPONSE; - c->resp_sent = 0; - err_t err = tcp_write(c->pcb, c->resp, (u16_t)c->resp_len, - TCP_WRITE_FLAG_COPY); +// Try to hand the buffered response to lwIP. ERR_MEM means it queued +// nothing (core/tcp_out.c) and the application is expected to wait for the +// peer to acknowledge what is already in flight and try again -- so leave +// resp_queued false and let the poll callback come back to it. Dropping the +// response and closing, as this used to do, loses a reply the client is +// still waiting for. +static void __not_in_flash_func(send_buffered_try)(http_conn_t *c) { + if (c->pcb == NULL || c->resp_queued) { + return; + } + err_t err = + tcp_write(c->pcb, c->resp, (u16_t)c->resp_len, TCP_WRITE_FLAG_COPY); if (err == ERR_OK) { + c->resp_queued = true; tcp_output(c->pcb); - } else { - DPRINTF("http_server: tcp_write failed: %d\n", err); - conn_close(c); + return; + } + if (err == ERR_MEM) { + return; // nothing queued; srv_poll_cb retries, the idle sweep gives up } + DPRINTF("http_server: tcp_write failed: %d\n", err); + conn_close(c); +} + +static void __not_in_flash_func(send_buffered)(http_conn_t *c) { + c->state = HC_WRITE_RESPONSE; + c->resp_sent = 0; + c->resp_queued = false; + send_buffered_try(c); } // Write a response with optional extra header lines (each must end From b15ca5009762ed9b8dfea0adb8d228bc27ec53be Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Wed, 16 Sep 2026 23:49:26 +0200 Subject: [PATCH 4/8] Wake a stalled streamer from the poll callback (EPIC-13 STORY-05) stream_download_drive returns when tcp_write reports ERR_MEM and waits for a sent callback to pump the rest. That callback only arrives when the peer acknowledges something, so a writer that stopped with nothing unacknowledged -- ERR_MEM from an exhausted pool rather than a full window -- waited for an event that could not come, and the transfer sat there until the idle sweep closed it. srv_poll_cb now drives HC_STREAM_DOWNLOAD and HC_STREAM_LISTING as well as retrying a pending buffered response, then falls through to the idle check so a peer that really has gone away is still swept. The other two halves of this story landed with STORY-03: stream_send_chunk will not start a chunk the send buffer cannot hold whole, and send_buffered retries instead of dropping the response. Tested with EPIC-11's heap-hold hook at 5,112 bytes free, where the heap minimum reached 480 bytes and lwIP reported 1,595 failed allocations: error responses, listings, and 256 KB and 4 MB downloads all completed intact, a 4 MB upload returned 201, and service recovered when the hold was released. The same run on a458ac2 behaves the same, so that scenario does not discriminate between the builds; these are contract fixes read out of the lwIP source, not a reproduced failure. What does exercise the path is a slow reader: 256 KB to a client reading at 5 KB/s now arrives complete with a matching sha256 in 53 s, with the heap held at 5 KB free as well. In EPIC-09 that client was cut off after 8.4 s and 39,420 bytes. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/http_server.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/rp/src/http_server.c b/rp/src/http_server.c index 39c4291..2855d50 100644 --- a/rp/src/http_server.c +++ b/rp/src/http_server.c @@ -236,6 +236,8 @@ static void srv_err_cb(void *arg, err_t err); static void stream_listing_drive(http_conn_t *c); static void __not_in_flash_func(stream_download_drive)(http_conn_t *c); static void stream_debug_drive(http_conn_t *c); +static void __not_in_flash_func(stream_download_drive)(http_conn_t *c); +static void stream_listing_drive(http_conn_t *c); // Chunked-encoding helpers (definitions further down). static err_t __not_in_flash_func(stream_send_chunk)(http_conn_t *c, const char *body, size_t body_len); @@ -597,12 +599,20 @@ static err_t srv_poll_cb(void *arg, struct tcp_pcb *pcb) { stream_debug_drive(c); return conn_takeAborted() ? ERR_ABRT : ERR_OK; } - // A response lwIP had no room for is still owed to the client. Retry it - // here; if it never goes out, the idle timeout below closes the - // connection. + // Anything lwIP had no room for is still owed to the client, and a writer + // that stopped on ERR_MEM with nothing unacknowledged never gets a sent + // callback to wake it -- poll is the only thing that can retry. Falls + // through to the idle check below, so a peer that has really gone away is + // still swept. if (c->state == HC_WRITE_RESPONSE && !c->resp_queued) { send_buffered_try(c); - return conn_takeAborted() ? ERR_ABRT : ERR_OK; + } else if (c->state == HC_STREAM_DOWNLOAD) { + stream_download_drive(c); + } else if (c->state == HC_STREAM_LISTING) { + stream_listing_drive(c); + } + if (c->state == HC_FREE) { + return conn_takeAborted() ? ERR_ABRT : ERR_OK; // the retry closed it } uint32_t idle_ms = (uint32_t)to_ms_since_boot(get_absolute_time()) - c->last_activity_ms; From f10bd9700df9067d8ef709edac7b1f2eab65aa65 Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Wed, 16 Sep 2026 23:53:20 +0200 Subject: [PATCH 5/8] Give FatFs enough lock entries for both sides (EPIC-13 STORY-06) FF_FS_LOCK counts open files and open non-root directories, and it is shared by everything on the card. The worst case this firmware can reach is 28: GEMDRIVE's 8 open files, its 16 searches (each DTA slot keeps a DIR open between Fsfirst and Fsnext), and 2 HTTP connections holding a FIL and a DIR each. The table was 8, so the ST on its own could exhaust it and starve any HTTP transfer, or the reverse. Sized to 28, with the arithmetic written next to it. Each entry is a 16-byte FILESEM, so the heap ceiling drops by 320 bytes, from 46,224 to 45,904 -- measured, and matching the prediction. Capping searches was the alternative, rejected because the cap would be enforced against a limit the ST cannot see. FR_TOO_MANY_OPEN_FILES was previously reported as whatever each handler's generic failure happened to be: Fopen said "file not found", Fcreate and Fsfirst said "path not found", and the HTTP server called it a disk error. It is now ENHNDL (-35) on all three GEMDOS paths and 503 too_many_open_files over HTTP, next to the existing 503 insufficient_memory. Both are retry-later conditions rather than faults. The HTTP half is verified on hardware: a 4 MB download with 10 listings running against it, all 200 and cmp identical, smoke.py 8/8. The ST half -- several desktop windows open during a copy and a transfer -- still needs the Atari. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/ff/ffconf.h | 7 ++++++- rp/src/gemdrive.c | 17 +++++++++++++---- rp/src/http_server.c | 7 +++++++ 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/rp/src/ff/ffconf.h b/rp/src/ff/ffconf.h index ea4cdde..a562ef4 100644 --- a/rp/src/ff/ffconf.h +++ b/rp/src/ff/ffconf.h @@ -251,7 +251,12 @@ number. / bit1=1: Do not trust last allocated cluster number in the FSINFO. */ -#define FF_FS_LOCK 8 +/* 28 = the worst case this firmware can reach at once (EPIC-13 STORY-06): +/ GEMDRIVE_MAX_OPEN_FILES 8 open files, plus GEMDRIVE_MAX_DTAS 16 searches that +/ each keep a DIR open between Fsfirst and Fsnext, plus the HTTP server's +/ HTTP_SERVER_MAX_CONNECTIONS 2 connections holding a FIL and a DIR each. +/ Each entry is a 16-byte FILESEM, so the table costs 448 bytes of .bss. */ +#define FF_FS_LOCK 28 /* The option FF_FS_LOCK switches file lock function to control duplicated file open / and illegal operation to open objects. This option must be 0 when FF_FS_READONLY / is 1. diff --git a/rp/src/gemdrive.c b/rp/src/gemdrive.c index 20968fa..066bb53 100644 --- a/rp/src/gemdrive.c +++ b/rp/src/gemdrive.c @@ -702,7 +702,9 @@ static void __not_in_flash_func(handleFcreateCall)(uint16_t *payload) { if (res != FR_OK) { DPRINTF("GEMDRIVE Fcreate: '%s' -> fr=%d\n", sdPath, (int)res); releaseFileSlot(slotIdx); - writeAppFreeWord(GEMDRIVE_FCREATE_HANDLE_OFFSET, (uint16_t)-34); // EPTHNF + uint16_t err = (res == FR_TOO_MANY_OPEN_FILES) ? (uint16_t)-35 // ENHNDL + : (uint16_t)-34; // EPTHNF + writeAppFreeWord(GEMDRIVE_FCREATE_HANDLE_OFFSET, err); return; } // Match source: apply the GEMDOS attrib mode via f_chmod immediately @@ -976,7 +978,11 @@ static void __not_in_flash_func(handleFopenCall)(uint16_t *payload) { DPRINTF("GEMDRIVE Fopen: '%s' (mode=%lu) failed (%d)\n", sdPath, (unsigned long)mode, (int)res); releaseFileSlot(slotIdx); - writeAppFreeLong(GEMDRIVE_FOPEN_HANDLE_OFFSET, (uint32_t)-33); // EFILNF + // FatFs's lock table is shared with the HTTP server; a full one is out of + // handles, not a missing file (EPIC-13 STORY-06). + uint32_t err = (res == FR_TOO_MANY_OPEN_FILES) ? (uint32_t)-35 // ENHNDL + : (uint32_t)-33; // EFILNF + writeAppFreeLong(GEMDRIVE_FOPEN_HANDLE_OFFSET, err); return; } int handle = handleFromSlotIndex(slotIdx); @@ -1262,8 +1268,11 @@ static void __not_in_flash_func(handleFsfirstCall)(uint16_t *payload) { pattern, (int)res); releaseDtaSlot(dtaAddr); // Match md-drives-emulator: EPTHNF (-34) when path doesn't exist, - // EFILNF (-33) when path exists but no entries match. - uint16_t err = (res == FR_NO_PATH) ? 0xFFDE : 0xFFDF; + // EFILNF (-33) when path exists but no entries match. A full lock table + // is neither -- it is out of handles (EPIC-13 STORY-06). + uint16_t err = (res == FR_TOO_MANY_OPEN_FILES) ? 0xFFDD // ENHNDL (-35) + : (res == FR_NO_PATH) ? 0xFFDE + : 0xFFDF; clearDtaFound(err); return; } diff --git a/rp/src/http_server.c b/rp/src/http_server.c index 2855d50..7e5c448 100644 --- a/rp/src/http_server.c +++ b/rp/src/http_server.c @@ -4625,6 +4625,13 @@ static void write_fs_error(http_conn_t *c, FRESULT fr, const char *message) { write_error(c, 503, "Service Unavailable", "insufficient_memory", message); return; } + // FatFs's lock table is shared with GEMDRIVE (FF_FS_LOCK in ffconf.h). A + // full table means the ST is holding its share right now, so this is also + // worth retrying rather than a disk fault (EPIC-13 STORY-06). + if (fr == FR_TOO_MANY_OPEN_FILES) { + write_error(c, 503, "Service Unavailable", "too_many_open_files", message); + return; + } write_error(c, 500, "Internal Server Error", "disk_error", message); } From 3f620210b7a5f32c044e96aa866780136d589eae Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Wed, 16 Sep 2026 23:56:19 +0200 Subject: [PATCH 6/8] Keep SELECT and the console alive during spin-waits (EPIC-13 STORY-07) Six HTTP handlers block inside srv_recv_cb while the ST answers -- 10 s for a Runner load, 5 s for an unload, 1 s for an advanced-load chunk and for each of the three meminfo waits. Nothing else runs meanwhile, so for the length of the wait the SELECT button did nothing and queued console bytes stayed in the ring. All six had the same three lines, so they now share one http_spinTick() that also polls SELECT and drains USB CDC. The watchdog feed and the HTTP_WAIT phase were already there from EPIC-09 STORY-06. smoke.py 8/8 on debug. The check that actually enters a spin-wait -- SELECT pressed during a 10 s runner load -- needs the ST in Runner mode and is still open. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/http_server.c | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/rp/src/http_server.c b/rp/src/http_server.c index 7e5c448..8372ba0 100644 --- a/rp/src/http_server.c +++ b/rp/src/http_server.c @@ -27,6 +27,7 @@ #include "pico/cyw43_arch.h" #include "pico/time.h" #include "runner.h" +#include "select.h" #include "settings.h" #include "usbcdc.h" @@ -350,6 +351,19 @@ static bool upload_drain_pbuf(http_conn_t *c, struct pbuf *seg, size_t off, return true; } +// What a spin-wait owes the rest of the firmware. Six HTTP handlers block +// inside srv_recv_cb while the ST answers -- up to 10 s for a Runner load -- +// and nothing else runs meanwhile, so each turn of those loops has to feed the +// watchdog, drain the cartridge ring the ST is waiting on, poll SELECT so the +// button still resets the device, and push queued console bytes out of USB. +static void http_spinTick(void) { + health_feed(); + health_setPhase(HEALTH_PHASE_HTTP_WAIT); + chandler_loop(); + select_checkPushReset(); + usbcdc_drain(); +} + // Traffic in either direction keeps a connection alive for the sweeper. static void conn_touch(http_conn_t *c) { c->last_activity_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); @@ -1808,9 +1822,7 @@ static void handle_runner_load(http_conn_t *c) { absolute_time_t deadline = delayed_by_us(get_absolute_time(), RUNNER_LOAD_TIMEOUT_US); while (emul_isRunnerBusy()) { - health_feed(); - health_setPhase(HEALTH_PHASE_HTTP_WAIT); - chandler_loop(); + http_spinTick(); if (absolute_time_diff_us(get_absolute_time(), deadline) <= 0) { uint32_t fail_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); // Treat the timeout as a load failure with a synthetic @@ -1939,9 +1951,7 @@ static void handle_runner_unload(http_conn_t *c) { absolute_time_t deadline = delayed_by_us(get_absolute_time(), RUNNER_UNLOAD_TIMEOUT_US); while (emul_isRunnerBusy()) { - health_feed(); - health_setPhase(HEALTH_PHASE_HTTP_WAIT); - chandler_loop(); + http_spinTick(); if (absolute_time_diff_us(get_absolute_time(), deadline) <= 0) { uint32_t fail_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); // Synthetic timeout failure — keeps state consistent @@ -2387,9 +2397,7 @@ static bool adv_load_dispatch_chunk(http_conn_t *c) { absolute_time_t deadline = delayed_by_us(get_absolute_time(), ADV_LOAD_TIMEOUT_US); while (!emul_isRunnerAdvLoadAcked()) { - health_feed(); - health_setPhase(HEALTH_PHASE_HTTP_WAIT); - chandler_loop(); + http_spinTick(); if (absolute_time_diff_us(get_absolute_time(), deadline) <= 0) { DPRINTF("adv_load: chunk dispatch timed out at target=0x%lX len=%lu\n", (unsigned long)c->adv_load_target, (unsigned long)len); @@ -2509,9 +2517,7 @@ static bool handle_runner_adv_load_init(http_conn_t *c, struct pbuf *seg, absolute_time_t deadline = delayed_by_us(get_absolute_time(), RUNNER_MEMINFO_TIMEOUT_US); while (!emul_isRunnerMeminfoReady()) { - health_feed(); - health_setPhase(HEALTH_PHASE_HTTP_WAIT); - chandler_loop(); + http_spinTick(); if (absolute_time_diff_us(get_absolute_time(), deadline) <= 0) { runner_meminfo_t empty = {0}; uint32_t fail_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); @@ -2582,9 +2588,7 @@ static void handle_runner_adv_meminfo(http_conn_t *c) { absolute_time_t deadline = delayed_by_us(get_absolute_time(), RUNNER_MEMINFO_TIMEOUT_US); while (!emul_isRunnerMeminfoReady()) { - health_feed(); - health_setPhase(HEALTH_PHASE_HTTP_WAIT); - chandler_loop(); + http_spinTick(); if (absolute_time_diff_us(get_absolute_time(), deadline) <= 0) { uint32_t fail_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); runner_meminfo_t empty = {0}; @@ -2809,9 +2813,7 @@ static void handle_runner_meminfo(http_conn_t *c) { absolute_time_t deadline = delayed_by_us(get_absolute_time(), RUNNER_MEMINFO_TIMEOUT_US); while (!emul_isRunnerMeminfoReady()) { - health_feed(); - health_setPhase(HEALTH_PHASE_HTTP_WAIT); - chandler_loop(); + http_spinTick(); if (absolute_time_diff_us(get_absolute_time(), deadline) <= 0) { // Timeout — clear busy and report. uint32_t fail_ms = (uint32_t)to_ms_since_boot(get_absolute_time()); From 40b6d0b14ae2dff18f8000060a8427eb58587e91 Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Thu, 17 Sep 2026 00:03:32 +0200 Subject: [PATCH 7/8] Drop the abort flag when closing outside a callback (EPIC-13 STORY-03) http_server_deinit closes every live connection, but it is not running inside an lwIP callback, so there is nobody to return ERR_ABRT. Leaving the flag set would make the next callback report an abort that never happened. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/http_server.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rp/src/http_server.c b/rp/src/http_server.c index 8372ba0..4c102b2 100644 --- a/rp/src/http_server.c +++ b/rp/src/http_server.c @@ -206,6 +206,7 @@ static bool g_body_stream_busy = false; static http_conn_t *conn_alloc(void); static void conn_free(http_conn_t *c); static void conn_close(http_conn_t *c); +static bool conn_takeAborted(void); static void parse_and_dispatch(http_conn_t *c, struct pbuf *seg, size_t body_off); @@ -301,6 +302,9 @@ void http_server_deinit(void) { conn_close(&g_conns[i]); } } + // Not inside a callback, so there is nobody to return ERR_ABRT: drop the + // flag rather than leave it for the next one. + (void)conn_takeAborted(); } // --- Connection lifecycle --- From 4e472492771390bf64bea3c0fc3d716a57a755df Mon Sep 17 00:00:00 2001 From: Diego Parrilla Date: Thu, 17 Sep 2026 12:17:04 +0200 Subject: [PATCH 8/8] Clear the loaded-program mirror when the Runner cold boots (EPIC-13 STORY-08) emul_resetRunnerSession() runs on the Runner's HELLO, which means the ST has cold booted and owns nothing. It cleared busy, cwd and the errnos but left runnerPendingBasepage set, so the RP stayed certain a program was still loaded across an ST reboot: every later load answered 409 program_already_loaded, and the unload that would have cleared it answered 422, because the ST rightly refuses to Mfree a basepage from a previous life (mfree_result=-40, EIMBA). Nothing the API offered could recover it -- one crashed program poisoned the Runner until the RP itself was rebooted. The session reset now clears the basepage mirror and the load errno with everything else. Verified on hardware: after an ST reset the API reports loaded_basepage null and loads work again. Found while soaking the Runner for STORY-08. The soak itself is still blocked by a separate defect that is not ours: exec takes the Atari down about one time in three, usually cold-booting it (which the RP now recovers from by itself) and occasionally wedging it until a physical reset. Written up in the story. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016emgLTZm7w3qZsRbukWwE4 --- rp/src/emul.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/rp/src/emul.c b/rp/src/emul.c index 60c30ae..22add4d 100644 --- a/rp/src/emul.c +++ b/rp/src/emul.c @@ -445,6 +445,15 @@ void emul_resetRunnerSession(void) { runnerLastCdErrno = 0; runnerLastHasResErrno = false; runnerLastResErrno = 0; + // The session resets on the Runner's HELLO, which means the ST has cold + // booted and owns nothing: no basepage, no failed unload to report. Keeping + // the mirror across that left the RP certain a program was still loaded, so + // every later load answered 409 and the unload that would have cleared it + // answered 422 -- the ST rightly refuses to Mfree a basepage from a previous + // life (EPIC-13 STORY-08). + runnerPendingBasepage = 0; + runnerLoadHasErrno = false; + runnerLoadErrno = 0; runnerMeminfoPending = false; runnerMeminfoHasSnapshot = false; runnerAdvancedInstalled = false;