From 5f4ff10bd7064d7aae86607a8c4ec5ae4faef1da Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Fri, 4 Dec 2026 20:12:12 +0800 Subject: [PATCH 1/2] perf(ipc): restore parallel pipe transfers and target wakeups --- Documentation/core-api/execution.rst | 26 ++-- fs/notify/watch.c | 33 ++++- include/reliefnt/fsnotify.h | 7 ++ include/reliefnt/syscall_internal.h | 7 +- kernel/sched/core.c | 29 ++++- kernel/sched/internal.h | 7 ++ kernel/sched/wait.c | 8 +- kernel/syscall/entry.c | 83 ++++++++----- kernel/syscall/io/io.c | 2 +- kernel/syscall/ipc/ipc.c | 113 +++++++++--------- tools/test_memory_pressure_mincore_fix4.py | 1 + tools/test_memory_pressure_regular_read.py | 4 +- tools/test_pipe_parallel.py | 9 +- tools/test_syscall_io.py | 3 +- tools/test_user_return_gate.py | 1 + tools/tests/inotify_core_test.c | 28 +++++ .../tests/memory_pressure_mincore_fix4_test.c | 4 +- tools/tests/pipe_parallel_runtime_probe.c | 30 ++++- tools/tests/pipe_parallel_test.c | 73 ++++++++++- tools/tests/pipe_wake_test.c | 6 +- tools/tests/sched_wakeup_test.c | 31 +++++ tools/tests/syscall_io_test.c | 3 + tools/tests/user_return_gate_test.c | 2 +- 23 files changed, 386 insertions(+), 124 deletions(-) diff --git a/Documentation/core-api/execution.rst b/Documentation/core-api/execution.rst index 124e93bc..d697ec8c 100644 --- a/Documentation/core-api/execution.rst +++ b/Documentation/core-api/execution.rst @@ -22,11 +22,11 @@ EEVDF 公平任务使用增强红黑树组织选择状态;CPU 所有权、任 源不可用时回退旧 uptime,源切换不使公平时钟倒退。这不是用户时钟源; 正常调度采样须在一次硬件回绕内,不对长时间暂停后的绝对时间作保证。 -发布可运行任务时,调度器设置各在线 CPU 的重新调度标志,并通过独立的 -LAPIC 向量唤醒远端 CPU;同一未处理标志只发送一次 IPI。自 CPU、离线 CPU -及 SMP 启动交接完成前不发送。IPI 只确认本地 APIC,用户帧进入正常的 -调度检查;内核帧继续执行,到原有安全检查点再切换,不抢占持锁内核代码。 -任务的 CPU 预留、亲和性、停止状态和 EEVDF 权重保持原有规则。 +唤醒一个阻塞任务时,调度器优先通知持有其用户帧的 CPU,或亲和性允许的 +上次运行且目前空闲的 CPU。两者均不可用时,向各在线 CPU 发布重新调度 +请求。远端 CPU 通过独立的 LAPIC 向量接收通知。同一未处理标志只发送 +一次 IPI。自 CPU、离线 CPU 及 SMP 启动交接完成前不发送。 +IPI 确认本地 APIC 后,用户帧进入正常调度检查,内核帧在安全检查点切换。 用户帧离开直接返回路径后,必须在释放 CPU 预留之前保存 FPU/SSE 状态。 空闲等待会释放执行事务,原任务可能在另一 CPU 运行并更新快照;因此即使 @@ -80,11 +80,17 @@ OFD、管道和地址空间的生命周期,各管道自己的数据锁保护 该路径只接纳没有共享 MM、没有在途续调且缓冲区已驻留的用户任务。 复制前检查全部页面;输出还要求各级页表及叶项具有真实硬件写权限。 缺页、COW、共享文件首次写入通知和设备映射不在数据锁内处理,统一回到 -完整路径。命名管道及带路径的描述符保留原来的 inode 通知,跟踪中的任务 -也走完整分发。每次复制仍最多 32 KiB,不改变 ``PIPE_BUF``、容量或 -大请求短读写语义。 - -数据锁在唤醒等待队列、通知 poll 或检查调度之前释放。阻塞等待和 +完整路径。匿名管道可以持有 pipefs inode 并走并行路径。命名管道、可能有 +inotify 读写观察者的匿名管道和跟踪中的任务仍走完整分发。每次复制仍最多 +32 KiB,``PIPE_BUF``、容量和大请求的短读写规则保持一致。内置 +``/dev/null`` 的标量写入也可用读事务完成。它检查描述符权限和用户地址 +范围,按 Linux 的单次传输上限返回已丢弃的字节数。 +有已驻留输出缓冲区的 ``clock_gettime(CLOCK_MONOTONIC)`` 也可以在读事务 +内取得原时间源的快照,避免启用进度显示时的连续时钟查询阻塞并行 I/O。 + +数据锁在唤醒等待队列、通知 poll 或检查调度之前释放。首次 poll 或 epoll +扫描会读取当时的管道状态并启用后续数据通知。在首次扫描之前,管道数据 +变动只唤醒该管道自身的读写等待者。阻塞等待和 ``SIGPIPE`` 继续由独占路径处理;检查条件与登记睡眠之间不会插入并行 数据修改。已完成的调用更新原有进程 I/O 统计,并用同一用户返回检查处理 待处理信号、CPU 亲和性和重新调度请求。 diff --git a/fs/notify/watch.c b/fs/notify/watch.c index 1c1c96c6..fae3cd66 100644 --- a/fs/notify/watch.c +++ b/fs/notify/watch.c @@ -4,6 +4,32 @@ #define FSNOTIFY_STORED_FLAGS (IN_EXCL_UNLINK|IN_ONESHOT) static uint64_t watch_total; +#define PIPE_WATCH_BUCKETS 64u +static uint64_t pipe_io_watches[PIPE_WATCH_BUCKETS]; + +/** @copydoc fsnotify_pipe_io_watched */ +bool fsnotify_pipe_io_watched(const struct storage_node *node) +{ + return pipe_io_watches[node->entry_id % PIPE_WATCH_BUCKETS] != 0; +} + +/** @brief Update the pipe I/O watch summary under the execution writer. + * @param key Watch's retained value identity. + * @param old_mask Previous event mask, or zero for a new watch. + * @param new_mask Updated event mask, or zero when removing the watch. + */ +static void fsnotify_pipe_io_update(const struct fsnotify_key *key, + uint32_t old_mask,uint32_t new_mask) +{ + if (!(key->node.flags & STORAGE_NODE_FLAG_PIPEFS)) return; + bool before = (old_mask & (IN_ACCESS | IN_MODIFY)) != 0; + bool after = (new_mask & (IN_ACCESS | IN_MODIFY)) != 0; + uint64_t *count = &pipe_io_watches[key->node.entry_id % PIPE_WATCH_BUCKETS]; + if (before != after) { + if (after) ++*count; + else --*count; + } +} /** @brief Check the global watch count without walking open instances. * @return True if at least one watch is live. Execution writer is required; @@ -60,8 +86,9 @@ int fsnotify_add_watch(struct fsnotify_instance *instance,const struct fsnotify_ for(struct fsnotify_watch *watch=instance->watches;watch;watch=watch->next) { if(!fsnotify_key_same(&watch->key,key))continue; if(mask & IN_MASK_CREATE)return -EEXIST; - if(mask & IN_MASK_ADD)watch->mask|=requested; - else watch->mask=requested; + if(mask & IN_MASK_ADD)requested|=watch->mask; + fsnotify_pipe_io_update(&watch->key,watch->mask,requested); + watch->mask=requested; return watch->wd; } int rc=fsnotify_account_watch_acquire(instance->account);if(rc)return rc; @@ -70,6 +97,7 @@ int fsnotify_add_watch(struct fsnotify_instance *instance,const struct fsnotify_ int wd=fsnotify_allocate_wd(instance); if(wd<0){kernel_free(watch);fsnotify_account_watch_release(instance->account);return wd;} *watch=(struct fsnotify_watch){.next=instance->watches,.key=*key,.mask=requested,.wd=wd}; + fsnotify_pipe_io_update(key,0,requested); instance->watches=watch;++watch_total;return wd; } @@ -84,6 +112,7 @@ void fsnotify_watch_remove(struct fsnotify_instance *instance,struct fsnotify_wa { struct fsnotify_watch *watch=*link; *link=watch->next; + fsnotify_pipe_io_update(&watch->key,watch->mask,0); if(ignored)fsnotify_queue_event(instance,watch->wd,IN_IGNORED,0,NULL); fsnotify_account_watch_release(instance->account); --watch_total;kernel_free(watch); diff --git a/include/reliefnt/fsnotify.h b/include/reliefnt/fsnotify.h index 8aa471fb..5a06f905 100644 --- a/include/reliefnt/fsnotify.h +++ b/include/reliefnt/fsnotify.h @@ -96,6 +96,13 @@ uint32_t fsnotify_next_cookie(void); * @return True if at least one watch exists. Execution writer required. */ bool fsnotify_has_watches(void); +/** @brief Check whether pipe I/O may need to deliver an inode event. + * @param node Borrowed anonymous pipefs inode identity. + * @return False when neither access nor modification has a watch in the + * inode's bucket. Collisions conservatively return true. Shared or exclusive + * execution ownership is sufficient; no callback or reference is acquired. + */ +bool fsnotify_pipe_io_watched(const struct storage_node *node); /** @brief Check whether a watched native cache generation needs preservation. * @param node Borrowed FAT/exFAT storage identity with nonzero generation. * @return True for matching filesystem, volume, mount and inode generation among watches. diff --git a/include/reliefnt/syscall_internal.h b/include/reliefnt/syscall_internal.h index fd61cef9..a0415a4b 100644 --- a/include/reliefnt/syscall_internal.h +++ b/include/reliefnt/syscall_internal.h @@ -13,6 +13,9 @@ struct trap_frame; struct task_lookup_path; struct storage_inode_ref; +/* Linux MAX_RW_COUNT: a signed-int byte count rounded down to a page. */ +#define LINUX_MAX_RW_COUNT 0x7ffff000u + /** @brief Unshare filesystem state through either Linux syscall dispatcher. * @param task Current execution-owned task, required. * @param flags Full native unsigned long flag word, without truncation. @@ -545,8 +548,8 @@ int task_pipe_write(struct task_file *file, const void *buffer, uint32_t length) */ bool task_pipe_try_io(struct task_file *file, void *buffer, uint32_t length, bool writing, int *result); -/** @brief Query readiness without parking; include terminal HUP/ERR conditions. - * @param file Pinned description under execution ownership. +/** @brief Query readiness and enable subsequent poll notifications for this pipe. + * @param file Pinned description under exclusive execution ownership. * @param events Requested Linux poll bits. * @return Ready event bits or POLLNVAL for a stale/nonpipe description. */ diff --git a/kernel/sched/core.c b/kernel/sched/core.c index eae9541f..27f02b3d 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -55,6 +55,17 @@ static void sched_request_reschedule_cpu(uint32_t cpu) __atomic_store_n(&sched_resched_pending[cpu], 1, __ATOMIC_RELEASE); } +/** @brief Queue a reschedule for one online CPU, sending at most one IPI. + * @param cpu Destination below SMP_MAX_CPUS. + * @param current CPU running the caller, whose return checks its own flag. + */ +static void sched_kick_cpu(uint32_t cpu, uint32_t current) +{ + uint32_t pending = __atomic_exchange_n(&sched_resched_pending[cpu], 1, + __ATOMIC_ACQ_REL); + if (cpu != current && !pending) smp_send_reschedule(cpu); +} + /** @brief Publish runnable work and interrupt remote CPUs once per pending flag. * IRQ/task callers serialize the readiness transition with scheduler_lock or * execution ownership. Local returns observe their own flag without an IPI; @@ -68,13 +79,25 @@ void sched_request_reschedule_all_online(void) if (count > SMP_MAX_CPUS) count = SMP_MAX_CPUS; for (uint32_t cpu = 0; cpu < count; ++cpu) { if (cpu != current && !smp_cpu_online(cpu)) continue; - uint32_t pending = __atomic_exchange_n(&sched_resched_pending[cpu], 1, - __ATOMIC_ACQ_REL); - if (cpu != current && !pending) smp_send_reschedule(cpu); + sched_kick_cpu(cpu, current); } if (current >= count) sched_request_reschedule_cpu(current); } +/** @copydoc sched_request_reschedule_for_wake */ +void sched_request_reschedule_for_wake(const struct task *task) +{ + uint32_t owner = task->running_cpu; + uint32_t cpu = owner == SCHED_CPU_NONE ? task->last_cpu : owner; + if (task->kind == TASK_KIND_USER && cpu < SMP_MAX_CPUS && smp_cpu_online(cpu) && + task_cpu_allowed(task, cpu) && + (owner == SCHED_CPU_NONE ? !current_task[cpu] : current_task[cpu] == task)) { + sched_kick_cpu(cpu, scheduler_cpu_index()); + return; + } + sched_request_reschedule_all_online(); +} + void sched_notify_runnable(void) { sched_request_reschedule_all_online(); diff --git a/kernel/sched/internal.h b/kernel/sched/internal.h index f6cf1a1c..77ccd442 100644 --- a/kernel/sched/internal.h +++ b/kernel/sched/internal.h @@ -501,6 +501,13 @@ uint32_t scheduler_cpu_index(void); */ void sched_request_reschedule_all_online(void); +/** @brief Kick a newly woken task's frame owner or idle previous CPU. + * @param task Live READY task under scheduler_lock after a blocked-task wake. + * Broadcast when neither target can service the task. Selection still uses + * the normal affinity, run-queue and work-stealing rules. + */ +void sched_request_reschedule_for_wake(const struct task *task); + void sched_notify_runnable(void); bool sched_current_cpu_needs_resched(void); diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index a6a0a326..d15230a0 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -27,9 +27,9 @@ void sched_block_current(void) /** @brief Wake a blocked task without reviving stopped/exited/vfork-wait tasks. * @param task Borrowed task pinned by execution/wait lifetime, nullable. - * IRQ/task safe scheduler-lock transaction; requests remote rescheduling only - * after publishing readiness. No allocation, callback or ownership transfer; - * running_cpu keeps an unretired frame from being claimed by another CPU. + * IRQ/task safe scheduler-lock transaction; publishes readiness before + * notifying the frame owner or an idle CPU where possible. No allocation, + * callback or ownership transfer. */ void sched_wake_interruptible(struct task *task) { @@ -38,7 +38,7 @@ void sched_wake_interruptible(struct task *task) if (task && task->state == TASK_BLOCKED && !task->vfork_child) { task->wake_tick = 0; task->state = TASK_READY; - sched_request_reschedule_all_online(); + sched_request_reschedule_for_wake(task); } /* running_cpu prevents another CPU from claiming a not-yet-retired frame. */ kernel_spin_unlock_irqrestore(&scheduler_lock, flags); diff --git a/kernel/syscall/entry.c b/kernel/syscall/entry.c index e2b56bb1..fc447320 100644 --- a/kernel/syscall/entry.c +++ b/kernel/syscall/entry.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -224,34 +225,37 @@ static int task_begin_syscall_io(struct task *task, uint64_t number, int32_t fd, /** @brief Check current private-MM user pages without faulting or allocating. * @param task Current task pinned by execution read ownership. * @param address User buffer address. @param length Bounded bytes to copy. - * @param writing True for a pipe write/source, false for a read/destination. + * @param writable True for a destination, false for an input buffer. * @return True only when every page is already accessible with the needed - * permission; a missing/COW page falls back before taking a pipe data lock. + * permission. Missing pages and COW use the ordinary faultable path. */ -static bool syscall_pipe_buffer_resident(struct task *task, uint64_t address, - uint32_t length, bool writing) +static bool syscall_buffer_resident(struct task *task, uint64_t address, + uint32_t length, bool writable) { for (uint64_t page = address & ~4095ULL, end = address + length; length && page < end; page += 4096u) { - if (!address_space_user_page_copyable(sched_task_as(task), page, !writing)) return false; + if (!address_space_user_page_copyable(sched_task_as(task), page, writable)) return false; } return true; } -/** @brief Admit ready scalar anonymous-pipe I/O without the exclusive gate. +/** @brief Admit ready pipe I/O, a null write or a monotonic snapshot under the reader. * @param frame Current syscall frame, changed only after completing an I/O. * @param resume Required output; NULL retains ordinary return scheduling. - * @return True after completing the call, false without consuming user bytes. + * @return True after completing the call, false without modifying user bytes. * The reader gate pins the task, private MM, descriptor/OFD and pipe ring * against close, resizing and reclaim. Per-pipe locks serialize data only; * missing pages, shared MM, tracing and every suspended call retain the full * dispatcher. Queued writers reject admission, preserving lifecycle progress. - * No user fault, allocator, inode notification or provider callback is allowed. + * Watched pipefs inodes use the writer to deliver notifications. No user + * fault, allocation or provider callback is allowed under the reader. */ -static bool syscall_try_pipe_io(struct trap_frame *frame, struct task **resume) +static bool syscall_try_shared(struct trap_frame *frame, struct task **resume) { bool writing = frame->rax == LINUX_SYS_WRITE; - if (!writing && frame->rax != LINUX_SYS_READ) return false; + bool clock = frame->rax == LINUX_SYS_CLOCK_GETTIME && + (int32_t)frame->rdi == LINUX_CLOCK_MONOTONIC; + if (!writing && !clock && frame->rax != LINUX_SYS_READ) return false; uint64_t flags; if (!kernel_execution_try_read_lock_scoped_irqsave(&flags, lock_profile_syscall_scope(frame->rax))) return false; @@ -260,28 +264,48 @@ static bool syscall_try_pipe_io(struct trap_frame *frame, struct task **resume) if (!task || task->kind != TASK_KIND_USER || task->state != TASK_RUNNING || task->running_cpu != smp_current_cpu() || task->shared_mm || (task->flags & TASK_FLAG_PENDING_LOAD) || task->syscall_file || task->syscall_pty.used || - task->restart_syscall || task->fifo_open_file || task->waiting_queue || syscall_trace_task(task)) goto out; + task->restart_syscall || task->fifo_open_file || task->waiting_queue || + task->sysv_sem.ops || task->sysv_msg.queue || syscall_trace_task(task)) goto out; #ifdef CONFIG_SECCOMP_FILTER /* This reader cannot queue signals or retire tasks. In particular, inspect * seccomp state under the gate shared with TSYNC and fork publication. */ if (seccomp_active(task)) goto out; #endif - struct task_file *file = task_file_for_fd(task, (int32_t)frame->rdi); - if (!file || !(file->flags & TASK_FILE_FLAG_PIPE) || (file->flags & TASK_FILE_FLAG_PATH) || - file->character_file || file->path_ref.mount) goto out; - uint64_t address = frame->rsi, count = frame->rdx; + uint64_t address = frame->rsi; + uint64_t count = clock ? sizeof(struct linux_timespec) : frame->rdx; if (count && (address < RELIEFNT_USER_BASE || address >= RELIEFNT_USER_TOP || count > RELIEFNT_USER_TOP - address)) goto out; - uint32_t length = count > 32768u ? 32768u : (uint32_t)count; - if (!syscall_pipe_buffer_resident(task, address, length, writing)) goto out; int result; - if (!task_pipe_try_io(file, (void *)(uintptr_t)address, length, writing, &result)) goto out; - if (writing) { - task->proc_write_chars += (uint64_t)result; - ++task->proc_write_calls; + if (clock) { + struct linux_timespec value; + if (!syscall_buffer_resident(task, address, sizeof(value), true)) goto out; + /* Reuse the syscall clock's locked snapshot and monotonic floor on + * machines whose vDSO must fall back to the kernel. */ + result = time_clock_get(LINUX_CLOCK_MONOTONIC, &value); + if (!result) *(struct linux_timespec *)(uintptr_t)address = value; } else { - task->proc_read_chars += (uint64_t)result; - ++task->proc_read_calls; + struct task_file *file = task_file_for_fd(task, (int32_t)frame->rdi); + if (!file || (file->flags & TASK_FILE_FLAG_PATH) || file->character_file) goto out; + if (file->flags & TASK_FILE_FLAG_PIPE) { + if (file->path_ref.mount && (!(file->node.flags & STORAGE_NODE_FLAG_PIPEFS) || + fsnotify_pipe_io_watched(&file->node))) goto out; + uint32_t length = count > 32768u ? 32768u : (uint32_t)count; + if (!syscall_buffer_resident(task, address, length, !writing) || + !task_pipe_try_io(file, (void *)(uintptr_t)address, length, writing, &result)) + goto out; + } else { + if (!writing || !(file->flags & TASK_FILE_FLAG_DEV_NULL) || + !file_can_write(file)) goto out; + /* Discard the bytes without accessing the user buffer. */ + result = (int)(count > LINUX_MAX_RW_COUNT ? LINUX_MAX_RW_COUNT : count); + } + if (writing) { + task->proc_write_chars += (uint64_t)result; + ++task->proc_write_calls; + } else { + task->proc_read_chars += (uint64_t)result; + ++task->proc_read_calls; + } } frame->rax = (uint64_t)result; *resume = NULL; @@ -515,9 +539,14 @@ static bool syscall_execute_locked(struct task *calling_task, struct trap_frame number == LINUX_SYS_PREADV2 || number == LINUX_SYS_GETDENTS || number == LINUX_SYS_GETDENTS64) && result >= 0; struct task_file *access_file = calling_task->syscall_file; - if ((scalar_access || vector_access) && access_file && access_file->path_ref.mount && - !(access_file->flags & TASK_FILE_FLAG_PATH) && vfs_notify_event) - vfs_notify_event(&access_file->path_ref, IN_ACCESS); + if (access_file && access_file->path_ref.mount && + !(access_file->flags & TASK_FILE_FLAG_PATH) && vfs_notify_event) { + if (scalar_access || vector_access) + vfs_notify_event(&access_file->path_ref, IN_ACCESS); + else if (result > 0 && (number == LINUX_SYS_WRITE || number == LINUX_SYS_WRITEV) && + (access_file->flags & TASK_FILE_FLAG_PIPE)) + vfs_notify_event(&access_file->path_ref, IN_MODIFY); + } } if (restored_signal_frame) { /* sigreturn and successful exec already supplied the user context. */ @@ -572,7 +601,7 @@ struct task *syscall_dispatch_frame(struct trap_frame *frame) if (!frame) return NULL; sched_account_mode(true); struct task *resume = NULL; - if (syscall_try_pipe_io(frame, &resume)) return resume; + if (syscall_try_shared(frame, &resume)) return resume; /* Several storage and GUI services still own global scratch buffers. */ kernel_execution_lock_scoped_irqsave(&lock_flags, lock_profile_syscall_scope(frame->rax)); #ifdef CONFIG_SWAP diff --git a/kernel/syscall/io/io.c b/kernel/syscall/io/io.c index a251a6e2..b835fbce 100644 --- a/kernel/syscall/io/io.c +++ b/kernel/syscall/io/io.c @@ -232,7 +232,7 @@ int64_t syscall_io_write(uint64_t a0, uint64_t a1, uint64_t a2) if ((file->flags & TASK_FILE_FLAG_DEV_NULL) || task_device_is(file, STORAGE_DEV_KIND_NULL)) { if (!file_can_write(file)) return -RELIEFOS_EBADF; - return (int64_t)(a2 > 0x7ffff000u ? 0x7ffff000u : a2); + return (int64_t)(a2 > LINUX_MAX_RW_COUNT ? LINUX_MAX_RW_COUNT : a2); } if (file->flags & TASK_FILE_FLAG_DEV_NODE) { if (!file_can_write(file)) return -RELIEFOS_EBADF; diff --git a/kernel/syscall/ipc/ipc.c b/kernel/syscall/ipc/ipc.c index c9e1ed90..e4a06e20 100644 --- a/kernel/syscall/ipc/ipc.c +++ b/kernel/syscall/ipc/ipc.c @@ -48,6 +48,7 @@ struct task_pipe { uint32_t reader_generation, writer_generation; uint32_t handle; bool named; + bool poll_seen; struct storage_node node; uint32_t head; uint32_t tail; @@ -290,6 +291,17 @@ static struct task_pipe *task_pipe_for_file(const struct task_file *file) KERNEL_OBJECT_PIPE); } +/** @brief Count buffered bytes from the pipe's bounded ring cursors. + * @param pipe Live pipe under exclusive execution ownership or its data lock. + * @return Current byte count. The ring has one spare byte to distinguish full + * from empty, and each cursor is strictly below capacity plus one. + */ +static uint32_t pipe_buffered(const struct task_pipe *pipe) +{ + uint32_t head = pipe->head, tail = pipe->tail; + return head >= tail ? head - tail : pipe->capacity + 1u - tail + head; +} + /** @brief Apply Linux pipe sizing while retaining byte order and per-UID accounting. * @param file Pinned pipe open-file description under execution ownership. * @param setting True to set capacity, false to query it. @@ -306,7 +318,7 @@ int64_t task_pipe_capacity(struct task_file *file, bool setting, uint32_t bytes) uint32_t capacity = TASK_PIPE_PAGE; while (capacity < bytes) capacity <<= 1; if (!task_pipe_privileged() && capacity > TASK_PIPE_USER_MAX) return -RELIEFOS_EPERM; - uint32_t used = (pipe->head + pipe->capacity + 1u - pipe->tail) % (pipe->capacity + 1u); + uint32_t used = pipe_buffered(pipe); if (used > capacity) return -RELIEFOS_EBUSY; if (capacity == pipe->capacity) return capacity; if (capacity > pipe->capacity && pipe->owner && !task_pipe_privileged() && @@ -423,15 +435,6 @@ int task_pipe_open(struct task *task, const struct vfs_path *path, uint32_t flag return fd; } -/** @brief Count buffered bytes with the pipe data lock held. - * @param pipe Live pipe protected by execution ownership and data_lock. - * @return Current buffered byte count; no waits or reference changes. - */ -static uint32_t pipe_buffered(const struct task_pipe *pipe) -{ - return (pipe->head + pipe->capacity + 1u - pipe->tail) % (pipe->capacity + 1u); -} - /** @brief Snapshot unread pipe bytes without consuming data or waiting. * @param file Borrowed read or write endpoint, pinned by execution ownership. * @return Buffered byte count or -EBADF for a stale/nonpipe description. @@ -450,41 +453,32 @@ int task_pipe_available(const struct task_file *file) /** @brief Copy buffered bytes while serializing this pipe's ring only. * @param pipe Live data-locked pipe. @param buffer Prepared writable memory. - * @param length Available destination bytes. @return Bytes consumed. + * @param count Committed byte count, no larger than the buffered data. * Caller prevents page faults while holding data_lock; no wait or allocation. */ -static uint32_t pipe_copy_read(struct task_pipe *pipe, void *buffer, uint32_t length) -{ - uint32_t count = 0; - while (pipe->tail != pipe->head && count < length) { - uint32_t chunk = pipe->tail < pipe->head ? pipe->head - pipe->tail - : pipe->capacity + 1u - pipe->tail; - if (chunk > length - count) chunk = length - count; - __builtin_memcpy((uint8_t *)buffer + count, pipe->data + pipe->tail, chunk); - pipe->tail = (pipe->tail + chunk) % (pipe->capacity + 1u); - count += chunk; - } - return count; +static void pipe_copy_read(struct task_pipe *pipe, void *buffer, uint32_t count) +{ + if (!count) return; + uint32_t to_end = pipe->capacity + 1u - pipe->tail; + uint32_t first = count < to_end ? count : to_end; + __builtin_memcpy(buffer, pipe->data + pipe->tail, first); + if (count > first) __builtin_memcpy((uint8_t *)buffer + first, pipe->data, count - first); + pipe->tail = count < to_end ? pipe->tail + count : count - to_end; } /** @brief Copy a bounded accepted write while holding one pipe's data lock. * @param pipe Live data-locked pipe. @param buffer Prepared readable bytes. - * @param length Requested bytes; caller has checked atomic-write admission. - * @return Bytes published, capped by free space. No wait or allocation; - * caller prevents page faults and keeps the entire atomic record locked. + * @param count Accepted bytes, no larger than the available space. + * Caller prevents page faults and keeps the entire atomic record locked. */ -static uint32_t pipe_copy_write(struct task_pipe *pipe, const void *buffer, uint32_t length) -{ - uint32_t count = 0, available = pipe->capacity - pipe_buffered(pipe); - if (length > available) length = available; - while (count < length) { - uint32_t chunk = pipe->capacity + 1u - pipe->head; - if (chunk > length - count) chunk = length - count; - __builtin_memcpy(pipe->data + pipe->head, (const uint8_t *)buffer + count, chunk); - pipe->head = (pipe->head + chunk) % (pipe->capacity + 1u); - count += chunk; - } - return count; +static void pipe_copy_write(struct task_pipe *pipe, const void *buffer, uint32_t count) +{ + if (!count) return; + uint32_t to_end = pipe->capacity + 1u - pipe->head; + uint32_t first = count < to_end ? count : to_end; + __builtin_memcpy(pipe->data + pipe->head, buffer, first); + if (count > first) __builtin_memcpy(pipe->data, (const uint8_t *)buffer + first, count - first); + pipe->head = count < to_end ? pipe->head + count : count - to_end; } /** @brief Complete a ready anonymous-pipe transfer under shared execution ownership. @@ -516,16 +510,18 @@ bool task_pipe_try_io(struct task_file *file, void *buffer, uint32_t length, kernel_spin_unlock_irqrestore(&pipe->data_lock, flags); return false; } - uint32_t count = writing ? pipe_copy_write(pipe, buffer, length) : pipe_copy_read(pipe, buffer, length); - available = pipe->capacity - pipe_buffered(pipe); + uint32_t limit = writing ? available : used; + uint32_t count = length < limit ? length : limit; + if (writing) pipe_copy_write(pipe, buffer, count); + else pipe_copy_read(pipe, buffer, count); kernel_spin_unlock_irqrestore(&pipe->data_lock, flags); if (count) { if (writing) { (void)kernel_wait_queue_wake_all(&pipe->wait_read); - kernel_poll_readiness_notify(); + if (pipe->poll_seen) kernel_poll_readiness_notify(); } else { - (void)kernel_wait_queue_wake_satisfied(&pipe->wait_write, available); - if (used == pipe->capacity) kernel_poll_readiness_notify(); + (void)kernel_wait_queue_wake_satisfied(&pipe->wait_write, available + count); + if (pipe->poll_seen && used == pipe->capacity) kernel_poll_readiness_notify(); } } *result = (int)count; @@ -547,13 +543,13 @@ int task_pipe_read(struct task_file *file, void *buffer, uint32_t length) kernel_wait_queue_remove(&pipe->wait_read, sched_current_task()); uint64_t flags; kernel_spin_lock_irqsave(&pipe->data_lock, &flags); - bool was_full = pipe_buffered(pipe) == pipe->capacity; - uint32_t count = pipe_copy_read(pipe, buffer, length); - uint32_t available = pipe->capacity - pipe_buffered(pipe); + uint32_t used = pipe_buffered(pipe); + uint32_t count = length < used ? length : used; + pipe_copy_read(pipe, buffer, count); kernel_spin_unlock_irqrestore(&pipe->data_lock, flags); if (count) { - (void)kernel_wait_queue_wake_satisfied(&pipe->wait_write, available); - if (was_full) kernel_poll_readiness_notify(); + (void)kernel_wait_queue_wake_satisfied(&pipe->wait_write, pipe->capacity - used + count); + if (pipe->poll_seen && used == pipe->capacity) kernel_poll_readiness_notify(); return (int)count; } if (!pipe->writers) return 0; @@ -590,11 +586,12 @@ int task_pipe_write(struct task_file *file, const void *buffer, uint32_t length) kernel_wait_queue_block_current_minimum(&pipe->wait_write, length); return -RELIEFOS_EAGAIN; } - uint32_t count = pipe_copy_write(pipe, buffer, length); + uint32_t count = length < available ? length : available; + pipe_copy_write(pipe, buffer, count); kernel_spin_unlock_irqrestore(&pipe->data_lock, flags); if (count) { (void)kernel_wait_queue_wake_all(&pipe->wait_read); - kernel_poll_readiness_notify(); + if (pipe->poll_seen) kernel_poll_readiness_notify(); return (int)count; } if (file->flags & RELIEFOS_O_NONBLOCK) return -RELIEFOS_EAGAIN; @@ -603,26 +600,26 @@ int task_pipe_write(struct task_file *file, const void *buffer, uint32_t length) } /** - * @brief Report endpoint readiness and FIFO writer-generation HUP semantics. - * @param file Pinned description under the kernel execution lock. + * @brief Report readiness and mark this pipe for subsequent data notifications. + * @param file Pinned description under the exclusive execution gate. * @param events Requested poll events. * @return Ready bits and unconditional HUP/ERR/NVAL notifications. */ short task_pipe_poll(const struct task_file *file, short events) { - const struct task_pipe *pipe = task_pipe_for_file(file); + struct task_pipe *pipe = task_pipe_for_file(file); short result = 0; if (!pipe) { return POLLNVAL; } + /* Every poll/epoll scan reaches here before sleeping. The execution gate + * orders this first scan against data transfers on the same pipe. */ + pipe->poll_seen = true; if ((file->flags & RELIEFOS_O_ACCMODE) != RELIEFOS_O_RDONLY) { if (pipe->readers == 0) { result |= POLLERR; - } else if (events & POLLOUT) { - uint32_t next = (pipe->head + 1U) % (pipe->capacity + 1u); - if (next != pipe->tail) { - result |= POLLOUT; - } + } else if ((events & POLLOUT) && pipe_buffered(pipe) < pipe->capacity) { + result |= POLLOUT; } } if ((file->flags & RELIEFOS_O_ACCMODE) != RELIEFOS_O_WRONLY) { diff --git a/tools/test_memory_pressure_mincore_fix4.py b/tools/test_memory_pressure_mincore_fix4.py index 98c95ba2..1eaf8b10 100644 --- a/tools/test_memory_pressure_mincore_fix4.py +++ b/tools/test_memory_pressure_mincore_fix4.py @@ -46,6 +46,7 @@ def main(): sources = ["tools/tests/memory_pressure_mincore_fix4_test.c", "kernel/exec/usercopy.c", "kernel/syscall/fs/lookup_state.c", "kernel/sched/core.c", "kernel/sched/accounting.c", "kernel/sched/wait.c", + "kernel/sched/user_namespace.c", "kernel/sched/oom.c", "kernel/sync/wait.c", "block/core/storage_wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/attributes.c", diff --git a/tools/test_memory_pressure_regular_read.py b/tools/test_memory_pressure_regular_read.py index 069cefe7..86a175f9 100644 --- a/tools/test_memory_pressure_regular_read.py +++ b/tools/test_memory_pressure_regular_read.py @@ -39,7 +39,9 @@ def main(): "-Wl,--gc-sections", "-I" + str(directory), "-Iinclude", "-Iinclude/uapi"] sources = ["tools/tests/memory_pressure_regular_read_test.c", "kernel/exec/usercopy.c", "tools/tests/task8_host_stubs/device_page_unreached.c", - "kernel/syscall/fs/lookup_state.c", "kernel/sched/core.c", "kernel/sched/accounting.c", + "kernel/syscall/fs/lookup_state.c", "kernel/syscall/fs/locks.c", + "kernel/sched/core.c", "kernel/sched/accounting.c", + "kernel/sched/user_namespace.c", "kernel/sched/wait.c", "kernel/sched/oom.c", "kernel/sync/wait.c", "block/core/storage_wait.c", "mm/reclaim/pressure.c", "mm/reclaim/wait.c", "mm/cache/page_cache.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", diff --git a/tools/test_pipe_parallel.py b/tools/test_pipe_parallel.py index f197f9c8..a59c169d 100644 --- a/tools/test_pipe_parallel.py +++ b/tools/test_pipe_parallel.py @@ -13,13 +13,8 @@ temporary.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="pipe-parallel-", dir=temporary) as directory: work = Path(directory) - if "static bool syscall_try_pipe_io(" in source: - bodies = [function(source, name) for name in ( - "syscall_trace_task", "syscall_pipe_buffer_resident", "syscall_try_pipe_io")] - else: - # Old kernels route every pipe transaction through the exclusive gate. - bodies = ["static bool syscall_try_pipe_io(struct trap_frame *f, struct task **r) " - "{ (void)f; (void)r; return false; }"] + bodies = [function(source, name) for name in ( + "file_can_write", "syscall_trace_task", "syscall_buffer_resident", "syscall_try_shared")] (work / "pipe_entry.inc").write_text("\n\n".join(bodies)) binary = work / "pipes" subprocess.run(["clang", "-std=gnu11", "-O1", "-g", "-pthread", "-Wall", "-Wextra", diff --git a/tools/test_syscall_io.py b/tools/test_syscall_io.py index d4a502d8..15b46b2f 100644 --- a/tools/test_syscall_io.py +++ b/tools/test_syscall_io.py @@ -101,7 +101,8 @@ def main(): "-fno-omit-frame-pointer", "-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections", "-I" + str(work), "-Iinclude", "-Iinclude", "-Iinclude", "-Iinclude/uapi", - "tools/tests/syscall_io_test.c", "fs/vfs/file.c", "fs/vfs/open.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", + "tools/tests/syscall_io_test.c", "fs/vfs/file.c", "fs/vfs/open.c", + "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "kernel/sched/user_namespace.c", "-o", str(executable), ], cwd=ROOT, env={**os.environ, "TMPDIR": str(temporary)}) run([str(executable)], cwd=ROOT, timeout=30) diff --git a/tools/test_user_return_gate.py b/tools/test_user_return_gate.py index 77cd6b89..a7b89d12 100644 --- a/tools/test_user_return_gate.py +++ b/tools/test_user_return_gate.py @@ -86,6 +86,7 @@ def main(): "-Iinclude/uapi", "-Iinclude", "tools/tests/" + fixture + ".c", *(["kernel/syscall/fs/lookup_state.c", "kernel/syscall/io/vector.c", "fs/vfs/mount_tree.c", "fs/vfs/lookup_cache.c", "fs/vfs/path.c", + "kernel/sched/user_namespace.c", "drivers/usb/core/registry.c", "drivers/usb/core/work.c", "kernel/device/driver_manager_phase.c", "block/device/registry.c"] if fixture == "user_return_gate_test" else []), "-o", str(executable), diff --git a/tools/tests/inotify_core_test.c b/tools/tests/inotify_core_test.c index 5f60e0de..b116fefd 100644 --- a/tools/tests/inotify_core_test.c +++ b/tools/tests/inotify_core_test.c @@ -250,6 +250,33 @@ static void test_limits_lifetime_and_faults(void) assert(c != 0 && fsnotify_next_cookie() != c); } +/** @brief Keep the pipe I/O hint in sync with changes to live watches. */ +static void test_pipe_io_watches(void) +{ + struct fsnotify_instance *i = instance(100); + struct fsnotify_key pipe = key(3, 11, RELIEFOS_FS_TYPE_FIFO); + pipe.node.flags = STORAGE_NODE_FLAG_PIPEFS; + pipe.node.entry_id = 7; + struct storage_node other = pipe.node; + other.entry_id++; + int wd = fsnotify_add_watch(i, &pipe, IN_ATTRIB); + assert(wd > 0 && !fsnotify_pipe_io_watched(&pipe.node)); + assert(fsnotify_add_watch(i, &pipe, IN_ACCESS | IN_MASK_ADD) == wd); + assert(fsnotify_pipe_io_watched(&pipe.node) && !fsnotify_pipe_io_watched(&other)); + assert(fsnotify_add_watch(i, &pipe, IN_MODIFY | IN_ONESHOT) == wd); + fsnotify_emit(&pipe, IN_MODIFY, 0, NULL, false); + assert(!fsnotify_pipe_io_watched(&pipe.node)); + expect_event(i, wd, IN_MODIFY, 0, NULL, 0); + expect_event(i, wd, IN_IGNORED, 0, NULL, 0); + wd = fsnotify_add_watch(i, &pipe, IN_ACCESS); + assert(wd > 0 && fsnotify_pipe_io_watched(&pipe.node)); + assert(fsnotify_add_watch(i, &pipe, IN_ATTRIB) == wd); + assert(!fsnotify_pipe_io_watched(&pipe.node)); + assert(fsnotify_add_watch(i, &pipe, IN_MODIFY) == wd); + fsnotify_put(i); + assert(!fsnotify_pipe_io_watched(&pipe.node)); +} + int main(void) { assert(sizeof(struct inotify_event) == 16); @@ -257,6 +284,7 @@ int main(void) test_oneshot_exclusion_and_lifecycle(); test_overflow_and_allocation_failure(); test_limits_lifetime_and_faults(); + test_pipe_io_watches(); assert(wakeups > 0 && allocations == 0); puts("inotify core: all tests passed"); return 0; diff --git a/tools/tests/memory_pressure_mincore_fix4_test.c b/tools/tests/memory_pressure_mincore_fix4_test.c index fb0abb3f..aaa41f02 100644 --- a/tools/tests/memory_pressure_mincore_fix4_test.c +++ b/tools/tests/memory_pressure_mincore_fix4_test.c @@ -101,11 +101,11 @@ void task_release_syscall_file(struct task *task) #endif void task_process_vm_scope_release(void *state) { (void)state; abort(); } void sched_task_identity_put(struct task_identity *identity) { (void)identity; abort(); } -/** @brief No fixture descriptor belongs to a pipe. +/** @brief Route this fixture's reclaim calls through exclusive dispatch. * @param frame Borrowed syscall frame. @param resume Unchanged task output. * @return False so the production slow dispatcher executes the tested syscall. */ -static bool syscall_try_pipe_io(struct trap_frame *frame,struct task **resume) +static bool syscall_try_shared(struct trap_frame *frame,struct task **resume) { (void)frame; (void)resume; return false; } int64_t kernel_signal_rt_sigreturn(struct task *t,struct trap_frame *f) { (void)t; (void)f; abort(); } diff --git a/tools/tests/pipe_parallel_runtime_probe.c b/tools/tests/pipe_parallel_runtime_probe.c index 6be5b60a..7a88d6b6 100644 --- a/tools/tests/pipe_parallel_runtime_probe.c +++ b/tools/tests/pipe_parallel_runtime_probe.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -95,6 +96,33 @@ static void destinations(void) puts("[pipe-parallel] lazy/COW destinations preserved"); } +/** @brief Observe scalar transfers through the pipefs inode in /proc/self/fd. */ +static void pipe_notifications(void) +{ + int pair[2]; + if (pipe(pair)) { CHECK(0); return; } + int events = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); + char name[48], byte = 0; + snprintf(name, sizeof(name), "/proc/self/fd/%d", pair[0]); + int wd = inotify_add_watch(events, name, IN_ACCESS | IN_MODIFY); + CHECK(wd >= 0); + CHECK(write(pair[1], "p", 1) == 1 && read(pair[0], &byte, 1) == 1 && byte == 'p'); + struct inotify_event records[2]; + ssize_t bytes = read(events, records, sizeof(records)); + CHECK(bytes == sizeof(records)); + if (bytes == sizeof(records)) { + CHECK(records[0].wd == wd && records[0].mask == IN_MODIFY && !records[0].len); + CHECK(records[1].wd == wd && records[1].mask == IN_ACCESS && !records[1].len); + } + CHECK(inotify_rm_watch(events, wd) == 0); + CHECK(write(pair[1], "q", 1) == 1 && read(pair[0], &byte, 1) == 1 && byte == 'q'); + CHECK(read(events, records, sizeof(records)) == sizeof(records[0]) && + records[0].mask == IN_IGNORED); + close(events); + close(pair[0]); + close(pair[1]); +} + /** @brief Query a monotonic timestamp in nanoseconds. */ static uint64_t now(void) { @@ -142,7 +170,7 @@ int main(int argc,char **argv) { setvbuf(stdout,NULL,_IONBF,0);alarm(25); if(argc==2 && !strcmp(argv[1],"--pty"))return terminal(); - records(64);records(4096);destinations(); + records(64);records(4096);destinations();pipe_notifications(); printf("[pipe-parallel] DONE failures=%u\n",failures); return failures ? 1 : 0; } diff --git a/tools/tests/pipe_parallel_test.c b/tools/tests/pipe_parallel_test.c index d0fda8ed..52fce930 100644 --- a/tools/tests/pipe_parallel_test.c +++ b/tools/tests/pipe_parallel_test.c @@ -7,6 +7,7 @@ #include #include #include "../../kernel/syscall/internal.h" +#include #include "../../kernel/sync/lock.c" #include "../../kernel/sync/wait.c" @@ -28,6 +29,7 @@ static pthread_mutex_t rendezvous = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t changed = PTHREAD_COND_INITIALIZER; static const void *held_source; static bool copying, independent_finished; +static bool watched; uint64_t kernel_irq_save(void) { uint64_t saved=irq;irq=0;return saved; } void kernel_irq_restore(uint64_t flags) { irq=flags; } @@ -54,6 +56,18 @@ bool sched_try_resume_current_user_frame(const struct trap_frame *frame) { assert(__atomic_load_n(&execution_readers,__ATOMIC_ACQUIRE) && !irq);if(resume_ok)owner.frame=*frame;return resume_ok; } void arch_set_user_fs(uint64_t base) { assert(__atomic_load_n(&execution_readers,__ATOMIC_ACQUIRE) && base==owner.fs_base); } +/** @brief Supply inotify admission for the retained anonymous inode. */ +bool fsnotify_pipe_io_watched(const struct storage_node *node) +{ assert(node->flags == STORAGE_NODE_FLAG_PIPEFS && node->entry_id == 7); return watched; } + +/** @brief Supply the monotonic clock's protected snapshot to the entry fixture. */ +int time_clock_get(int32_t clock, struct linux_timespec *value) +{ + assert(clock == LINUX_CLOCK_MONOTONIC && !irq && execution_readers); + *value = (struct linux_timespec){.tv_sec = 7, .tv_nsec = 56}; + return 0; +} + #include "pipe_entry.inc" /** @brief Initialize one host thread as a distinct logical kernel CPU. */ @@ -84,7 +98,7 @@ static bool invoke(bool writing,unsigned pipe,void *buffer,size_t length,int64_t struct trap_frame frame={.rax=writing ? LINUX_SYS_WRITE : LINUX_SYS_READ, .rdi=3+2*pipe+writing,.rsi=(uintptr_t)buffer,.rdx=length}; struct trap_frame before=frame;struct task *resume=NULL; - bool done=syscall_try_pipe_io(&frame,&resume); + bool done=syscall_try_shared(&frame,&resume); assert(!irq); if(done) { *result=(int64_t)frame.rax;assert(resume==(resume_ok ? &owner : NULL)); } else assert(!memcmp(&before,&frame,sizeof(frame)) && !resume); @@ -165,7 +179,28 @@ int main(void) pipes[0].named=true;assert(!invoke(true,0,bytes,64,&result));pipes[0].named=false; ends[0][1].path_ref.mount=(void *)1;assert(!invoke(true,0,bytes,64,&result)); ends[0][1].path_ref.mount=NULL; + + for (unsigned end = 0; end < 2; ++end) { + ends[0][end].path_ref.mount = (void *)1; + ends[0][end].node = (struct storage_node){.type = RELIEFOS_FS_TYPE_FIFO, + .flags = STORAGE_NODE_FLAG_PIPEFS, .entry_id = 7}; + } + watched = true; + assert(!invoke(true,0,bytes,64,&result) && !invoke(false,0,out,64,&result)); + watched = false; + uint64_t generation = kernel_poll_readiness_generation(); + if (!invoke(true,0,bytes,64,&result) || result != 64 || + !invoke(false,0,out,64,&result) || result != 64 || memcmp(bytes,out,64)) { + fputs("FAIL: a retained anonymous pipefs inode disabled parallel I/O\n",stderr); + return 1; + } + assert(kernel_poll_readiness_generation() == generation); + uint64_t flags; + kernel_execution_lock_irqsave(&flags); + assert(!task_pipe_poll(&ends[0][0], POLLIN)); + kernel_execution_unlock_irqrestore(flags); assert(invoke(true,0,bytes,32768,&result) && result==32768); + assert(kernel_poll_readiness_generation() != generation); assert(invoke(true,0,bytes,32768,&result) && result==32768); assert(!invoke(true,0,bytes,64,&result)); assert(invoke(false,0,out,1,&result) && result==1); @@ -173,10 +208,42 @@ int main(void) ends[0][1].flags|=RELIEFOS_O_NONBLOCK; assert(!invoke(true,0,bytes,64,&result)); assert(invoke(true,0,bytes,8192,&result) && result==1); /* Large nonblocking short write. */ - uint64_t flags;kernel_execution_lock_irqsave(&flags); + kernel_execution_lock_irqsave(&flags); assert(!invoke(true,0,bytes,64,&result));kernel_execution_unlock_irqrestore(flags); - reset();unsigned char a[64],b[64];memset(a,0xa5,64);memset(b,0x5a,64); + ends[1][1].flags = TASK_FILE_FLAG_DEV_NULL | RELIEFOS_O_WRONLY; + resident = false; + if (!invoke(true,1,(void *)RELIEFNT_USER_BASE,0x80000000u,&result) || + result != 0x7ffff000u) { + fputs("FAIL: discard-only writes entered the exclusive I/O path\n",stderr); + return 1; + } + assert(!invoke(true,1,(void *)(RELIEFNT_USER_TOP-1),2,&result)); + assert(invoke(true,1,NULL,0,&result) && result==0); + ends[1][1].flags |= TASK_FILE_FLAG_PATH; + assert(!invoke(true,1,bytes,64,&result)); + ends[1][1].flags = TASK_FILE_FLAG_DEV_NULL | RELIEFOS_O_RDONLY; + assert(!invoke(true,1,bytes,64,&result)); + + reset(); + struct linux_timespec time = {0}; + struct trap_frame clock = {.rax = LINUX_SYS_CLOCK_GETTIME, .rdi = LINUX_CLOCK_MONOTONIC, + .rsi = (uintptr_t)&time}; + struct task *resume = NULL; + if (!syscall_try_shared(&clock, &resume)) { + fputs("FAIL: a resident monotonic time query entered the exclusive dispatcher\n",stderr); + return 1; + } + assert(clock.rax == 0 && resume == &owner && time.tv_sec == 7 && time.tv_nsec == 56); + assert(!owner.proc_read_calls && !owner.proc_write_calls); + clock.rax = LINUX_SYS_CLOCK_GETTIME; + writable = false; + assert(!syscall_try_shared(&clock, &resume)); + writable = true; + clock.rdi = LINUX_CLOCK_THREAD_CPUTIME_ID; + assert(!syscall_try_shared(&clock, &resume)); + + unsigned char a[64],b[64];memset(a,0xa5,64);memset(b,0x5a,64); held_source=a;pthread_t first,second; struct operation operations[]={{1,0,a,true},{2,1,b,false}}; assert(!pthread_create(&first,NULL,independent,&operations[0])); diff --git a/tools/tests/pipe_wake_test.c b/tools/tests/pipe_wake_test.c index 8726477b..c8eff58a 100644 --- a/tools/tests/pipe_wake_test.c +++ b/tools/tests/pipe_wake_test.c @@ -88,9 +88,11 @@ void kernel_free(void *memory) (void)memory; } -/** @brief Reject VFS access in the wait-queue fixture. */ +#ifndef PIPE_WAKE_REAL_VFS +/** @brief Reject VFS access in the standalone wait-queue fixture. */ const struct storage_node *vfs_path_node(const struct vfs_path *path) { (void)path; abort(); } +#endif int storage_inode_put(struct storage_inode_ref *reference) { @@ -260,6 +262,8 @@ static int test_full_to_nonfull_read_notifies_global_poll_waiters(void) { reset_pipe(); if (fill_pipe(TASK_PIPE_CAP)) return 1; + REQUIRE(task_pipe_poll(&write_end, POLLOUT) == 0, + "poll must inspect the full pipe before waiting for writable space"); if (block_global_poll_waiter(4u)) return 1; uint64_t generation = kernel_poll_readiness_generation(); diff --git a/tools/tests/sched_wakeup_test.c b/tools/tests/sched_wakeup_test.c index be8cb8d0..81e0afc2 100644 --- a/tools/tests/sched_wakeup_test.c +++ b/tools/tests/sched_wakeup_test.c @@ -21,6 +21,36 @@ void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) { (void)lock; (void)flags; } +/** @brief Wake on the former idle CPU and keep the local running task on CPU. */ +static void test_idle_cpu_wake(void) +{ + fixture_cpus = 2; + ipis[1] = 0; + sched_resched_pending[0] = sched_resched_pending[1] = 0; + struct task blocked = {.pid = 8, .kind = TASK_KIND_USER, .state = TASK_BLOCKED, + .running_cpu = SCHED_CPU_NONE, .last_cpu = 1, .affinity_mask = 3}; + sched_wake_interruptible(&blocked); + assert(blocked.state == TASK_READY && blocked.running_cpu == SCHED_CPU_NONE); + assert(ipis[1] == 1 && sched_resched_pending[1] && !sched_resched_pending[0]); + + blocked.state = TASK_BLOCKED; + blocked.running_cpu = 1; + current_task[1] = &blocked; + sched_resched_pending[1] = 0; + sched_wake_interruptible(&blocked); + assert(blocked.state == TASK_READY && blocked.running_cpu == 1); + assert(ipis[1] == 2 && sched_resched_pending[1] && !sched_resched_pending[0]); + + struct task other = {.pid = 9, .state = TASK_RUNNING}; + blocked.state = TASK_BLOCKED; + blocked.running_cpu = SCHED_CPU_NONE; + current_task[1] = &other; + sched_resched_pending[1] = 0; + sched_wake_interruptible(&blocked); + assert(blocked.state == TASK_READY && sched_resched_pending[0] && ipis[1] == 3); + current_task[1] = NULL; +} + int main(void) { /* A wakeup must interrupt remote CPUs without waiting for a timer. */ @@ -68,5 +98,6 @@ int main(void) assert(sched_set_task_affinity(7,1)==-22 && task.affinity_mask==1); task.kind=TASK_KIND_USER;assert(!sched_set_task_affinity(7,1)); tasks=NULL;task_count=0; + test_idle_cpu_wake(); puts("PASS scheduler wake: remote interrupt, coalescing, offline/UP, ownership and stopped/vfork state"); } diff --git a/tools/tests/syscall_io_test.c b/tools/tests/syscall_io_test.c index 0081cc42..538748d2 100644 --- a/tools/tests/syscall_io_test.c +++ b/tools/tests/syscall_io_test.c @@ -3,9 +3,11 @@ * The fixture checks descriptor selection, validation and pipe/eventfd/null * results; full dispatcher routing is covered separately in the guest. */ #include +#define PIPE_WAKE_REAL_VFS #define main pipe_wake_regressions #include "pipe_wake_test.c" #undef main +#undef PIPE_WAKE_REAL_VFS #include #include #include @@ -13,6 +15,7 @@ #include #include #include +#include #include static _Noreturn int io_unexpected(const char *name, ...) diff --git a/tools/tests/user_return_gate_test.c b/tools/tests/user_return_gate_test.c index 95f464bd..43511226 100644 --- a/tools/tests/user_return_gate_test.c +++ b/tools/tests/user_return_gate_test.c @@ -293,7 +293,7 @@ static int64_t backend(struct task *task, uint64_t nr, uint64_t a0, return backend_result; } /* Pipe reader admission is tested against real concurrent rings separately. */ -static bool syscall_try_pipe_io(struct trap_frame *frame,struct task **resume) +static bool syscall_try_shared(struct trap_frame *frame,struct task **resume) {(void)frame;(void)resume;return false;} #define RELIEFOS_SYSCALL_FRAME_DISPATCH backend #include "syscall_return_body.inc" From 786c1f68fada4c31bb93a8e4f207951112653968 Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Fri, 4 Dec 2026 20:43:03 +0800 Subject: [PATCH 2/2] perf(net): batch Ethernet RX and reduce socket polling latency Submit e1000 DMA asynchronously, batch descriptor recycling, and enable e1000e MSI with a polling fallback. Cut empty synchronous scans and add a bounded UDP reply recheck on polling NICs. --- Documentation/core-api/network-devices.rst | 15 +++ drivers/net/e1000/e1000_main.c | 64 ++++++---- drivers/net/e1000e/Kbuild | 2 +- drivers/net/e1000e/internal.h | 22 +++- drivers/net/e1000e/interrupt.c | 79 ++++++++++++ drivers/net/e1000e/main.c | 8 +- drivers/net/e1000e/rings.c | 28 +++-- include/reliefnt/net.h | 10 ++ include/reliefnt/net_device.h | 6 + include/reliefnt/net_ipv6.h | 3 +- kernel/device/services.c | 40 +++++-- net/input.c | 112 ++++++++++++++---- net/internal.h | 7 +- net/ipv6/core.c | 16 ++- net/socket/udp.c | 31 +++++ net/tcp/socket.c | 17 +-- net/utility.c | 27 ++--- tools/test_e1000e.py | 2 +- tools/tests/e1000_init_test.c | 13 ++ tools/tests/e1000e_test.c | 58 +++++++++ tools/tests/ipv6_protocol_test.c | 4 +- tools/tests/ipv6_vector_stubs.c | 18 +++ tools/tests/net_rx_budget_test.c | 42 ++++++- ...didate-3-net-ioctl-user-candidate-3.stub.c | 2 +- tools/tests/task8_inet_signal_test.c | 1 + tools/tests/tcp_state_test.c | 2 +- tools/tests/udp_socket_test.c | 1 + 27 files changed, 516 insertions(+), 114 deletions(-) create mode 100644 drivers/net/e1000e/interrupt.c diff --git a/Documentation/core-api/network-devices.rst b/Documentation/core-api/network-devices.rst index bbb75171..a22ebc9f 100644 --- a/Documentation/core-api/network-devices.rst +++ b/Documentation/core-api/network-devices.rst @@ -22,6 +22,19 @@ Device identity e1000 和 e1000e 的链路状态查询在每个设备、每个时钟 tick 内复用一次硬件采样,避免短时间内反复读取同一个 MMIO 寄存器。e1000e 发送前另行检查当前链路。收包轮询和协议定时器照常运行。 +e1000 把帧提交到 DMA 环后立即返回,仅在环满时等待可重用的描述符。 +e1000 和 e1000e 每回收 8 个接收描述符更新一次硬件队列尾指针,队列排空时立即归还余下的描述符。 +e1000e 优先使用 MSI 收包。IRQ 只应答硬件并安排任务上下文收包。任务发现 +队列已空时重新打开通知并复查描述符,以处理这段时间到达的数据。MSI +分配失败时继续轮询,卸载时先关闭 IRQ 并等待回调退出,再停止 DMA。 + +同步收包在完整一轮网卡都没有新数据或协议工作时结束,每次最多处理 32 轮。 +收到丢弃的描述符、推进 TCP 发送或投递 loopback 数据时继续处理。 +UDP 单播通过轮询网卡发出后,如果随即检查收包且队列为空,内核会再检查 +一次出站网卡。每次最多使用约 180 微秒的检查预算,所有接口每个时钟 +tick 合计最多 2 毫秒,并有尝试次数上限。IRQ 网卡通过现有的就绪通知唤醒 +等待 ``poll()`` 的任务。 + 旧 ``e1000_*`` 服务入口和 ReliefOS 旧网络管理请求查询首个存活接口。 旧驱动 API 表和公开用户结构继续使用原布局。新设备接口属于 ReliefNT 私有 内核接口,原生模块通过精确构建 ABI 关联。 @@ -86,6 +99,8 @@ Validation ========== ``tools/test_net_device.py`` 验证多个 owner、独立回调、计数和索引生命周期。 +``tools/test_net_rx_budget.py`` 验证中断收包的公平调度、同步空轮询退出和 UDP +收包复查预算。e1000 与 e1000e 的宿主测试检查 DMA 环、描述符发布及 MSI 回退。 ``tools/test_net_multi_interface.py`` 验证 ioctl、rtnetlink 和逐接口选路。 ``tools/test_net_multinic_data.py`` 验证 ARP、UDP 输出和 AF_PACKET 隔离。 既有 TCP、UDP 和 IPv6 定向套件覆盖对应传输的设备绑定、作用域与资源清理。 diff --git a/drivers/net/e1000/e1000_main.c b/drivers/net/e1000/e1000_main.c index c89f46c9..f2c30bfd 100644 --- a/drivers/net/e1000/e1000_main.c +++ b/drivers/net/e1000/e1000_main.c @@ -80,6 +80,7 @@ static void e1000_log(enum console_log_level level, const char *message) /* Linux e1000's default accommodates receive bursts while a task is running. */ #define E1000_RX_COUNT 256u +#define E1000_RX_REFILL_BATCH 8u #define E1000_TX_COUNT 16u #define E1000_BUFFER_SIZE 2048u #define E1000_TX_WAIT_SPINS 250000u @@ -134,6 +135,7 @@ struct e1000_state { uint8_t *rx_buf[E1000_RX_COUNT]; uint8_t *tx_buf[E1000_TX_COUNT]; uint32_t rx_index; + uint32_t rx_refill_count; uint32_t tx_tail; struct kernel_spinlock carrier_lock; uint64_t carrier_tick; @@ -157,15 +159,6 @@ static void e1000_memzero(void *dst, uint32_t len) } } -static void e1000_memcpy(void *dst, const void *src, uint32_t len) -{ - uint8_t *d = (uint8_t *)dst; - const uint8_t *s = (const uint8_t *)src; - while (len--) { - *d++ = *s++; - } -} - static uint32_t e1000_reg_read(struct e1000_state *d, uint32_t offset) { return *(volatile uint32_t *)(d->mmio_base + offset); @@ -309,6 +302,7 @@ static void e1000_configure_rx_tx(struct e1000_state *d) e1000_reg_write(d, E1000_REG_RDH, 0); e1000_reg_write(d, E1000_REG_RDT, E1000_RX_COUNT - 1u); d->rx_index = 0; + d->rx_refill_count = 0; e1000_reg_write(d, E1000_REG_TDBAL, (uint32_t)d->tx_phys); e1000_reg_write(d, E1000_REG_TDBAH, (uint32_t)(d->tx_phys >> 32)); @@ -429,6 +423,11 @@ static const uint8_t *e1000_device_mac(void *context) return d->mac; } +/** @brief Publish one frame to the TX ring, waiting only for reusable space. + * @param context Active controller under network execution ownership. + * @param frame Borrowed Ethernet frame. @param len Frame bytes excluding hardware FCS. + * @return Zero when DMA owns the frame, or a negative input or ring-full error. + */ static int e1000_device_send(void *context, const void *frame, uint32_t len) { struct e1000_state *d=context; @@ -438,8 +437,12 @@ static int e1000_device_send(void *context, const void *frame, uint32_t len) return -1; } index = d->tx_tail; + next = (index + 1u) % E1000_TX_COUNT; + /* The tail must never catch an outstanding head. Reserve one slot to + * distinguish a full ring from an empty one. */ for (uint32_t spin = 0; spin < E1000_TX_WAIT_SPINS; ++spin) { - if (d->tx[index].status & E1000_TX_STATUS_DD) { + if ((d->tx[index].status & E1000_TX_STATUS_DD) && + (d->tx[next].status & E1000_TX_STATUS_DD)) { break; } if (spin + 1u == E1000_TX_WAIT_SPINS) { @@ -447,7 +450,8 @@ static int e1000_device_send(void *context, const void *frame, uint32_t len) } e1000_cpu_relax(); } - e1000_memcpy(d->tx_buf[index], frame, len); + __atomic_thread_fence(__ATOMIC_ACQUIRE); + __builtin_memcpy(d->tx_buf[index], frame, len); d->tx[index].length = (uint16_t)len; d->tx[index].cso = 0; d->tx[index].cmd = E1000_TX_CMD_EOP | E1000_TX_CMD_IFCS | E1000_TX_CMD_RS; @@ -455,18 +459,29 @@ static int e1000_device_send(void *context, const void *frame, uint32_t len) d->tx[index].css = 0; d->tx[index].special = 0; __atomic_thread_fence(__ATOMIC_RELEASE); - next = (index + 1u) % E1000_TX_COUNT; d->tx_tail = next; e1000_reg_write(d, E1000_REG_TDT, next); - for (uint32_t spin = 0; spin < E1000_TX_WAIT_SPINS; ++spin) { - if (d->tx[index].status & E1000_TX_STATUS_DD) { - return 0; - } - e1000_cpu_relax(); - } - return -1; + return 0; } +/** @brief Return every recycled RX descriptor to hardware in one tail update. + * @param d Active controller under network execution ownership. + */ +static void e1000_rx_refill(struct e1000_state *d) +{ + if (!d->rx_refill_count) return; + __atomic_thread_fence(__ATOMIC_RELEASE); + uint32_t tail = (d->rx_index + E1000_RX_COUNT - 1u) % E1000_RX_COUNT; + e1000_reg_write(d, E1000_REG_RDT, tail); + d->rx_refill_count = 0; +} + +/** @brief Consume one frame and amortize RX tail updates across a ready burst. + * @param context Active controller under network execution ownership. + * @param frame Writable receive buffer. @param capacity Buffer bytes. + * @param out_len Optional frame length, cleared when no data is returned. + * @return One for a frame, zero for no frame, or a negative descriptor error. + */ static int e1000_device_poll(void *context, void *frame, uint32_t capacity, uint32_t *out_len) { struct e1000_state *d=context; @@ -483,6 +498,7 @@ static int e1000_device_poll(void *context, void *frame, uint32_t capacity, uint index = d->rx_index; status = d->rx[index].status; if ((status & E1000_RX_STATUS_DD) == 0) { + e1000_rx_refill(d); return 0; } __atomic_thread_fence(__ATOMIC_ACQUIRE); @@ -492,20 +508,18 @@ static int e1000_device_poll(void *context, void *frame, uint32_t capacity, uint receive_error = len > capacity ? -90 : -74; len = 0; } - if (len > capacity) { - len = capacity; - } if (len) { - e1000_memcpy(frame, d->rx_buf[index], len); + __builtin_memcpy(frame, d->rx_buf[index], len); } d->rx[index].length = 0; d->rx[index].checksum = 0; d->rx[index].status = 0; d->rx[index].errors = 0; d->rx[index].special = 0; - __atomic_thread_fence(__ATOMIC_RELEASE); - e1000_reg_write(d, E1000_REG_RDT, index); d->rx_index = (index + 1u) % E1000_RX_COUNT; + if (++d->rx_refill_count == E1000_RX_REFILL_BATCH || + !(d->rx[d->rx_index].status & E1000_RX_STATUS_DD)) + e1000_rx_refill(d); if (out_len) { *out_len = len; } diff --git a/drivers/net/e1000e/Kbuild b/drivers/net/e1000e/Kbuild index 3af9ff00..bce8998b 100644 --- a/drivers/net/e1000e/Kbuild +++ b/drivers/net/e1000e/Kbuild @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 obj-$(CONFIG_E1000E) += e1000e.o -e1000e-y := main.o hardware.o link.o rings.o module.o +e1000e-y := main.o hardware.o link.o rings.o interrupt.o module.o include $(srctree)/scripts/Makefile.module diff --git a/drivers/net/e1000e/internal.h b/drivers/net/e1000e/internal.h index 24eac446..0b8b7538 100644 --- a/drivers/net/e1000e/internal.h +++ b/drivers/net/e1000e/internal.h @@ -14,6 +14,8 @@ #define E1K_FCAH 0x002cu #define E1K_FCT 0x0030u #define E1K_ICR 0x00c0u +#define E1K_ITR 0x00c4u +#define E1K_IMS 0x00d0u #define E1K_IMC 0x00d8u #define E1K_RCTL 0x0100u #define E1K_TCTL 0x0400u @@ -37,6 +39,7 @@ #define E1K_DRV_LOAD (1u << 28) #define E1K_SW_OWN (1u << 5) #define E1K_RX_COUNT 256u +#define E1K_RX_REFILL_BATCH 8u #define E1K_TX_COUNT 64u #define E1K_BUFFER 2048u #define E1K_MAX_FRAME 1518u @@ -72,10 +75,12 @@ struct e1k_device { volatile struct e1k_rx_descriptor *rx; volatile struct e1k_tx_descriptor *tx; uint8_t *rx_data, *tx_data; - unsigned rx_next, tx_next, tx_clean; + unsigned rx_next, rx_refill_count, tx_next, tx_clean; uint64_t carrier_tick; bool carrier_valid, carrier_up; - struct kernel_spinlock rx_lock, tx_lock, carrier_lock; + uint32_t irq_handle, irq_ifindex; + bool irq_masked; + struct kernel_spinlock rx_lock, tx_lock, carrier_lock, irq_lock; }; /** @brief Read one aligned device register through the owned UC mapping. @@ -135,4 +140,17 @@ int e1k_send(struct e1k_device *d, const void *frame, uint32_t length); * @return One for a frame, zero for an empty ring, or negative malformed/size error. */ int e1k_receive(struct e1k_device *d, void *frame, uint32_t capacity, uint32_t *length); +/** @brief Enable receive MSI on a registered controller if a vector is available. + * @param d Active device with all interrupt sources masked. + * @param ifindex Registered interface, which may still await publication. + */ +void e1k_interrupt_start(struct e1k_device *d, uint32_t ifindex); +/** @brief Rearm MSI after the receive queue drains and check for a raced frame. + * @param d Pinned controller with rx_lock held. + */ +void e1k_interrupt_complete(struct e1k_device *d); +/** @brief Mask the receive source and drain callbacks before teardown. + * @param d Owned controller with normal data callbacks already drained. + */ +void e1k_interrupt_stop(struct e1k_device *d); #endif diff --git a/drivers/net/e1000e/interrupt.c b/drivers/net/e1000e/interrupt.c new file mode 100644 index 00000000..950022be --- /dev/null +++ b/drivers/net/e1000e/interrupt.c @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "internal.h" +#include + +/* Descriptor threshold, receive overrun and receive timer. */ +#define E1K_RX_INTERRUPTS ((1u << 4) | (1u << 6) | (1u << 7)) +#define E1K_ITR_64_US 250u + +/** @brief Mask and acknowledge a receive event before queuing task-context work. + * @param context Controller pinned by the MSI lease. + */ +static void e1k_rx_irq(void *context) +{ + struct e1k_device *d = context; + uint64_t flags; + kernel_spin_lock_irqsave(&d->irq_lock, &flags); + e1k_write(d, E1K_IMC, E1K_RX_INTERRUPTS); + (void)e1k_read(d, E1K_ICR); + d->irq_masked = true; + uint32_t id = d->irq_ifindex; + kernel_spin_unlock_irqrestore(&d->irq_lock, flags); + if (id) netdev_rx_notify(id); +} + +/** @copydoc e1k_interrupt_start */ +void e1k_interrupt_start(struct e1k_device *d, uint32_t ifindex) +{ + if (!d->api->request_pci_irq || !d->api->free_pci_irq || + d->api->request_pci_irq(&d->pci, e1k_rx_irq, d, &d->irq_handle)) return; + + uint64_t flags; + kernel_spin_lock_irqsave(&d->irq_lock, &flags); + d->irq_ifindex = ifindex; + e1k_write(d, E1K_ITR, E1K_ITR_64_US); + (void)e1k_read(d, E1K_ICR); + e1k_write(d, E1K_IMS, E1K_RX_INTERRUPTS); + e1k_flush(d); + d->irq_masked = false; + kernel_spin_unlock_irqrestore(&d->irq_lock, flags); + netdev_rx_notify(ifindex); +} + +/** @copydoc e1k_interrupt_complete */ +void e1k_interrupt_complete(struct e1k_device *d) +{ + if (!d->irq_handle) return; + uint64_t flags; + uint32_t notify = 0; + kernel_spin_lock_irqsave(&d->irq_lock, &flags); + if (d->irq_masked && d->irq_ifindex) { + e1k_write(d, E1K_IMS, E1K_RX_INTERRUPTS); + e1k_flush(d); + d->irq_masked = false; + if (d->rx[d->rx_next].status & 1u) { + e1k_write(d, E1K_IMC, E1K_RX_INTERRUPTS); + (void)e1k_read(d, E1K_ICR); + d->irq_masked = true; + notify = d->irq_ifindex; + } + } + kernel_spin_unlock_irqrestore(&d->irq_lock, flags); + if (notify) netdev_rx_notify(notify); +} + +/** @copydoc e1k_interrupt_stop */ +void e1k_interrupt_stop(struct e1k_device *d) +{ + if (!d->irq_handle) return; + uint64_t flags; + kernel_spin_lock_irqsave(&d->irq_lock, &flags); + e1k_write(d, E1K_IMC, E1K_RX_INTERRUPTS); + (void)e1k_read(d, E1K_ICR); + uint32_t handle = d->irq_handle; + d->irq_handle = 0; + d->irq_ifindex = 0; + d->irq_masked = true; + kernel_spin_unlock_irqrestore(&d->irq_lock, flags); + d->api->free_pci_irq(handle); +} diff --git a/drivers/net/e1000e/main.c b/drivers/net/e1000e/main.c index 5aa206f2..882adfb4 100644 --- a/drivers/net/e1000e/main.c +++ b/drivers/net/e1000e/main.c @@ -66,6 +66,7 @@ static const struct reliefnt_netdev_ops ops={ */ static int stop_device(struct e1k_device *d) { + e1k_interrupt_stop(d); int rc=e1k_hardware_stop(d); if (rc) return rc; e1k_free_rings(d); @@ -107,11 +108,11 @@ static int start(const struct reliefos_driver_kernel_api *api) *d=(struct e1k_device){.api=api,.pci=pci,.next=devices}; devices=d; rc=e1k_hardware_start(d); if (!rc) rc=e1k_allocate_rings(d); + uint32_t ifindex; if (!rc) { uint16_t command=api->pci_read16(pci.bus,pci.slot,pci.function,4); api->pci_write16(pci.bus,pci.slot,pci.function,4,command|6u); e1k_enable_rings(d); d->active=true; - uint32_t ifindex; rc=driver_register_netdev(&ops,d,&ifindex); } if (rc) { @@ -123,11 +124,12 @@ static int start(const struct reliefos_driver_kernel_api *api) } e1k_write(d,E1K_CTRL_EXT,e1k_read(d,E1K_CTRL_EXT)|E1K_DRV_LOAD); e1k_flush(d); ++registered; + e1k_interrupt_start(d, ifindex); api->console_log(CONSOLE_LOG_INFO, - "[e1000e] %02x:%02x.%u Intel %04x:%04x MAC=%02x:%02x:%02x:%02x:%02x:%02x; link=%s\n", + "[e1000e] %02x:%02x.%u Intel %04x:%04x MAC=%02x:%02x:%02x:%02x:%02x:%02x; link=%s irq=%s\n", pci.bus,pci.slot,pci.function,pci.vendor_id,pci.device_id, d->mac[0],d->mac[1],d->mac[2],d->mac[3],d->mac[4],d->mac[5], - ready(d)?"up":"negotiating/down"); + ready(d)?"up":"negotiating/down", d->irq_handle?"msi":"poll"); } return registered ? 0 : first_error ? first_error : -19; } diff --git a/drivers/net/e1000e/rings.c b/drivers/net/e1000e/rings.c index 803aa5a4..dbf0678e 100644 --- a/drivers/net/e1000e/rings.c +++ b/drivers/net/e1000e/rings.c @@ -56,7 +56,7 @@ void e1k_enable_rings(struct e1k_device *d) uint32_t tx_policy=(1u<<24)|(1u<<16); if (d->pci.device_id==0x10d3) tx_policy|=1u<<22; /* 82574 required reserved-bit value. */ e1k_write(d,E1K_TX_BASE+0x28,tx_policy); - d->rx_next=d->tx_next=d->tx_clean=0; + d->rx_next=d->rx_refill_count=d->tx_next=d->tx_clean=0; __atomic_thread_fence(__ATOMIC_RELEASE); e1k_write(d,E1K_RX_BASE+0x18,E1K_RX_COUNT-1); e1k_write(d,E1K_TIPG,8u|(2u<<10)|(10u<<20)); @@ -102,8 +102,7 @@ int e1k_send(struct e1k_device *d, const void *frame, uint32_t length) return -11; } uint8_t *buffer=d->tx_data+index*E1K_BUFFER; - const uint8_t *input=frame; - for (unsigned i=0;itx[index].length=(uint16_t)length; d->tx[index].checksum_start=0; d->tx[index].command=0x0b; /* EOP | IFCS | RS, no checksum/segmentation offload. */ @@ -116,7 +115,19 @@ int e1k_send(struct e1k_device *d, const void *frame, uint32_t length) return 0; } -/** @brief Consume one RX descriptor, rejecting malformed and fragmented frames. +/** @brief Publish all recycled descriptors while holding the RX ring lock. + * @param d Pinned active controller. + */ +static void e1k_refill_rx(struct e1k_device *d) +{ + if (!d->rx_refill_count) return; + __atomic_thread_fence(__ATOMIC_RELEASE); + unsigned tail=(d->rx_next+E1K_RX_COUNT-1u)%E1K_RX_COUNT; + e1k_write(d,E1K_RX_BASE+0x18,tail); + d->rx_refill_count=0; +} + +/** @brief Consume one RX descriptor and batch descriptor tail notifications. * @param d Active pinned device. @param frame Writable capacity-byte output. * @param capacity Output buffer size. @param length Optional output, reset on error/empty. * @return One for a complete frame, zero if empty, or negative input/size/frame errno. @@ -132,6 +143,8 @@ int e1k_receive(struct e1k_device *d, void *frame, uint32_t capacity, uint32_t * unsigned index=d->rx_next; uint8_t status=d->rx[index].status; if (!(status&1)) { + e1k_refill_rx(d); + e1k_interrupt_complete(d); kernel_spin_unlock_irqrestore(&d->rx_lock,flags); return 0; } @@ -144,15 +157,14 @@ int e1k_receive(struct e1k_device *d, void *frame, uint32_t capacity, uint32_t * d->dropping_fragments=!(status&2); if (rc==1) { const uint8_t *buffer=d->rx_data+index*E1K_BUFFER; - uint8_t *output=frame; - for (unsigned i=0;irx[index].length=0; d->rx[index].checksum=0; d->rx[index].status=0; d->rx[index].errors=0; d->rx[index].special=0; - __atomic_thread_fence(__ATOMIC_RELEASE); - e1k_write(d,E1K_RX_BASE+0x18,index); d->rx_next=(index+1)%E1K_RX_COUNT; + if (++d->rx_refill_count==E1K_RX_REFILL_BATCH || !(d->rx[d->rx_next].status&1)) + e1k_refill_rx(d); kernel_spin_unlock_irqrestore(&d->rx_lock,flags); return rc; } diff --git a/include/reliefnt/net.h b/include/reliefnt/net.h index 8ba0acd0..cbf5c8fd 100644 --- a/include/reliefnt/net.h +++ b/include/reliefnt/net.h @@ -40,7 +40,17 @@ void net_tcp_maintenance(void); * @brief Copy the current interface configuration (IP, MAC, flags) into config; 0 on success. */ int net_get_config(struct reliefos_net_config *config); +/** @brief Pump synchronous packet work until a full idle NIC sweep or the turn budget. + * Receive drops and protocol progress keep the pump running. Task context + * under network execution ownership, including when no Ethernet NIC exists. + */ void net_poll_packets(void); +/** @brief Briefly recheck one polling NIC for a reply to a recently sent datagram. + * @param ifindex Stable outbound Ethernet NIC. IRQ-driven NICs need no recheck. + * Task context under network execution ownership. The work is bounded per + * request and globally per tick, with no sleep, allocation or retained lease. + */ +void net_poll_datagram_reply(uint32_t ifindex); /** @brief Drain IRQ-notified NICs using bounded, fair receive slices. * @param budget Maximum descriptor attempts, including drops and empty polls. * Task context with network execution ownership; full queues request another diff --git a/include/reliefnt/net_device.h b/include/reliefnt/net_device.h index 55267d11..023ed3da 100644 --- a/include/reliefnt/net_device.h +++ b/include/reliefnt/net_device.h @@ -38,6 +38,12 @@ uint32_t netdev_next(uint32_t after); * publication are retained, and no module/context pointer is queued. */ void netdev_rx_notify(uint32_t ifindex); +/** @brief Check whether a live NIC still relies on synchronous receive polling. + * @param ifindex Stable NIC identity. + * @return True for a published NIC that has never registered a receive hint. + * IRQ-driven providers notify once after arming their interrupt source. + */ +bool netdev_rx_is_polling(uint32_t ifindex); /** @brief Claim a pending visible NIC using circular index order. * @param after Previous serviced identity. @return Pending ID or zero. * Task context under network execution; consumers revalidate with netdev_poll. diff --git a/include/reliefnt/net_ipv6.h b/include/reliefnt/net_ipv6.h index 27a9a830..a9bbc7ae 100644 --- a/include/reliefnt/net_ipv6.h +++ b/include/reliefnt/net_ipv6.h @@ -121,9 +121,10 @@ void net_ipv6_link_changed(bool up); * Before initialization, state is applied later by the initialization scan. */ int net_ipv6_link_changed_on(struct net_namespace *ns, uint32_t ifindex,bool up); /** @brief Advance protocol timers and deferred loopback work in every live network. + * @return True if at least one queued loopback packet was processed. * Pins the servicing network across transport callbacks under execution ownership. */ -void net_ipv6_poll(void); +bool net_ipv6_poll(void); /** @brief Indicate receive/timer work requiring the task-context network pump. * @return True when bounded maintenance should remain enabled. */ bool net_ipv6_maintenance_pending(void); diff --git a/kernel/device/services.c b/kernel/device/services.c index ee3c7c94..8c7c70e7 100644 --- a/kernel/device/services.c +++ b/kernel/device/services.c @@ -27,7 +27,7 @@ struct netdev_binding { struct reliefnt_netdev_ops ops; void *context; uint32_t owner, ifindex; - bool published, rx_pending; + bool published, rx_pending, rx_notifies; uint8_t mac_cache[6]; struct net_proc_counters counters; }; @@ -484,13 +484,33 @@ void netdev_rx_notify(uint32_t ifindex) { bool visible=false; uint64_t flags; kernel_spin_lock_irqsave(&manager_service_lock,&flags); - for (struct netdev_binding *b=netdev_bindings; b; b=b->next) - if (b->ifindex==ifindex) { b->rx_pending=true; visible=b->published; break; } + for (struct netdev_binding *b=netdev_bindings; b; b=b->next) { + if (b->ifindex != ifindex) continue; + b->rx_notifies = true; + b->rx_pending = true; + visible = b->published; + break; + } kernel_spin_unlock_irqrestore(&manager_service_lock,flags); if (visible) kernel_deferred_schedule(DEFERRED_NET_RX); } EXPORT_SYMBOL(netdev_rx_notify); +/** @copydoc netdev_rx_is_polling */ +bool netdev_rx_is_polling(uint32_t ifindex) +{ + uint64_t flags; + bool polling = false; + kernel_spin_lock_irqsave(&manager_service_lock, &flags); + for (struct netdev_binding *b = netdev_bindings; b; b = b->next) { + if (b->ifindex != ifindex) continue; + polling = b->published && !b->rx_notifies; + break; + } + kernel_spin_unlock_irqrestore(&manager_service_lock, flags); + return polling; +} + /** @brief Claim one pending published identity in round-robin index order. * @param after Previously serviced index, or zero to start at the first NIC. * @return Copied pending index or zero, never a context or module callback. @@ -578,12 +598,14 @@ static int netdev_receive(uint32_t ifindex, void *frame, uint32_t capacity, return -19; } int ret=b->ops.poll(b->context,frame,capacity,&length); - uint64_t flags; kernel_spin_lock_irqsave(&manager_service_lock, &flags); - if (ret>0) { b->counters.rx_bytes+=length; ++b->counters.rx_packets; - proc_nic.rx_bytes+=length; ++proc_nic.rx_packets; } - else if (ret<0) { ++b->counters.rx_errors; ++proc_nic.rx_errors; - if (ret==-90 || ret==-74) { ++b->counters.rx_drops; ++proc_nic.rx_drops; } } - kernel_spin_unlock_irqrestore(&manager_service_lock, flags); + if (ret) { + uint64_t flags; kernel_spin_lock_irqsave(&manager_service_lock, &flags); + if (ret>0) { b->counters.rx_bytes+=length; ++b->counters.rx_packets; + proc_nic.rx_bytes+=length; ++proc_nic.rx_packets; } + else { ++b->counters.rx_errors; ++proc_nic.rx_errors; + if (ret==-90 || ret==-74) { ++b->counters.rx_drops; ++proc_nic.rx_drops; } } + kernel_spin_unlock_irqrestore(&manager_service_lock, flags); + } if (out_length) *out_length=length; driver_manager_service_unpin(owner); return ret; } diff --git a/net/input.c b/net/input.c index 03de5d24..d26be071 100644 --- a/net/input.c +++ b/net/input.c @@ -2,9 +2,16 @@ #include #define NET_TCP_MAINTENANCE_POLL_BUDGET 4u +#define NET_SYNC_POLL_BUDGET 32u +#define NET_RX_REPLY_MAX_POLLS 1024u +#define NET_RX_REPLY_MAX_US 180u +#define NET_RX_REPLY_TICK_US 2000u static uint64_t net_tcp_maintenance_last_tick; static bool net_tcp_maintenance_tick_valid; +static uint32_t net_poll_previous; +static uint64_t net_rx_reply_tick; +static uint32_t net_rx_reply_used_us; /** * Net process frame. @@ -51,41 +58,98 @@ static void net_process_frame(uint32_t ifindex, const uint8_t *frame, uint32_t l } } -/** - * @brief Receive one NIC frame, dispatch it, and service a bounded TCP work batch. +/** @brief Find the next live NIC in circular order. + * @param after Last visited interface, or zero at the start. + * @return Next live interface or zero when the registry is empty. + */ +static uint32_t net_poll_next(uint32_t after) +{ + uint32_t next = netdev_next(after); + return next || !after ? next : netdev_next(0); +} + +/** @brief Dispatch one polled descriptor and advance the shared NIC cursor. + * @param ifindex Next interface, or zero when no NIC is available. * @param arp_wait Optional synchronous ARP waiter. - * @param ping_wait Optional synchronous ping waiter. + * @param ping_wait Optional ICMP waiter. * @param udp_wait Optional synchronous UDP waiter. - * @param tcp_wait Optional synchronous TCP waiter. - * @note Up to four active sockets are serviced after receive dispatch even when - * no frame arrived; inactive registry entries are not scanned. + * @param tcp_wait Optional TCP waiter. + * @return True if the provider consumed a descriptor, even if it dropped the frame. */ -void net_poll_once(struct net_arp_wait *arp_wait, - struct net_ping_wait *ping_wait, - struct net_udp_wait *udp_wait, - struct net_tcp_wait *tcp_wait) +static bool net_poll_frame(uint32_t ifindex, struct net_arp_wait *arp_wait, + struct net_ping_wait *ping_wait, struct net_udp_wait *udp_wait, + struct net_tcp_wait *tcp_wait) { - net_device_retry_registration(); + net_poll_previous = ifindex; + if (!ifindex || !net_interface_is_up(NULL, ifindex)) return false; uint8_t frame[NET_FRAME_MAX]; uint32_t len = 0; - static uint32_t previous; - uint32_t ifindex = netdev_next(previous); - if (!ifindex) ifindex = netdev_next(0); - previous = ifindex; - if (ifindex && net_interface_is_up(NULL, ifindex)) { - int ret = netdev_poll(ifindex, frame, sizeof(frame), &len); - if (ret > 0 && len) { - net_packet_input_on(NULL, ifindex, frame, len); - net_process_frame(ifindex, frame, len, arp_wait, ping_wait, udp_wait, tcp_wait); - } + int ret = netdev_poll(ifindex, frame, sizeof(frame), &len); + if (ret > 0 && len) { + net_packet_input_on(NULL, ifindex, frame, len); + net_process_frame(ifindex, frame, len, arp_wait, ping_wait, udp_wait, tcp_wait); } - net_tcp_service_sockets(); - net_ipv6_poll(); + return ret > 0 || ret == -LINUX_EMSGSIZE || ret == -LINUX_EBADMSG; +} + +/** @brief Run one NIC and protocol turn for optional synchronous waiters. + * @param arp_wait Optional ARP waiter. @param ping_wait Optional ICMP waiter. + * @param udp_wait Optional UDP waiter. @param tcp_wait Optional TCP waiter. + */ +void net_poll_once(struct net_arp_wait *arp_wait, struct net_ping_wait *ping_wait, + struct net_udp_wait *udp_wait, struct net_tcp_wait *tcp_wait) +{ + net_device_retry_registration(); + (void)net_poll_frame(net_poll_next(net_poll_previous), arp_wait, ping_wait, udp_wait, tcp_wait); + (void)net_tcp_service_sockets(); + (void)net_ipv6_poll(); } +/** @copydoc net_poll_packets */ void net_poll_packets(void) { - for (unsigned i = 0; i < 32; ++i) net_poll_once(0, 0, 0, 0); + net_device_retry_registration(); + uint32_t first_idle = 0; + uint32_t id = net_poll_next(net_poll_previous); + for (unsigned turn = 0; turn < NET_SYNC_POLL_BUDGET; ++turn) { + bool progressed = net_poll_frame(id, NULL, NULL, NULL, NULL); + progressed |= net_tcp_service_sockets(); + progressed |= net_ipv6_poll(); + if (progressed) first_idle = 0; + else if (!id) break; + else if (!first_idle) first_idle = id; + id = net_poll_next(id); + if (first_idle && id == first_idle) break; + } +} + +/** @copydoc net_poll_datagram_reply */ +void net_poll_datagram_reply(uint32_t ifindex) +{ + if (!net_interface_is_up(NULL, ifindex) || !netdev_rx_is_polling(ifindex)) return; + uint64_t tick = time_ticks(); + if (tick != net_rx_reply_tick) { + net_rx_reply_tick = tick; + net_rx_reply_used_us = 0; + } + uint32_t limit = NET_RX_REPLY_TICK_US - net_rx_reply_used_us; + if (!limit) return; + if (limit > NET_RX_REPLY_MAX_US) limit = NET_RX_REPLY_MAX_US; + + uint64_t start = time_work_counter_us(); + uint64_t elapsed; + for (unsigned turn = 0; ; ++turn) { + bool received = net_poll_frame(ifindex, NULL, NULL, NULL, NULL); + elapsed = time_work_counter_us() - start; + if (received || elapsed >= limit) break; + if (turn + 1u == NET_RX_REPLY_MAX_POLLS) { + /* Even before a sub-tick clock is available, cap time spent polling. */ + elapsed = limit; + break; + } + __asm__ volatile("pause"); + } + net_rx_reply_used_us += elapsed < limit ? (uint32_t)elapsed : limit; } /** @brief Drain notified NICs in fair slices with a strict descriptor budget. diff --git a/net/internal.h b/net/internal.h index ac5219b1..f27341b2 100644 --- a/net/internal.h +++ b/net/internal.h @@ -841,9 +841,10 @@ void net_socket_acknowledge(struct net_socket *socket, uint32_t ack); /** * @brief Retry active TCP handshakes, queued data, RTOs, persist probes, and FINs. - * @note Called from each network poll pass; services at most four queued sockets. + * @return True if new sequence space or loopback was serviced, or the batch + * did not reach every active socket. One turn services at most four sockets. */ -void net_tcp_service_sockets(void); +bool net_tcp_service_sockets(void); /** * @brief Check the active TCP work queue without scanning the socket registry. @@ -877,8 +878,6 @@ void net_init(void); */ int net_is_ready(void); -void net_poll_packets(void); - /** * @brief Send raw IPv4 using the configured route and Ethernet transport. * @param destination Host-order destination IPv4 address. diff --git a/net/ipv6/core.c b/net/ipv6/core.c index 6a1741d7..6e46cd07 100644 --- a/net/ipv6/core.c +++ b/net/ipv6/core.c @@ -1483,18 +1483,21 @@ static void ipv6_loop_deliver(struct net_ipv6_state *state, struct ipv6_pending } /** @brief Advance bounded address, neighbor, listener, reassembly and deferred-loopback work. * @param state Borrowed protocol owner under network execution ownership. + * @return True if at least one queued loopback packet was processed. */ -static void ipv6_poll_state(struct net_ipv6_state *state) +static bool ipv6_poll_state(struct net_ipv6_state *state) { - if(!state->initialized)return; + if(!state->initialized)return false; for(uint32_t i=state->net_ns?0:netdev_next(0);i;i=netdev_next(i)){ struct ipv6_link *link=ipv6_link(state,i,false); bool up=net_interface_is_ready(state->net_ns, i) && !ipv6_control(state,i,NET_IPV6_DISABLE); if((link && link->up)!=up)(void)net_ipv6_link_changed_on(state->net_ns, i,up); } uint64_t now=time_uptime_ms(); + bool delivered = false; for(uint32_t i=0;ipending[i].used && state->pending[i].loopback){ - struct ipv6_pending p=state->pending[i];state->pending[i].used=false;ipv6_loop_deliver(state,&p);kernel_free(p.data);} + struct ipv6_pending p=state->pending[i];state->pending[i].used=false;ipv6_loop_deliver(state,&p);kernel_free(p.data); + delivered = true;} for(struct ipv6_link *link=state->links;link;link=link->next) if(link->up && now>=link->reachable_refresh)ipv6_refresh_reachable(link); /* Report a new solicited-node membership before sending its DAD probe. */ @@ -1552,19 +1555,22 @@ static void ipv6_poll_state(struct net_ipv6_state *state) n->value.state==IPV6_NUD_PROBE?n->value.mac:0);++n->probes;n->deadline=now+link->retrans_ms;} } } + return delivered; } /** @copydoc net_ipv6_poll */ -void net_ipv6_poll(void) +bool net_ipv6_poll(void) { + bool delivered = false; struct net_ipv6_state *state = net_ipv6_state_get(NULL); while (state) { struct net_namespace *ns = net_namespace_get(state->net_ns); net_interface_ipv4_poll(ns); - ipv6_poll_state(state); + delivered |= ipv6_poll_state(state); struct net_ipv6_state *next = state->next; /* Read the successor before final put can unlink this state. */ net_namespace_put(ns); state = next; } + return delivered; } diff --git a/net/socket/udp.c b/net/socket/udp.c index df244779..6189f8a3 100644 --- a/net/socket/udp.c +++ b/net/socket/udp.c @@ -78,6 +78,8 @@ struct udp_socket { int ifindex; int error; uint64_t receive_timeout; + uint64_t tx_tick; + uint32_t tx_ifindex; uint32_t queued; struct udp_packet *head, *tail; uint32_t errors_queued; @@ -89,6 +91,28 @@ static uint64_t proc_udp_ino, loopback_bytes, loopback_packets; static uint16_t next_port = 49152; static uint16_t swap16(uint16_t x) { return __builtin_bswap16(x); } static uint32_t swap32(uint32_t x) { return __builtin_bswap32(x); } + +/** @brief Remember a unicast Ethernet send until the next read attempt. + * @param s Execution-owned UDP socket. + * @param ifindex Outbound interface, or zero for a non-unicast send. + */ +static void udp_remember_transmit(struct udp_socket *s, uint32_t ifindex) +{ + s->tx_ifindex = !s->net_ns && ifindex > NET_IF_LOOPBACK ? ifindex : 0; + if (s->tx_ifindex) s->tx_tick = time_ticks(); +} + +/** @brief Use one short receive recheck following a recent Ethernet send. + * @param s Execution-owned UDP socket whose normal receive queue was just polled. + */ +static void udp_check_reply(struct udp_socket *s) +{ + uint32_t ifindex = s->tx_ifindex; + s->tx_ifindex = 0; + if (ifindex && !s->head && !s->error && time_ticks() - s->tx_tick <= 1) + net_poll_datagram_reply(ifindex); +} + static struct udp_socket *udp_from_file(struct task_file *file) { return file && file->kind == TASK_FILE_KIND_UDP ? (void *)(uintptr_t)file->aux : NULL; } @@ -612,6 +636,7 @@ static int udp4_send(struct udp_socket *s, uint32_t ip, uint16_t port, } net_udp_input_ex(s->net_ns, path.source, ip, s->port, port, data, length, (int)path.ifindex, (uint8_t)ttl); + udp_remember_transmit(s, 0); return (int)length; } if (multicast && (!ttl || path.ifindex == NET_IF_LOOPBACK)) ret = 0; @@ -622,6 +647,7 @@ static int udp4_send(struct udp_socket *s, uint32_t ip, uint16_t port, if (ret >= 0 && multicast && s->ipv4_multicast_loop) net_udp_input_ex(s->net_ns, path.source, ip, s->port, port, data, length, (int)path.ifindex, (uint8_t)ttl); + if (ret >= 0) udp_remember_transmit(s, !multicast && ip != UINT32_MAX ? path.ifindex : 0); return ret < 0 ? ret : (int)length; } @@ -681,6 +707,7 @@ static int udp6_send(struct udp_socket *s, const void *data, uint32_t length, ret = net_ipv6_output(s->net_ns, &path, 17, packet, length + 8, hops, to.sin6_flowinfo, s->dont_fragment || s->mtu_discover == IPV6_PMTUDISC_DO, s->multicast_loop); kernel_free(packet); + if (ret >= 0) udp_remember_transmit(s, to.sin6_addr.s6_addr[0] == 0xff ? 0 : path.ifindex); return ret < 0 ? ret : (int)length; } @@ -747,7 +774,10 @@ static int udp_recv(struct task_file *file, void *data, uint32_t length, source, source_length, info); if (s->error) { int error = s->error; s->error = 0; return -error; } net_poll_packets(); + if (!(file->flags & RELIEFOS_O_NONBLOCK) && !(flags & MSG_DONTWAIT) && + !s->receive_timeout_immediate) udp_check_reply(s); if (!s->head) { + if (s->error) { int error = s->error; s->error = 0; return -error; } if ((file->flags & RELIEFOS_O_NONBLOCK) || (flags & MSG_DONTWAIT)) return -LINUX_EAGAIN; struct task *task = sched_current_task(); uint64_t now = time_ticks(); @@ -1014,6 +1044,7 @@ short task_udp_poll(struct task_file *file, short events) struct udp_socket *s = udp_from_file(file); if (!s) return POLLNVAL; net_poll_packets(); + if (events & POLLIN) udp_check_reply(s); return (events & POLLOUT) | (s->head ? (events & POLLIN) : 0) | (s->error || s->errors_head ? POLLERR : 0); } diff --git a/net/tcp/socket.c b/net/tcp/socket.c index 54421ab0..9dae2d4f 100644 --- a/net/tcp/socket.c +++ b/net/tcp/socket.c @@ -688,25 +688,28 @@ transmit: ; net_socket_touch(socket); } -/** - * @brief Service a bounded rotating batch of active TCP sockets. - * @note The work queue contains only sockets with protocol work, so idle open - * sockets never add cost to packet polling or periodic maintenance. - */ -void net_tcp_service_sockets(void) +/** @copydoc net_tcp_service_sockets */ +bool net_tcp_service_sockets(void) { + bool progressed = net_tcp_loop_pending(); net_tcp_loop_service(); uint32_t service_limit = net_tcp_work_count; - if (service_limit > NET_TCP_SOCKET_SERVICE_BUDGET) + if (service_limit > NET_TCP_SOCKET_SERVICE_BUDGET) { service_limit = NET_TCP_SOCKET_SERVICE_BUDGET; + progressed = true; + } for (uint32_t serviced = 0; serviced < service_limit && net_tcp_work_head; ++serviced) { struct net_socket *socket = net_tcp_work_head; + uint32_t previous_seq = socket->local_seq; net_socket_work_remove(socket); net_socket_service(socket); + progressed |= socket->local_seq != previous_seq; net_socket_work_schedule(socket); } + progressed |= net_tcp_loop_pending(); net_tcp_loop_service(); + return progressed; } /** diff --git a/net/utility.c b/net/utility.c index b9e6d391..f1c7c025 100644 --- a/net/utility.c +++ b/net/utility.c @@ -15,32 +15,23 @@ void net_cpu_relax(void) #endif } -/** - * Net memcpy. - * @param dst Value supplied by the caller. - * @param src Value supplied by the caller. - * @param len Maximum number of elements available in the related buffer. +/** @brief Copy a packet field or payload with the kernel memory primitive. + * @param dst Writable destination. + * @param src Readable source that does not overlap the destination. + * @param len Exact byte length. Zero length permits null pointers. */ void net_memcpy(void *dst, const void *src, uint32_t len) { - uint8_t *d = (uint8_t *)dst; - const uint8_t *s = (const uint8_t *)src; - while (len--) { - *d++ = *s++; - } + if (len) __builtin_memcpy(dst, src, len); } -/** - * Net memzero. - * @param dst Value supplied by the caller. - * @param len Maximum number of elements available in the related buffer. +/** @brief Clear a packet field or payload with the kernel memory primitive. + * @param dst Writable destination. + * @param len Exact byte length. Zero length permits a null pointer. */ void net_memzero(void *dst, uint32_t len) { - uint8_t *d = (uint8_t *)dst; - while (len--) { - *d++ = 0; - } + if (len) __builtin_memset(dst, 0, len); } /** diff --git a/tools/test_e1000e.py b/tools/test_e1000e.py index 70aaf58f..00e548bc 100644 --- a/tools/test_e1000e.py +++ b/tools/test_e1000e.py @@ -7,7 +7,7 @@ ROOT = Path(__file__).resolve().parents[1] SOURCES = ["tools/tests/e1000e_test.c", *[ - "drivers/net/e1000e/" + name + ".c" for name in ("main", "hardware", "link", "rings")]] + "drivers/net/e1000e/" + name + ".c" for name in ("main", "hardware", "link", "rings", "interrupt")]] def main(): diff --git a/tools/tests/e1000_init_test.c b/tools/tests/e1000_init_test.c index 2adb431c..2f81e1db 100644 --- a/tools/tests/e1000_init_test.c +++ b/tools/tests/e1000_init_test.c @@ -215,11 +215,23 @@ int main(void) assert(e1000_device_is_ready(devices)); unsigned char frame[2048]; uint32_t length; + memset(frame,0x5a,sizeof(frame)); + /* The simulated device does not complete DMA until the fixture asks it to. */ + assert(e1000_device_send(devices, frame, 64)==0); + assert(*(uint32_t *)(registers+E1000_REG_TDT)==1 && + g_e1000.tx[0].status==0 && !memcmp(g_e1000.tx_buf[0],frame,64)); + for (unsigned packet=1; packetvendor_id == 0x8086 && device->slot == 3 && !irq_handler); + if (irq_error) return irq_error; + irq_handler = handler; + irq_context = context; + *handle = 21; + return 0; +} +/** @brief Require the source to be masked before destroying the lease. */ +static void free_irq(uint32_t handle) +{ + assert(handle == 21 && irq_handler && (REG(0xd8) & (1u << 7))); + irq_handler = NULL; + irq_context = NULL; + ++irq_frees; +} +/** @brief Record requests to schedule the exact published interface. */ +void netdev_rx_notify(uint32_t ifindex) +{ + assert(ifindex == 2 && irq_handler); + ++rx_notifications; +} static uint64_t read_ticks(void) { return tick; } static void log_text(enum console_log_level level, const char *format, ...) { (void)level; (void)format; } @@ -260,6 +289,17 @@ int main(void) assert(!memcmp(output,bytes,1500) && !rx[i].status && REG(0x2818)==i); } unsigned i=(rx_count*2+3)%rx_count; + for (unsigned n=0; n<10; ++n) { + unsigned slot=(i+n)%rx_count; + rx[slot].length=64; rx[slot].status=3; + } + for (unsigned n=0; n<10; ++n) { + uint32_t received=0; + assert(network->poll(network_context,output,sizeof(output),&received)==1 && received==64); + unsigned last=n<7 ? i+rx_count-1 : n<9 ? i+7 : i+9; + assert(REG(0x2818)==last%rx_count); + } + i=(i+10)%rx_count; rx[i].length=65535; rx[i].status=3; uint32_t length=99; assert(network->poll(network_context, output,sizeof(output),&length)==-90 && !length); @@ -306,6 +346,24 @@ int main(void) assert(networks[1]->poll(contexts[1],output,sizeof(output),&length)==1 && output[0]==0xb2); assert(networks[0]->poll(contexts[0],output,sizeof(output),&length)==1 && output[0]==0xa1); active_registers=0; finish(); assert(command_second==7); + struct reliefos_driver_kernel_api irq_api = api; + irq_api.request_pci_irq = request_irq; + irq_api.free_pci_irq = free_irq; + reset_fixture(); + assert(!e1000e_driver_module.init(&irq_api)); + assert(irq_handler && rx_notifications == 1 && (REG(0xd0) & (1u << 7))); + irq_handler(irq_context); + assert(rx_notifications == 2 && (REG(0xd8) & (1u << 7))); + REG(0xd0) = 0; + assert(!network->poll(network_context, output, sizeof(output), &length)); + assert(!length && (REG(0xd0) & (1u << 7))); + finish(); + assert(!irq_handler && !irq_context && irq_frees == 1); + reset_fixture(); + irq_error = -95; + assert(!e1000e_driver_module.init(&irq_api)); + assert(!irq_handler && rx_notifications == 2 && !REG(0xd0)); + finish(); puts("PASS e1000e: PCI IDs, high BAR/DMA, MAC/NVM, PHY, bounded TX, RX wrap/errors, rollback and retained failed STOP"); return 0; } diff --git a/tools/tests/ipv6_protocol_test.c b/tools/tests/ipv6_protocol_test.c index 68d9bbc4..d1bda885 100644 --- a/tools/tests/ipv6_protocol_test.c +++ b/tools/tests/ipv6_protocol_test.c @@ -171,6 +171,7 @@ uint16_t net_checksum_finish(uint32_t sum) { while(sum>>16)sum=(sum&65535)+(sum>>16);return (uint16_t)~sum; } /** @brief Return fake timer ticks. @return Tick count. */ uint64_t time_ticks(void) { return now_ms/10; } +uint64_t time_work_counter_us(void) { return now_ms*1000; } /** @brief Fetch one queued fixture NIC frame. @param frame Output. @param capacity Bytes available. * @param len Output length. @return One for a frame. */ int e1000_poll(void *frame,uint32_t capacity,uint32_t *len) @@ -181,6 +182,7 @@ int netdev_poll(uint32_t index,void *frame,uint32_t capacity,uint32_t *len) /* This fixture models poll-only NICs; IRQ admission has a separate host suite. */ uint32_t netdev_rx_take(uint32_t after) { (void)after;return 0; } void netdev_rx_notify(uint32_t index) { (void)index; } +bool netdev_rx_is_polling(uint32_t index) { return index==2; } int netdev_poll_notified(uint32_t index,void *frame,uint32_t capacity,uint32_t *len) { return netdev_poll(index,frame,capacity,len); } /** @brief Ignore packet socket mirroring. @param frame Bytes. @param length Byte length. */ @@ -203,7 +205,7 @@ void net_handle_ipv4_on(uint32_t index,const uint8_t *frame,uint32_t length,stru /** @brief No IPv4 TCP work is active. @return False. */ bool net_tcp_maintenance_pending(void) { return false; } /** @brief Ignore empty IPv4 TCP maintenance. */ -void net_tcp_service_sockets(void) { } +bool net_tcp_service_sockets(void) { return false; } #ifdef IPV6_NO_IMPLEMENTATION /** @brief Exercise the expected absent implementation failure. */ diff --git a/tools/tests/ipv6_vector_stubs.c b/tools/tests/ipv6_vector_stubs.c index 06b5d45f..ea09401c 100644 --- a/tools/tests/ipv6_vector_stubs.c +++ b/tools/tests/ipv6_vector_stubs.c @@ -1,4 +1,22 @@ +#include +#include + +/* The fixture only installs sockets, so device classification is always false. */ +struct task_file; +int task_device_is(const struct task_file *file, uint32_t kind) +{ + (void)file; + (void)kind; + return 0; +} + /* Unused fixture dependencies trap if reached. */ +int kmsg_write_record(const char *buffer, size_t length) +{ + (void)buffer; + (void)length; + __builtin_trap(); +} __attribute__((noreturn)) void task_netlink_recv(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_recv_staged(void) { __builtin_trap(); } __attribute__((noreturn)) void task_netlink_send(void) { __builtin_trap(); } diff --git a/tools/tests/net_rx_budget_test.c b/tools/tests/net_rx_budget_test.c index 2830ff66..a1380e22 100644 --- a/tools/tests/net_rx_budget_test.c +++ b/tools/tests/net_rx_budget_test.c @@ -9,7 +9,11 @@ extern void net_poll_rx_budget(uint32_t) __attribute__((weak)); static unsigned frames[2], pending[2], delivered[2], attempts, timers; static unsigned dropped; +static unsigned transmit_turns; +static unsigned arrive_after; +static uint64_t ticks, work_us; static bool down; +static bool polling; uint32_t netdev_rx_take(uint32_t after) { for (unsigned pass=0;pass<2;++pass) for (unsigned i=0;i<2;++i) @@ -17,11 +21,13 @@ uint32_t netdev_rx_take(uint32_t after) return 0; } void netdev_rx_notify(uint32_t id) { assert(id>=2 && id<=3); pending[id-2]=1; } +bool netdev_rx_is_polling(uint32_t id) { return id==2 && polling; } uint32_t netdev_next(uint32_t after) { return after<2 ? 2 : after==2 ? 3 : 0; } bool net_interface_is_up(struct net_namespace *ns, uint32_t id) { (void)ns; return id>=2 && id<=3 && !down; } int netdev_poll(uint32_t id,void *frame,uint32_t capacity,uint32_t *length) { assert(id>=2 && id<=3 && capacity>=64); ++attempts; *length=0; + if (id==2 && arrive_after && !--arrive_after) ++frames[0]; if (!frames[id-2]) return 0; --frames[id-2]; if (dropped) { --dropped; return -74; } @@ -38,13 +44,20 @@ void net_handle_arp_on(uint32_t id,const uint8_t *p,uint32_t n,struct net_arp_wa void net_handle_ipv4_on(uint32_t id,const uint8_t *p,uint32_t n,struct net_ping_wait *a, struct net_udp_wait *b,struct net_tcp_wait *c) { (void)id;(void)p;(void)n;(void)a;(void)b;(void)c; } void net_ipv6_input_on(struct net_namespace *ns, uint32_t id,const uint8_t *p,uint32_t n) { (void)ns; (void)id;(void)p;(void)n; } -void net_tcp_service_sockets(void) { ++timers; } -void net_ipv6_poll(void) {} +bool net_tcp_service_sockets(void) +{ + ++timers; + if (!transmit_turns) return false; + --transmit_turns; + return true; +} +bool net_ipv6_poll(void) { return false; } void net_device_retry_registration(void) {} bool net_device_registration_pending(void) { return false; } bool net_tcp_maintenance_pending(void) { return false; } bool net_ipv6_maintenance_pending(void) { return false; } -uint64_t time_ticks(void) { return 0; } +uint64_t time_ticks(void) { return ticks; } +uint64_t time_work_counter_us(void) { work_us+=10; return work_us; } int main(void) { if (!net_poll_rx_budget) { fputs("FAIL: budgeted IRQ receive service is unavailable\n",stderr); return 1; } @@ -58,6 +71,29 @@ int main(void) dropped=0; frames[0]=frames[1]=0; before=attempts; net_poll_rx_budget(32); assert(attempts-before==2 && !pending[0] && !pending[1]); + before=attempts; net_poll_packets(); + if (attempts-before!=2) { + fputs("FAIL: empty synchronous poll repeated already-drained NICs\n",stderr); + return 1; + } + before=attempts; transmit_turns=5; + net_poll_packets(); + assert(attempts-before==7 && transmit_turns==0); + before=attempts; frames[0]=frames[1]=40; + net_poll_packets(); + assert(attempts-before==32 && frames[0]==24 && frames[1]==24); + frames[0]=frames[1]=0; + before=attempts; net_poll_datagram_reply(2); + assert(attempts==before); /* Notification-driven devices need no recheck. */ + polling=true; arrive_after=4; + net_poll_datagram_reply(2); + assert(attempts-before==4 && !frames[0]); + for (unsigned i=0; i<16; ++i) net_poll_datagram_reply(2); + before=attempts; net_poll_datagram_reply(2); + assert(attempts==before); /* Empty polls exhaust the shared tick budget. */ + ++ticks; net_poll_datagram_reply(2); + assert(attempts>before); + before=attempts; net_poll_rx_budget(32); assert(attempts==before); net_poll_rx_budget(0); assert(attempts==before); down=true; frames[0]=1; pending[0]=1; diff --git a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c index fc8cfc33..16432cd5 100644 --- a/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c +++ b/tools/tests/task8_host_stubs/net-ioctl-user-candidate-3-net-ioctl-user-candidate-3.stub.c @@ -56,7 +56,7 @@ __attribute__((noreturn)) void net_ipv6_input_on(struct net_namespace *ns, uint3 __builtin_trap(); } /** @brief Trap if the ioctl-only fixture runs IPv6 discovery maintenance. */ -__attribute__((noreturn)) void net_ipv6_poll(void) { __builtin_trap(); } +__attribute__((noreturn)) bool net_ipv6_poll(void) { __builtin_trap(); } /** @brief Trap if the ioctl-only fixture selects an IPv6 transport route. */ __attribute__((noreturn)) int net_ipv6_route(struct net_namespace *ns, const struct in6_addr *destination, uint32_t scope, diff --git a/tools/tests/task8_inet_signal_test.c b/tools/tests/task8_inet_signal_test.c index c52d1114..16b1ec91 100644 --- a/tools/tests/task8_inet_signal_test.c +++ b/tools/tests/task8_inet_signal_test.c @@ -26,6 +26,7 @@ int task_allocate_fd(struct task *task,int minimum,struct task_file **out) int net_get_config(struct reliefos_net_config *config) { *config=(struct reliefos_net_config){.local_ip=0x0a00020f};return 0; } void net_poll_packets(void) {} +void net_poll_datagram_reply(uint32_t ifindex) { (void)ifindex; } int net_ipv4_send_udp(uint32_t s,uint32_t d,uint16_t sp,uint16_t dp,const void *b,uint32_t n) { (void)s;(void)d;(void)sp;(void)dp;(void)b;(void)n;return -LINUX_ENETDOWN; } void sched_sleep_current_until(uint64_t tick) { (void)tick;assert(0); } diff --git a/tools/tests/tcp_state_test.c b/tools/tests/tcp_state_test.c index 9e0719e4..98b6c29b 100644 --- a/tools/tests/tcp_state_test.c +++ b/tools/tests/tcp_state_test.c @@ -31,7 +31,7 @@ __attribute__((weak)) int net_ipv6_output(struct net_namespace *ns, const struct uint32_t length,int hops,uint32_t flowinfo,bool df,bool loop) { (void)ns; (void)path; (void)protocol; (void)data; (void)length; (void)hops; (void)flowinfo; (void)df; (void)loop; return ipv6_passive_options ? 0 : -LINUX_ENETUNREACH; } __attribute__((weak)) bool net_ipv6_maintenance_pending(void) { return false; } -__attribute__((weak)) void net_ipv6_poll(void) {} +__attribute__((weak)) bool net_ipv6_poll(void) { return false; } __attribute__((weak)) void net_ipv6_input(const uint8_t *frame,uint32_t length) { (void)frame; (void)length; } __attribute__((weak)) void net_ipv6_transport_proc_emit(struct text_stream *stream,const char *leaf) { (void)stream; (void)leaf; } diff --git a/tools/tests/udp_socket_test.c b/tools/tests/udp_socket_test.c index f5b3c83b..be2bbc3c 100644 --- a/tools/tests/udp_socket_test.c +++ b/tools/tests/udp_socket_test.c @@ -116,6 +116,7 @@ struct task_file *task_file_for_fd(struct task *task, int fd) int net_get_config(struct reliefos_net_config *config) { *config = (struct reliefos_net_config){.local_ip = 0x0a00020f}; return 0; } void net_poll_packets(void) {} +void net_poll_datagram_reply(uint32_t ifindex) { (void)ifindex; } #ifndef IPV6_TRANSPORT_FIXTURE __attribute__((weak)) void net_tcp6_proc_emit(struct net_namespace *ns, struct text_stream *stream) { (void)ns; (void)stream; abort(); }