New features: - get_time_us() in lib/u_async.c/h for µs-precision timing - Burst measurement (ETCP_SECTION_MEAS_TS 0x07, MEAS_RESP 0x08, FILLER 0x09) - 12 MTU packets sent at line rate, receiver measures inter-packet gaps - Burst triggered when link saturated + min 500ms interval - Result: measured BW -> bandwidth for shaper, burst_target_bdp for window cap - 3-phase adaptive inflight in link_stats_timer_cb: - Slow start: windows doubles each RTT, exits on loss/RTT spike/threshold - Congestion avoidance: additive increase, proportional RTT shrink, multiplicative loss shrink - Burst target cap: inflight_lim <= burst_target_bdp * 1.1 - Dynamic optimal_inflight = sum(link->inflight_lim_bytes), recalculated on change - Adaptive win_timebase = rtt/2 (was hardcoded 10ms) Fixes: - dummynet.c: shaper formula fixed (80000 -> 80) - dummynet.c: queue_data_put call fixed (3 args -> 2) - etcp.c: SIZE ERROR format string (missing log_name argument) - etcp_request_pkt: FILLER leaves room for PAYLOAD overhead Tests: - test_etcp_congestion.c: single-threaded, 5-phase BW/delay/loss test - sender + receiver + dummynet in one uasync - CSV metrics output every 100ms - All 29 existing tests pass
127 lines
5.4 KiB
C
127 lines
5.4 KiB
C
// uasync.h
|
||
|
||
// модуль асинхронных операций. добавляем сокеты и таймауты и mainloop их обслуживает.
|
||
|
||
#ifndef UASYNC_H
|
||
#define UASYNC_H
|
||
|
||
#include "platform_compat.h"
|
||
#include <stddef.h>
|
||
#include "timeout_heap.h"
|
||
#include "socket_compat.h"
|
||
|
||
typedef void (*timeout_callback_t)(void* user_arg);// передаёт user_arg из uasync_set_timeout
|
||
typedef void (*socket_callback_t)(int fd, void* user_arg);// передаёт user_arg из uasync_add_socket (for pipe/file)
|
||
typedef void (*socket_t_callback_t)(socket_t sock, void* user_arg);// передаёт user_arg из uasync_add_socket_t (for sockets)
|
||
// user_arg полезен если нужно передать управляющую структуру. Ее можно выделить в памяти и в ней хранить всё что надо. т.е. при set_timeout передаём и получаем ее в callback-е
|
||
|
||
|
||
// Error type
|
||
typedef int err_t;
|
||
#define ERR_OK 0
|
||
#define ERR_FAIL -1
|
||
|
||
// Socket node types
|
||
#define SOCKET_NODE_TYPE_FD 0 // Regular file descriptor (pipe, file)
|
||
#define SOCKET_NODE_TYPE_SOCK 1 // Socket (socket_t)
|
||
|
||
typedef void (*uasync_post_callback_t)(void* user_arg);
|
||
|
||
#include "memory_pool.h"
|
||
|
||
struct timeout_node; // Forward declaration
|
||
|
||
struct posted_task {
|
||
uasync_post_callback_t callback;
|
||
void* arg;
|
||
struct posted_task* next;
|
||
};
|
||
|
||
// Uasync instance structure
|
||
struct UASYNC {
|
||
struct memory_pool* timeout_pool; // Pool for timeout_node allocation
|
||
struct timeout_node* immediate_queue_head; // FIFO queue for immediate execution
|
||
struct timeout_node* immediate_queue_tail;
|
||
TimeoutHeap* timeout_heap; // Heap for timeout management
|
||
struct socket_array* sockets; // Array-based socket management
|
||
// Debug counters for memory allocation tracking
|
||
size_t timer_alloc_count;
|
||
size_t timer_free_count;
|
||
size_t socket_alloc_count;
|
||
size_t socket_free_count;
|
||
// Wakeup pipe for interrupting poll
|
||
int wakeup_pipe[2]; // [0] read, [1] write
|
||
int wakeup_initialized;
|
||
// Cached pollfd array for optimized poll operations (fallback for non-Linux)
|
||
struct pollfd* poll_fds; // Pre-allocated pollfd array
|
||
int poll_fds_capacity; // Current capacity of poll_fds
|
||
int poll_fds_count; // Number of valid entries in poll_fds
|
||
int poll_fds_dirty; // 1 if poll_fds needs rebuild
|
||
// Epoll support (Linux only)
|
||
int epoll_fd; // epoll file descriptor (-1 if not using epoll)
|
||
int use_epoll; // 1 if using epoll, 0 if using poll
|
||
struct posted_task* posted_tasks_head;
|
||
struct posted_task* posted_tasks_tail;
|
||
|
||
#ifdef _WIN32
|
||
CRITICAL_SECTION posted_lock;
|
||
#else
|
||
pthread_mutex_t posted_lock;
|
||
#endif
|
||
};
|
||
|
||
// Type definitions
|
||
typedef struct UASYNC uasync_t;
|
||
typedef struct UASYNC UASYNC_t;
|
||
|
||
// Instance API - основной API для работы с uasync
|
||
struct UASYNC* uasync_create(void);
|
||
void uasync_destroy(struct UASYNC* ua, int close_fds);
|
||
|
||
// текущее время (timebase 0.1ms)
|
||
uint64_t get_time_tb(void);
|
||
// текущее время в микросекундах (для burst-измерений)
|
||
uint64_t get_time_us(void);
|
||
|
||
// Timeouts, timebase = 0.1 mS
|
||
void* uasync_set_timeout(struct UASYNC* ua, int timeout_tb, void* user_arg, timeout_callback_t callback, const char* name);
|
||
err_t uasync_cancel_timeout(struct UASYNC* ua, void* t_id);
|
||
|
||
// Immediate execution in next mainloop (FIFO order)
|
||
void* uasync_call_soon(struct UASYNC* ua, void* user_arg, timeout_callback_t callback);
|
||
err_t uasync_call_soon_cancel(struct UASYNC* ua, void* t_id);
|
||
|
||
// Sockets - for regular file descriptors (pipe, file)
|
||
void* uasync_add_socket(struct UASYNC* ua, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_arg);
|
||
// Sockets - for socket_t (cross-platform sockets)
|
||
void* uasync_add_socket_t(struct UASYNC* ua, socket_t sock, socket_t_callback_t read_cbk, socket_t_callback_t write_cbk, socket_t_callback_t except_cbk, void* user_arg);
|
||
err_t uasync_remove_socket(struct UASYNC* ua, void* s_id);
|
||
err_t uasync_remove_socket_t(struct UASYNC* ua, socket_t sock);
|
||
|
||
// Single iteration of event loop with timeout (timebase units)
|
||
void uasync_poll(struct UASYNC* ua, int timeout_tb);
|
||
|
||
// Mainloop (бесконечный цикл, __noreturn)
|
||
void uasync_mainloop(struct UASYNC* ua);
|
||
|
||
// Debug statistics
|
||
void uasync_get_stats(struct UASYNC* ua, size_t* timer_alloc, size_t* timer_free, size_t* socket_alloc, size_t* socket_free);
|
||
|
||
// Lookup socket by file descriptor - returns current pointer even after realloc
|
||
int uasync_lookup_socket(struct UASYNC* ua, int fd, void** socket_id);
|
||
|
||
// Print all resources (timers, sockets) for debugging
|
||
void uasync_print_resources(struct UASYNC* ua, const char* prefix);
|
||
|
||
// Wakeup mechanism for interrupting poll
|
||
int uasync_wakeup(struct UASYNC* ua);
|
||
int uasync_get_wakeup_fd(struct UASYNC* ua); // returns write fd for wakeup pipe (for signal handlers)
|
||
|
||
// сообщить async (из другого thread) чтобы он вызвал callback с аргументом
|
||
void uasync_post(struct UASYNC* ua, uasync_post_callback_t callback, void* user_arg);
|
||
|
||
// синхронизация памяти (для доступности из других потоков)
|
||
void uasync_memsync(struct UASYNC* ua);
|
||
|
||
#endif // UASYNC_H
|