From 8a227e88138d080f8c85871e12001580a7bed8d9 Mon Sep 17 00:00:00 2001 From: Adam Shiervani Date: Fri, 4 Dec 2026 13:56:10 +0100 Subject: [PATCH 1/3] Let a memory request name the PSRAM that it has allocated already A request's psram_allocated_bytes is the part of psram_bytes that free PSRAM no longer has. Admission charges psram_bytes less that part, so the part counts once. The reservation still holds all of psram_bytes, and other owners are judged against all of it. --- .../include/jetkvm_memory_policy.h | 4 + .../jetkvm_memory_policy.c | 6 +- .../tests/run_static_test.sh | 1 + .../tests/test_queued_body_admission.py | 166 ++++++++++++++++++ 4 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 components/jetkvm_memory_policy/tests/test_queued_body_admission.py diff --git a/components/jetkvm_memory_policy/include/jetkvm_memory_policy.h b/components/jetkvm_memory_policy/include/jetkvm_memory_policy.h index 06548190..960c2ee8 100644 --- a/components/jetkvm_memory_policy/include/jetkvm_memory_policy.h +++ b/components/jetkvm_memory_policy/include/jetkvm_memory_policy.h @@ -231,6 +231,10 @@ typedef struct { size_t dma_largest_block; size_t psram_bytes; size_t psram_largest_block; + /* The part of psram_bytes that is allocated already, so that free PSRAM + * no longer has it. Admission charges psram_bytes less this part; the + * reservation holds all of psram_bytes. */ + size_t psram_allocated_bytes; /* Logical data already resident or allowed to materialize in the shared * storage ingress window. This remains reserved after physical PSRAM * allocation so RTC/SCTP/future reorder owners cannot exceed 4 MiB. */ diff --git a/components/jetkvm_memory_policy/jetkvm_memory_policy.c b/components/jetkvm_memory_policy/jetkvm_memory_policy.c index 401fbc10..c0bd25f5 100644 --- a/components/jetkvm_memory_policy/jetkvm_memory_policy.c +++ b/components/jetkvm_memory_policy/jetkvm_memory_policy.c @@ -357,7 +357,8 @@ static bool request_shape_valid( return request != NULL && request->dma_bytes <= request->internal_bytes && request->internal_largest_block <= request->internal_bytes && request->dma_largest_block <= request->dma_bytes && - request->psram_largest_block <= request->psram_bytes; + request->psram_largest_block <= request->psram_bytes && + request->psram_allocated_bytes <= request->psram_bytes; } esp_err_t jetkvm_memory_policy_init(void) @@ -640,7 +641,8 @@ static bool psram_fits( request->psram_largest_block > reserved_psram_largest ? request->psram_largest_block : reserved_psram_largest; return has_projected_floor(memory->psram_free, reserved_psram, - request->psram_bytes, + request->psram_bytes - + request->psram_allocated_bytes, JETKVM_MEMORY_PSRAM_ADMISSION_FLOOR_BYTES) && largest <= memory->psram_largest; } diff --git a/components/jetkvm_memory_policy/tests/run_static_test.sh b/components/jetkvm_memory_policy/tests/run_static_test.sh index 6c025766..1cd09b2e 100755 --- a/components/jetkvm_memory_policy/tests/run_static_test.sh +++ b/components/jetkvm_memory_policy/tests/run_static_test.sh @@ -10,3 +10,4 @@ python3 "$component_dir/tests/test_fragmented_psram_admission.py" python3 "$component_dir/tests/test_snapshot_cache.py" python3 "$component_dir/tests/test_psram_only_admission.py" python3 "$component_dir/tests/test_psram_wait_admission.py" +python3 "$component_dir/tests/test_queued_body_admission.py" diff --git a/components/jetkvm_memory_policy/tests/test_queued_body_admission.py b/components/jetkvm_memory_policy/tests/test_queued_body_admission.py new file mode 100644 index 00000000..d6f0eec9 --- /dev/null +++ b/components/jetkvm_memory_policy/tests/test_queued_body_admission.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""An upload whose body is queued in lwIP when its headers are admitted. + +The queued frames are in PSRAM and are part of the TCP window that the upload +charges. Numbers from a refusal on an Ethernet Mini: 262,144 B of body queued, +a 1,310,720 B window and a 6,144 B writer stack. +""" + +from pathlib import Path +import os +import re +import subprocess +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = (ROOT / 'jetkvm_memory_policy.c').read_text() +HEADER = (ROOT / 'include/jetkvm_memory_policy.h').read_text() + + +def function(name): + match = re.search(r'(?:static )?(?:(?:bool|void|esp_err_t|int32_t|size_t) |jetkvm_memory_policy_tls_admission_t \*)' + name + r'\([^;]*?\)\s*\{', SOURCE, re.S) + assert match, name + depth, end = 1, match.end() + while depth: + depth += (SOURCE[end] == '{') - (SOURCE[end] == '}') + end += 1 + return SOURCE[match.start():end] + + +logic = '\n'.join(function(name) for name in ( + 'has_projected_floor', 'projected_headroom', 'record_tls_admission', 'watch_held_tls', + 'request_shape_valid', 'psram_fits', 'request_fits', + 'video_rebuild_blocks', 'reserve_with_domain', 'jetkvm_memory_policy_reserve', + 'jetkvm_memory_policy_reserve_psram', 'reserve_tls_with_domain', + 'jetkvm_memory_policy_reserve_tls', 'jetkvm_memory_policy_release', +)) +macros = [] +for name in sorted(set(re.findall(r'JETKVM_MEMORY_\w+', logic))): + match = re.search(r'^#define ' + name + r'\s+((?:[^\n]*\\\n)*[^\n]*)', HEADER, re.M) + assert match, name + macros.append(match.group(0)) +types = [value for value in re.findall(r'typedef struct \{.*?\} \w+;', HEADER, re.S) + if value.endswith((' jetkvm_memory_policy_snapshot_t;', + ' jetkvm_memory_policy_request_t;', + ' jetkvm_memory_policy_reservation_t;', + ' jetkvm_memory_policy_tls_admission_t;'))] +assert len(types) == 4 +slot = re.search(r'typedef struct \{.*?\} reservation_slot_t;', SOURCE, re.S).group(0) +prefix = r''' +#include +#include +#include +#include +#include +#include +#include +''' +mock = r''' +/* The Ethernet board: no blocks of the Wi-Fi link in a TLS reservation. */ +#define JETKVM_MEMORY_TLS_LINK_BLOCKS 0U +#define JETKVM_MEMORY_WIFI_LINK_BLOCK_BYTES 1604U +typedef int esp_err_t; +#define MALLOC_CAP_INTERNAL 1U +#define MALLOC_CAP_8BIT 2U +#define MALLOC_CAP_DMA 4U +#define MALLOC_CAP_SPIRAM 8U +#define portMAX_DELAY UINT32_MAX +#define pdTRUE 1 +#define ESP_LOGW(...) ((void)0) +static jetkvm_memory_policy_snapshot_t memory; +static int mutex_storage; +static void *s_reservation_mutex = &mutex_storage; +static bool held; +static reservation_slot_t s_reservations[JETKVM_MEMORY_RESERVATION_SLOTS]; +static uint32_t s_next_reservation_generation = 1; +static struct { bool active; size_t working_set_bytes; } s_video_rebuild; +static jetkvm_memory_policy_tls_admission_t + tls_admission_storage[JETKVM_MEMORY_TLS_ADMISSION_OWNERS]; +static jetkvm_memory_policy_tls_admission_t *s_tls_admissions = tls_admission_storage; +static atomic_uint s_admission_denials, s_video_rebuild_blocked_materializations; +static int xSemaphoreTake(void *mutex, uint32_t ticks) { + assert(mutex == &mutex_storage && ticks == portMAX_DELAY && !held); + held = true; return pdTRUE; +} +static void xSemaphoreGive(void *mutex) { + assert(mutex == &mutex_storage && held); held = false; +} +/* The timer that reads free memory while a TLS reservation is held does + * not run in this test. */ +static void watch_run_locked(bool run) { (void)run; } +static size_t heap_caps_get_free_size(unsigned caps) { + if (caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)) return memory.internal_free; + if (caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)) return memory.dma_free; + assert(caps == (MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); return memory.psram_free; +} +static size_t heap_caps_get_largest_free_block(unsigned caps) { + if (caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)) return memory.internal_largest; + if (caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)) return memory.dma_largest; + assert(caps == (MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); return memory.psram_largest; +} +''' +cases = r''' +#define WINDOW 1310720U +#define STACK 6144U +#define QUEUED 262144U + +static bool upload_fits(size_t queued, jetkvm_memory_policy_reservation_t *upload) { + const jetkvm_memory_policy_request_t request = { + .psram_bytes = WINDOW + STACK, .psram_largest_block = STACK, + .psram_allocated_bytes = queued, + }; + return jetkvm_memory_policy_reserve("http-storage-upload", &request, upload); +} + +static bool psram_fits_now(size_t size) { + jetkvm_memory_policy_reservation_t ticket = {0}; + const bool admitted = jetkvm_memory_policy_reserve_psram("other", size, &ticket); + jetkvm_memory_policy_release(&ticket); + return admitted; +} + +int main(void) { + memory = (jetkvm_memory_policy_snapshot_t) { + .internal_free = 190843, .dma_free = 151767, + .psram_largest = 5767168, .internal_largest = 65536, .dma_largest = 65536, + }; + jetkvm_memory_policy_reservation_t upload = {0}; + + /* What free PSRAM shows with the body queued: the upload fits, without + * the queued bytes it would not. */ + memory.psram_free = JETKVM_MEMORY_PSRAM_ADMISSION_FLOOR_BYTES + WINDOW + STACK - QUEUED; + assert(!upload_fits(0U, &upload) && !upload.active); + assert(upload_fits(QUEUED, &upload) && upload.active); + jetkvm_memory_policy_release(&upload); + memory.psram_free -= 1U; + assert(!upload_fits(QUEUED, &upload)); + + /* The queued bytes are no more than the request. */ + memory.psram_free = 32U * 1024U * 1024U; + const jetkvm_memory_policy_request_t more = { + .psram_bytes = WINDOW, .psram_allocated_bytes = WINDOW + 1U, + }; + assert(!jetkvm_memory_policy_reserve("http-storage-upload", &more, &upload)); + + /* The reservation keeps the whole window: once the body is read, lwIP can + * fill the window again, and another owner is judged against all of it. */ + assert(upload_fits(QUEUED, &upload)); + memory.psram_free = JETKVM_MEMORY_PSRAM_ADMISSION_FLOOR_BYTES + WINDOW + STACK + 4096U; + assert(psram_fits_now(4096U) && !psram_fits_now(4097U)); + jetkvm_memory_policy_release(&upload); + assert(!held); + return 0; +} +''' +with tempfile.TemporaryDirectory(prefix='p4-queued-body-admission-') as temporary: + directory = Path(temporary) + source = directory / 'test.c' + executable = directory / 'test' + source.write_text('\n'.join([prefix, *macros, *types, slot, mock, logic, cases])) + subprocess.run(['cc', '-std=c11', '-Wall', '-Wextra', '-Werror', + '-fsanitize=address,undefined', '-fno-omit-frame-pointer', + str(source), '-o', str(executable)], check=True) + subprocess.run([str(executable)], check=True, + env={**os.environ, 'ASAN_OPTIONS': 'detect_leaks=0'}) +print('queued upload body counted once at admission, whole window reserved: PASS') From 63390349bf0a12be4c0c6f7908dc8ab0385d63b5 Mon Sep 17 00:00:00 2001 From: Adam Shiervani Date: Fri, 4 Dec 2026 13:56:15 +0100 Subject: [PATCH 2/3] Count the queued body of an upload once at its memory admission The upload's admission runs when the HTTP server reads the request head. Body bytes that arrived before then wait in lwIP's receive queue, one PSRAM block per frame, so free PSRAM no longer has them, and the admission charged them again as part of the 1.25 MiB TCP window. With a browser session and Tailscale on, a bench build refused uploads from about 100 KiB of queued body, while the same upload with its body sent 1.5 s later was admitted. The handler reads the queued bytes with FIONREAD (CONFIG_LWIP_SO_RCVBUF) and names them as allocated in its request. The reservation still holds the whole window, because lwIP can fill it again once the body is read. --- .../jetkvm_virtual_media_http.c | 19 +++++++++++++++++++ sdkconfig.defaults | 2 ++ 2 files changed, 21 insertions(+) diff --git a/components/jetkvm_virtual_media_http/jetkvm_virtual_media_http.c b/components/jetkvm_virtual_media_http/jetkvm_virtual_media_http.c index 0e425068..38e3f294 100644 --- a/components/jetkvm_virtual_media_http/jetkvm_virtual_media_http.c +++ b/components/jetkvm_virtual_media_http/jetkvm_virtual_media_http.c @@ -831,6 +831,21 @@ static bool allocate_upload_buffers_with_fallback( return allocate_upload_buffers(allocations, true); } +/* Body bytes that arrived before the handler ran wait in lwIP's receive + * queue, each frame in its own PSRAM block. They are part of the TCP window + * that admission charges, and free PSRAM no longer has them. FIONREAD needs + * CONFIG_LWIP_SO_RCVBUF. */ +static size_t queued_request_bytes(httpd_req_t *request) +{ + int queued = 0; + const int fd = httpd_req_to_sockfd(request); + if (fd < 0 || lwip_ioctl(fd, FIONREAD, &queued) != 0 || queued <= 0) { + return 0U; + } + return (size_t)queued < JETKVM_MEMORY_HTTP_TCP_RECEIVE_MAX_BYTES ? + (size_t)queued : JETKVM_MEMORY_HTTP_TCP_RECEIVE_MAX_BYTES; +} + static esp_err_t upload_handler_sync(httpd_req_t *request, uint32_t access_epoch) { size_t query_length = httpd_req_get_url_query_len(request); @@ -876,6 +891,7 @@ static esp_err_t upload_handler_sync(httpd_req_t *request, uint32_t access_epoch const bool local_control_start = local_upload_lease_take(upload_id); #endif + const size_t queued_bytes = queued_request_bytes(request); #if JETKVM_HTTP_UPLOAD_INTERNAL_DIRECT const jetkvm_memory_policy_request_t memory_request = { /* The single payload is a real Internal/DMA allocation. Keep charging @@ -890,6 +906,7 @@ static esp_err_t upload_handler_sync(httpd_req_t *request, uint32_t access_epoch .psram_bytes = JETKVM_MEMORY_HTTP_TCP_RECEIVE_MAX_BYTES + UPLOAD_WRITER_STACK_SIZE, .psram_largest_block = UPLOAD_WRITER_STACK_SIZE, + .psram_allocated_bytes = queued_bytes, .storage_ingress_bytes = JETKVM_MEMORY_HTTP_INGRESS_MAX_BYTES, }; #else @@ -907,6 +924,7 @@ static esp_err_t upload_handler_sync(httpd_req_t *request, uint32_t access_epoch UPLOAD_BUFFER_COUNT * UPLOAD_BUFFER_SIZE + UPLOAD_WRITER_STACK_SIZE, .psram_largest_block = UPLOAD_BUFFER_SIZE, + .psram_allocated_bytes = queued_bytes, .storage_ingress_bytes = JETKVM_MEMORY_HTTP_INGRESS_MAX_BYTES, }; @@ -930,6 +948,7 @@ static esp_err_t upload_handler_sync(httpd_req_t *request, uint32_t access_epoch UPLOAD_BUFFER_COUNT * UPLOAD_BUFFER_SIZE + UPLOAD_WRITER_STACK_SIZE, .psram_largest_block = UPLOAD_ALLOCATION_SIZE, + .psram_allocated_bytes = queued_bytes, .storage_ingress_bytes = JETKVM_MEMORY_HTTP_INGRESS_MAX_BYTES, }; #endif diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 4690e2e1..5fbdb617 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -141,6 +141,8 @@ CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=256 CONFIG_LWIP_UDP_RECVMBOX_SIZE=32 CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=0 CONFIG_LWIP_TCP_SACK_OUT=y +# FIONREAD: the HTTP upload admission reads how much of its body is queued. +CONFIG_LWIP_SO_RCVBUF=y # A connection sends at most one send buffer per round trip. Payloads are in # PSRAM and only while unacknowledged. CONFIG_LWIP_TCP_SND_BUF_DEFAULT=23040 From e91ae4a789e61758ca72cb3186b824c755e924de Mon Sep 17 00:00:00 2001 From: Adam Shiervani Date: Fri, 4 Dec 2026 13:56:23 +0100 Subject: [PATCH 3/3] Test an upload whose body is queued when it is admitted A request whose head is not complete holds the HTTP server task, so the upload's whole body and the bytes of up to 4 more connections wait in lwIP when the server reads the upload's head. Those connections take free PSRAM to a set margin over the upload's admission point: 128 KiB over it, the upload with 256 KiB queued is admitted; 128 KiB under it, an upload is refused. --- .../tests/upload_queued_body.test.mjs | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 tools/integration/tests/upload_queued_body.test.mjs diff --git a/tools/integration/tests/upload_queued_body.test.mjs b/tools/integration/tests/upload_queued_body.test.mjs new file mode 100644 index 00000000..55f254a7 --- /dev/null +++ b/tools/integration/tests/upload_queued_body.test.mjs @@ -0,0 +1,152 @@ +import assert from 'node:assert/strict'; +import net from 'node:net'; +import { test } from 'node:test'; +import { seededBytes, sha256 } from '../../combined_load/runner/content.mjs'; +import { connect } from '../lib/mini.mjs'; + +const KIB = 1024; +// The upload's PSRAM request besides its TCP window: the writer task's stack. +const WRITER_STACK = 6144; +// PSRAM per byte that waits in lwIP's receive queue (frame headers, heap +// blocks, the pbuf around each frame), measured on an Ethernet Mini. +const QUEUED_FOOTPRINT = 1.1; +// lwIP queues at most 256 frames of a connection that is not read +// (CONFIG_LWIP_TCP_RECVMBOX_SIZE), and the HTTP server's listen backlog has +// room for 5 connections that it has not accepted: the upload and 4 more. +const HELD_BYTES_MAX = 336 * KIB; +const HELD_CONNECTIONS = 4; +// The server closes a connection whose request head takes longer than 5 s. +const STALL_MS = 1500; +const STEADY_MS = 2000; +const STEADY_BYTES = 16 * KIB; + +const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); + +function open({ hostname, port }) { + return new Promise((resolve, reject) => { + const socket = net.connect(Number(port) || 80, hostname, () => resolve(socket)); + socket.once('error', reject); + }); +} + +function response(socket) { + return new Promise((resolve, reject) => { + let text = ''; + socket.on('data', chunk => { + text += chunk; + const head = text.indexOf('\r\n\r\n'); + const length = /content-length: *(\d+)/i.exec(text)?.[1]; + if (head >= 0 && length !== undefined && text.length >= head + 4 + Number(length)) { + socket.destroy(); + resolve({ status: Number(/^HTTP\/1\.1 (\d+)/.exec(text)?.[1]), body: text.slice(head + 4) }); + } + }); + socket.on('error', reject); + socket.on('close', () => reject(new Error(`the connection closed after ${JSON.stringify(text.slice(0, 80))}`))); + }); +} + +// The stats once free PSRAM has changed by less than STEADY_BYTES in +// STEADY_MS: the margin that the test builds must hold until the admission. +async function steadyStats(mini) { + const read = async () => (await fetch(new URL('/webrtc/stats', mini.url), { signal: AbortSignal.timeout(10_000) })).json(); + let last = await read(); + for (const end = Date.now() + 60_000; Date.now() < end;) { + await wait(STEADY_MS); + const now = await read(); + if (Math.abs(now.psramFree - last.psramFree) < STEADY_BYTES) return now; + last = now; + } + throw new Error('free PSRAM did not hold still for 60 s'); +} + +// POSTs `data` for the upload while the HTTP server task waits for the rest +// of another request's head, so that the whole body is queued in lwIP when +// the server reads the upload's head. Connections that the server has not +// accepted yet hold more queued bytes, so that free PSRAM less the upload's +// request is `margin` at that moment. The server accepts in arrival order, +// so it takes the upload before them. +async function uploadQueued(t, mini, { filename, margin, data }) { + const address = new URL(mini.url); + if (address.protocol !== 'http:') { + t.skip('the test sends its requests over plain sockets and needs the HTTP address of the Mini'); + return null; + } + const { dataChannel: uploadId } = await mini.rpc('startStorageFileUpload', { filename, size: data.length, sha256: sha256(data) }); + const stats = await steadyStats(mini); + const budget = stats.memoryBudget; + const window = budget.httpTcpReceiveMaximumBytes; + const found = stats.psramFree - budget.psramAdmissionFloor - budget.reservedPsramBytes - window - WRITER_STACK; + const held = Math.round((found - margin) / QUEUED_FOOTPRINT); + const perConnection = Math.min(HELD_BYTES_MAX, window); + t.diagnostic(`free PSRAM ${stats.psramFree} B, ${found} B over the upload's admission point; ${held} B held in other connections`); + if (data.length > perConnection || held < 0 || held > HELD_CONNECTIONS * perConnection) { + t.skip(`the Mini cannot be brought to ${margin} B over the upload's admission point with ${HELD_CONNECTIONS} connections of ${perConnection} B`); + return null; + } + const others = []; + const stall = await open(address); + try { + return await stallAndUpload(address, stall, others, { uploadId, held, perConnection, data }); + } finally { + stall.destroy(); + for (const socket of others) socket.resetAndDestroy(); + } +} + +async function stallAndUpload(address, stall, others, { uploadId, held, perConnection, data }) { + const { host } = address; + const stalled = response(stall); + stall.write(`GET /device/status HTTP/1.1\r\nHost: ${host}\r\n`); + await wait(300); + const upload = await open(address); + const answer = response(upload); + upload.write(Buffer.concat([Buffer.from(`POST /storage/upload?uploadId=${encodeURIComponent(uploadId)} HTTP/1.1\r\n` + + `Host: ${host}\r\nContent-Type: application/octet-stream\r\nContent-Length: ${data.length}\r\n\r\n`), data])); + const count = Math.ceil(held / perConnection); + for (let i = 0; i < count; ++i) { + const socket = await open(address); + socket.on('error', () => undefined); + socket.write(Buffer.alloc(Math.ceil(held / count), 0x78)); + others.push(socket); + } + await wait(STALL_MS); + stall.write('\r\n'); + assert.equal((await stalled).status, 200, 'the request that held the server is answered'); + return answer; +} + +async function bench(t) { + const mini = await connect(); + const filename = `integration-upload-queued-${Date.now()}.img`; + t.after(async () => { + try { + for (const name of [filename, `${filename}.incomplete`]) { + await mini.rpc('deleteStorageFile', { filename: name }).catch(e => { + if (!/file does not exist/.test(e.message)) throw e; + }); + } + } finally { + await mini.close(); + } + }); + return { mini, filename }; +} + +test('an upload whose body reached the Mini before its head was read is admitted when it fits', { timeout: 120_000 }, async t => { + const { mini, filename } = await bench(t); + const data = seededBytes(1, 256 * KIB); + const result = await uploadQueued(t, mini, { filename, margin: 128 * KIB, data }); + if (!result) return; + assert.equal(result.status, 200, `the upload: ${result.body}`); + const file = (await mini.rpc('listStorageFiles')).files.find(found => found.filename === filename); + assert.equal(file?.size, data.length, 'the card has the whole file'); +}); + +test('an upload that would take free PSRAM under the admission floor is refused', { timeout: 120_000 }, async t => { + const { mini, filename } = await bench(t); + const result = await uploadQueued(t, mini, { filename, margin: -128 * KIB, data: seededBytes(2, 64 * KIB) }); + if (!result) return; + assert.equal(result.status, 503); + assert.match(result.body, /Insufficient memory headroom/); +});