Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
6 changes: 4 additions & 2 deletions components/jetkvm_memory_policy/jetkvm_memory_policy.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions components/jetkvm_memory_policy/tests/run_static_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
166 changes: 166 additions & 0 deletions components/jetkvm_memory_policy/tests/test_queued_body_admission.py
Original file line number Diff line number Diff line change
@@ -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 <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
'''
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')
19 changes: 19 additions & 0 deletions components/jetkvm_virtual_media_http/jetkvm_virtual_media_http.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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,
};
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions sdkconfig.defaults
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading