ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
buffer.c
Go to the documentation of this file.
1#include <ascii-chat/buffer.h>
2#include <ascii-chat/common.h>
5#include <libplatform/atomic.h>
6#include <libplatform/lifecycle.h>
7#include <libplatform/mutex.h>
8#include <stdint.h>
9#include <string.h>
10
11#if defined(__has_feature)
12#if __has_feature(address_sanitizer)
13#include <sanitizer/asan_interface.h>
14#define BUFFER_POISON(p, n) __asan_poison_memory_region((p), (n))
15#define BUFFER_UNPOISON(p, n) __asan_unpoison_memory_region((p), (n))
16#endif
17#endif
18#ifndef BUFFER_POISON
19#define BUFFER_POISON(p, n) ((void)0)
20#define BUFFER_UNPOISON(p, n) ((void)0)
21#endif
22
23/* Power-of-two bins through 4 MiB; larger payloads are budgeted but not cached.
24 */
25#define BUFFER_BINS 17
26#define BUFFER_MIN_CAPACITY 64u
27#define BUFFER_MAX_CACHED ((size_t)4 * 1024 * 1024)
28
44
62
63static atomic_t process_bytes;
64static buffer_domain_t *default_domain;
65static buffer_domain_t *control_domain;
66static lifecycle_t default_lifecycle = LIFECYCLE_INIT;
67
68static bool process_reserve(size_t bytes, bool control) {
69 uint64_t current = atomic_load_u64(&process_bytes);
70 size_t limit = control ? BUFFER_PROCESS_LIMIT
72 while (current <= limit && bytes <= limit - current) {
73 if (atomic_cas_u64(&process_bytes, &current, current + bytes))
74 return true;
75 }
76 return false;
77}
78
80 return (size_t)atomic_load_u64(&process_bytes);
81}
82
84 if (!budget || budget->bytes || !bytes)
86 "Expected an empty buffer budget lease");
87 if (!process_reserve(bytes, false))
88 return SET_ERRNO(
90 "Process buffer budget exhausted reserving platform storage");
91 budget->bytes = bytes;
92 return ASCIICHAT_OK;
93}
94
96 if (budget && budget->bytes) {
97 atomic_fetch_sub_u64(&process_bytes, budget->bytes);
98 budget->bytes = 0;
99 }
100}
101
102/* The back pointer lives immediately before the aligned payload. It is never
103 * inspected for foreign allocations; those use their original deallocator. */
104static buffer_header_t *header(const void *data) {
105 return data ? ((buffer_header_t *const *)data)[-1] : NULL;
106}
107
108static void dispose(buffer_domain_t *domain, buffer_header_t *node) {
109 domain->stats.reserved_bytes -= node->charge;
110 atomic_fetch_sub_u64(&process_bytes, node->charge);
111 void *allocation = node->allocation;
112 SAFE_FREE(allocation);
113}
114
115static void trim_locked(buffer_domain_t *domain, bool all) {
116 uint64_t now = time_get_ns();
117 for (unsigned i = 0; i < BUFFER_BINS; i++) {
118 buffer_header_t **link = &domain->bins[i];
119 while (*link) {
120 buffer_header_t *node = *link;
121 if (all || now - node->returned_at >= domain->config.idle_ns) {
122 *link = node->next;
123 domain->stats.cached_bytes -= node->charge;
124 dispose(domain, node);
125 } else {
126 link = &node->next;
127 }
128 }
129 }
130}
131
134 if (!out)
135 return SET_ERRNO(ERROR_INVALID_PARAM, "Buffer domain output is NULL");
136 *out = NULL;
137 buffer_domain_config_t defaults = {BUFFER_DOMAIN_LIMIT, 32 * 1024 * 1024,
138 5000000000ULL, false};
139 if (!process_reserve(sizeof(buffer_domain_t), config && config->control))
140 return SET_ERRNO(ERROR_MEMORY,
141 "Process buffer budget exhausted creating domain");
142 buffer_domain_t *domain = ALLOC_CALLOC(1, sizeof(*domain));
143 if (!domain) {
144 atomic_fetch_sub_u64(&process_bytes, sizeof(*domain));
145 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate buffer domain");
146 }
147 domain->config = config ? *config : defaults;
148 if (!domain->config.limit_bytes)
150 if (mutex_init(&domain->mutex, domain->config.control
151 ? "reserved_control_buffer_pool"
152 : "shared_media_buffer_pool") != 0) {
153 atomic_fetch_sub_u64(&process_bytes, sizeof(*domain));
154 SAFE_FREE(domain);
155 return SET_ERRNO(ERROR_THREAD, "Cannot initialize buffer domain mutex");
156 }
157 *out = domain;
158 return ASCIICHAT_OK;
159}
160
161static void domain_dispose(buffer_domain_t *domain) {
162 mutex_destroy(&domain->mutex);
163 atomic_fetch_sub_u64(&process_bytes, sizeof(*domain));
164 SAFE_FREE(domain);
165}
166
168 if (!slot || !*slot)
169 return;
170 buffer_domain_t *domain = *slot;
171 *slot = NULL;
172 mutex_lock(&domain->mutex);
173 domain->closing = true;
174 trim_locked(domain, true);
175 bool done = domain->stats.outstanding == 0;
176 mutex_unlock(&domain->mutex);
177 if (done)
178 domain_dispose(domain);
179}
180
182 if (!domain)
183 return;
184 mutex_lock(&domain->mutex);
185 trim_locked(domain, false);
186 mutex_unlock(&domain->mutex);
187}
188
190 size_t alignment, void **out) {
191 if (!out)
192 return SET_ERRNO(ERROR_INVALID_PARAM, "Buffer output is NULL");
193 *out = NULL;
194 if (!alignment)
195 alignment = BUFFER_DEFAULT_ALIGNMENT;
196 if (alignment < sizeof(void *) || (alignment & (alignment - 1)) ||
197 alignment > 4096)
198 return SET_ERRNO(ERROR_INVALID_PARAM, "Buffer alignment must be a power of "
199 "two between pointer size and 4096");
200 if (!domain)
201 domain = buffer_default_domain();
202 if (!domain)
203 return SET_ERRNO(ERROR_INVALID_STATE, "Buffer system is unavailable");
204
205 size_t capacity = BUFFER_MIN_CAPACITY;
206 unsigned bin = 0;
207 while (capacity < size && bin + 1 < BUFFER_BINS) {
208 capacity *= 2;
209 bin++;
210 }
211 if (capacity < size)
212 capacity = size;
213 size_t overhead =
214 sizeof(buffer_header_t) + sizeof(buffer_header_t *) + alignment - 1;
215 if (capacity > SIZE_MAX - overhead)
216 return SET_ERRNO(ERROR_INVALID_PARAM, "Buffer capacity overflow");
217 size_t charge = capacity + overhead;
218
219 mutex_lock(&domain->mutex);
220 if (domain->closing) {
221 mutex_unlock(&domain->mutex);
222 return SET_ERRNO(ERROR_INVALID_STATE, "Buffer domain is closing");
223 }
224 buffer_header_t **link = &domain->bins[bin];
225 buffer_header_t *node = NULL;
226 if (capacity <= BUFFER_MAX_CACHED) {
227 while (*link) {
228 if ((*link)->alignment >= alignment) {
229 node = *link;
230 *link = node->next;
231 domain->stats.cached_bytes -= node->charge;
232 domain->stats.hits++;
233 break;
234 }
235 link = &(*link)->next;
236 }
237 }
238 if (!node) {
239 if (charge > domain->config.limit_bytes ||
240 domain->stats.reserved_bytes > domain->config.limit_bytes - charge) {
241 /* A miss may reclaim idle capacity, but a release never scans a pool. */
242 trim_locked(domain, true);
243 }
244 bool fits =
245 charge <= domain->config.limit_bytes &&
246 domain->stats.reserved_bytes <= domain->config.limit_bytes - charge;
247 bool reserved = fits && process_reserve(charge, domain->config.control);
248 if (fits && !reserved && domain->stats.cached_bytes) {
249 trim_locked(domain, true);
250 reserved = process_reserve(charge, domain->config.control);
251 }
252 if (!reserved) {
253 domain->stats.failures++;
254 mutex_unlock(&domain->mutex);
255 return SET_ERRNO(ERROR_MEMORY,
256 "Buffer budget exhausted requesting %zu bytes", size);
257 }
258 node = ALLOC_MALLOC(charge);
259 if (!node) {
260 atomic_fetch_sub_u64(&process_bytes, charge);
261 domain->stats.failures++;
262 mutex_unlock(&domain->mutex);
263 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate %zu buffer bytes",
264 charge);
265 }
266 memset(node, 0, sizeof(*node));
267 node->allocation = node;
268 uintptr_t start = (uintptr_t)(node + 1) + sizeof(buffer_header_t *);
269 node->data =
270 (void *)((start + alignment - 1) & ~(uintptr_t)(alignment - 1));
271 ((buffer_header_t **)node->data)[-1] = node;
272 node->domain = domain;
273 node->capacity = capacity;
274 node->charge = charge;
275 node->alignment = alignment;
276 node->bin = bin;
277 domain->stats.reserved_bytes += charge;
278 domain->stats.allocations++;
279 }
280 node->next = NULL;
281 BUFFER_UNPOISON(node->data, node->capacity);
282 atomic_store_u64(&node->references, 1);
283 node->length = size;
284 domain->stats.outstanding++;
285 domain->stats.live_bytes += node->charge;
286 domain->stats.requested_bytes += size;
287 if (domain->stats.reserved_bytes > domain->stats.peak_bytes)
288 domain->stats.peak_bytes = domain->stats.reserved_bytes;
289 *out = node->data;
290 mutex_unlock(&domain->mutex);
291 return ASCIICHAT_OK;
292}
293
294void *buffer_alloc(buffer_domain_t *domain, size_t size) {
295 void *data = NULL;
296 (void)buffer_acquire(domain, size, BUFFER_DEFAULT_ALIGNMENT, &data);
297 return data;
298}
299
300size_t buffer_capacity(const void *data) {
301 return data ? header(data)->capacity : 0;
302}
303size_t buffer_size(const void *data) { return data ? header(data)->length : 0; }
304
305asciichat_error_t buffer_set_size(void *data, size_t size) {
306 if (!data || size > buffer_capacity(data))
307 return SET_ERRNO(ERROR_INVALID_PARAM, "Buffer length exceeds capacity");
308 buffer_header_t *node = header(data);
309 buffer_domain_t *domain = node->domain;
310 mutex_lock(&domain->mutex);
311 if (atomic_load_u64(&node->references) != 1) {
312 mutex_unlock(&domain->mutex);
313 return SET_ERRNO(ERROR_INVALID_STATE, "Cannot resize shared buffer");
314 }
315 domain->stats.requested_bytes -= node->length;
316 node->length = size;
317 domain->stats.requested_bytes += size;
318 mutex_unlock(&domain->mutex);
319 return ASCIICHAT_OK;
320}
321
322const void *buffer_share(const void *data) {
323 if (!data)
324 return NULL;
325 buffer_header_t *node = header(data);
326 uint64_t references = atomic_load_u64(&node->references);
327 while (references && references != SIZE_MAX) {
328 if (atomic_cas_u64(&node->references, &references, references + 1))
329 return data;
330 }
331 SET_ERRNO(ERROR_INVALID_STATE, "Invalid buffer reference count");
332 return NULL;
333}
334
335bool buffer_is_unique(const void *data) {
336 return data && atomic_load_u64(&header(data)->references) == 1;
337}
338
339void buffer_unref(const void *data) {
340 if (!data)
341 return;
342 buffer_header_t *node = header(data);
343 buffer_domain_t *domain = node->domain;
344 uint64_t references = atomic_load_u64(&node->references);
345 while (references &&
346 !atomic_cas_u64(&node->references, &references, references - 1)) {
347 }
348 if (!references) {
349 SET_ERRNO(ERROR_INVALID_STATE, "Buffer has already been released");
350 return;
351 }
352 if (references > 1) {
353 return;
354 }
355 mutex_lock(&domain->mutex);
356 domain->stats.outstanding--;
357 domain->stats.live_bytes -= node->charge;
358 domain->stats.requested_bytes -= node->length;
359 bool done = domain->closing && !domain->stats.outstanding;
360 if (!domain->closing && node->capacity <= BUFFER_MAX_CACHED &&
361 node->charge <= domain->config.cache_bytes &&
362 domain->stats.cached_bytes <= domain->config.cache_bytes - node->charge) {
363 node->returned_at = time_get_ns();
364 BUFFER_POISON(node->data, node->capacity);
365 node->next = domain->bins[node->bin];
366 domain->bins[node->bin] = node;
367 domain->stats.cached_bytes += node->charge;
368 } else {
369 dispose(domain, node);
370 }
371 mutex_unlock(&domain->mutex);
372 if (done)
373 domain_dispose(domain);
374}
375
377 buffer_domain_t *domain,
378 size_t capacity) {
379 if (!workspace)
380 return SET_ERRNO(ERROR_INVALID_PARAM, "Workspace is NULL");
381 if (workspace->length > buffer_capacity(workspace->data))
383 "Workspace length exceeds its storage");
384 if (capacity <= buffer_capacity(workspace->data))
385 return ASCIICHAT_OK;
386 void *next = NULL;
387 asciichat_error_t result =
388 buffer_acquire(domain, capacity, BUFFER_DEFAULT_ALIGNMENT, &next);
389 if (result != ASCIICHAT_OK)
390 return result;
391 if (workspace->data && workspace->length)
392 memcpy(next, workspace->data, workspace->length);
393 buffer_release(workspace->data);
394 workspace->data = next;
395 return ASCIICHAT_OK;
396}
397
399 if (workspace) {
400 buffer_release(workspace->data);
401 workspace->length = 0;
402 }
403}
404
406 if (!out)
407 return;
408 memset(out, 0, sizeof(*out));
409 if (!domain)
410 return;
411 mutex_lock(&domain->mutex);
412 *out = domain->stats;
413 mutex_unlock(&domain->mutex);
414}
415
416void buffer_domain_log_stats(buffer_domain_t *domain, const char *name) {
417 buffer_stats_t stats;
418 buffer_domain_stats(domain, &stats);
419 log_debug("Buffers %s: reserved=%zu live=%zu requested=%zu cached=%zu "
420 "outstanding=%zu hits=%llu failures=%llu",
421 name ? name : "default", stats.reserved_bytes, stats.live_bytes,
422 stats.requested_bytes, stats.cached_bytes, stats.outstanding,
423 (unsigned long long)stats.hits, (unsigned long long)stats.failures);
424}
425
427 for (;;) {
428 if (lifecycle_init_once(&default_lifecycle))
429 break;
430 if (lifecycle_is_initialized(&default_lifecycle) ||
431 lifecycle_is_dead(&default_lifecycle))
432 return;
433 // Another caller must finish publishing both domains before allocations use
434 // them.
435 platform_sleep_us(100);
436 }
437 if (buffer_domain_create(NULL, &default_domain) != ASCIICHAT_OK) {
438 lifecycle_init_abort(&default_lifecycle);
439 return;
440 }
441 buffer_domain_config_t control = {BUFFER_CONTROL_RESERVE, 1024 * 1024,
442 5000000000ULL, true};
443 if (buffer_domain_create(&control, &control_domain) != ASCIICHAT_OK) {
444 buffer_domain_close(&default_domain);
445 lifecycle_init_abort(&default_lifecycle);
446 return;
447 }
448 NAMED_REGISTER_ATOMIC(&process_bytes, "buffer.process_reserved_bytes", NULL);
449 lifecycle_init_commit(&default_lifecycle);
450}
451
454 return default_domain;
455}
456
458 if (lifecycle_shutdown(&default_lifecycle)) {
459 NAMED_UNREGISTER(&process_bytes);
460 buffer_domain_close(&default_domain);
461 buffer_domain_close(&control_domain);
462 }
463}
464
467 return control_domain;
468}
#define SET_ERRNO(code,...)
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
uint64_t atomic_fetch_sub_u64(atomic_t *a, uint64_t delta)
Atomically subtract from a uint64_t and return the previous value.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
size_t buffer_capacity(const void *data)
Definition buffer.c:300
bool buffer_is_unique(const void *data)
Definition buffer.c:335
#define BUFFER_MIN_CAPACITY
Definition buffer.c:26
void buffer_domain_log_stats(buffer_domain_t *domain, const char *name)
Definition buffer.c:416
asciichat_error_t buffer_workspace_reserve(buffer_workspace_t *workspace, buffer_domain_t *domain, size_t capacity)
Definition buffer.c:376
void buffer_domain_stats(buffer_domain_t *domain, buffer_stats_t *out)
Definition buffer.c:405
void buffer_system_cleanup(void)
Definition buffer.c:457
void buffer_domain_close(buffer_domain_t **slot)
Definition buffer.c:167
asciichat_error_t buffer_set_size(void *data, size_t size)
Definition buffer.c:305
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:294
#define BUFFER_POISON(p, n)
Definition buffer.c:19
void buffer_budget_release(buffer_budget_t *budget)
Definition buffer.c:95
buffer_domain_t * buffer_default_domain(void)
Definition buffer.c:452
size_t buffer_process_reserved(void)
Definition buffer.c:79
void buffer_domain_trim(buffer_domain_t *domain)
Definition buffer.c:181
#define BUFFER_BINS
Definition buffer.c:25
#define BUFFER_MAX_CACHED
Definition buffer.c:27
void buffer_unref(const void *data)
Definition buffer.c:339
struct buffer_header buffer_header_t
void buffer_workspace_destroy(buffer_workspace_t *workspace)
Definition buffer.c:398
buffer_domain_t * buffer_control_domain(void)
Definition buffer.c:465
#define BUFFER_UNPOISON(p, n)
Definition buffer.c:20
asciichat_error_t buffer_domain_create(const buffer_domain_config_t *config, buffer_domain_t **out)
Definition buffer.c:132
void buffer_system_init(void)
Definition buffer.c:426
const void * buffer_share(const void *data)
Definition buffer.c:322
asciichat_error_t buffer_budget_reserve(buffer_budget_t *budget, size_t bytes)
Definition buffer.c:83
asciichat_error_t buffer_acquire(buffer_domain_t *domain, size_t size, size_t alignment, void **out)
Definition buffer.c:189
#define BUFFER_DOMAIN_LIMIT
Definition buffer.h:33
struct buffer_domain buffer_domain_t
Definition buffer.h:28
#define BUFFER_DEFAULT_ALIGNMENT
Definition buffer.h:30
#define buffer_release(data)
Definition buffer.h:108
#define BUFFER_PROCESS_LIMIT
Definition buffer.h:31
#define BUFFER_CONTROL_RESERVE
Definition buffer.h:32
Named object registry for debugging — log identifiable resource names.
int buffer_size
Size of circular buffer.
Definition grep.c:69
#define SAFE_FREE(ptr)
#define ALLOC_CALLOC(count, size)
#define ALLOC_MALLOC(size)
unsigned long long uint64_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
⚙️ Common definitions, error codes, macros, and types shared throughout the application
static bool size_t gotel_query_t * out
Definition queries.h:10
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
Owns the temporary storage used by buffer budget. The data pointers and size or cursor fields describ...
Definition budget.h:15
size_t bytes
Definition budget.h:16
The useful part of buffer header is in next, domain, allocation, data: together they describe what is...
Definition buffer.c:55
buffer_stats_t stats
Definition buffer.c:58
bool closing
Definition buffer.c:60
mutex_t mutex
Definition buffer.c:56
buffer_header_t * bins[17]
Definition buffer.c:59
buffer_domain_config_t config
Definition buffer.c:57
size_t capacity
Definition buffer.c:36
void * allocation
Definition buffer.c:34
size_t charge
Definition buffer.c:38
struct buffer_header * next
Definition buffer.c:32
uint64_t returned_at
Definition buffer.c:41
buffer_domain_t * domain
Definition buffer.c:33
unsigned bin
Definition buffer.c:42
size_t alignment
Definition buffer.c:39
size_t length
Definition buffer.c:37
void * data
Definition buffer.c:35
atomic_t references
Definition buffer.c:40
size_t live_bytes
Definition buffer.h:47
uint64_t hits
Definition buffer.h:52
size_t outstanding
Definition buffer.h:51
size_t reserved_bytes
Definition buffer.h:46
size_t peak_bytes
Definition buffer.h:50
size_t requested_bytes
Definition buffer.h:48
size_t cached_bytes
Definition buffer.h:49
uint64_t failures
Definition buffer.h:54
uint64_t allocations
Definition buffer.h:53
Owns the temporary storage used by buffer workspace. The data pointers and size or cursor fields desc...
Definition buffer.h:122
⏱️ High-precision timing utilities using sokol_time.h and uthash