# Nexus Network Membrane (Grafted LwIP)

**Status:** Experimental / Grafted (Phase 1)
**Version:** v0.1 (Hybrid Polling)
**Location:** `core/rumpk/libs/membrane`

## Overview

The Network Membrane is a userland networking stack running inside the `init` process (Subject Zero). It provides TCP/IP capabilities to the Nexus Sovereign Core by "grafting" the lightweight IP (LwIP) stack onto the Nexus ION (Input/Output Nexus) ring architecture.

This implementation follows **SPEC-017 (The Network Membrane)** and **SPEC-701 (The Sovereign Network)**.

## Architecture

### 1. The Graft (LwIP Integration)
Nexus avoids writing a TCP/IP stack from scratch for Phase 1. Instead, we compile LwIP as a static library (`libnexus.a`) linked into the userland payload.
*   **Mode:** `NO_SYS` (No OS threads). LwIP is driven by a single event loop.
*   **Memory:** Static buffers (Pbufs) managed by `ion_client`.

### 2. The Glue (`net_glue.nim`)
Bridging Nim userland and C LwIP:
*   **`pump_membrane_stack()`**: The heartbeat function. It must be called repeatedly by the main loop. It:
    *   Checks `sys_now()` for timer expiration (DHCP fine/coarse, TCP fast/slow).
    *   Polls `ion_net_rx` for inbound packets from the Kernel (NetSwitch).
    *   Injects packets into `netif->input`.
*   **`ion_linkoutput`**: The LwIP callback to send packets. Uses `ion_net_tx` to push packets to the Kernel.

### 3. Syscall Interface
LwIP requires system services provided via `libc.nim` and the `SysTable`:
*   **`sys_now()`**: Returns monotonic time in milliseconds using `rdtime` (via `syscall_get_time_ns`).
*   **`printf/abort`**: Mapped to `console_write` syscalls.

## Current Limitations (v1.1.1)

### 1. The "Busy Wait" Workaround
**Issue:** The kernel Scheduler currently lacks a hardware Timer Driver for `wfi` (Wait For Interrupt).
**Symptom:** Calling `nanosleep` (0x65) puts the fiber to sleep forever because no timer interrupt wakes the CPU.
**Workaround:** `init.nim` uses a busy-wait loop (`while sys_now() - start < 10: yield()`). This keeps the network stack responsive but results in high CPU usage.
**Fix Planned:** Implement ACLINT/SBI Timer driver in HAL.

### 2. No IP Acquisition (Ingress)
**Issue:** While Egress (DHCP DISCOVER) works and is verified, no Ingress packets (DHCP OFFER) are received.
**Suspected Cause:** VirtIO interrupts might be masked or not delegated correctly, preventing `NetSwitch` from seeing inbound traffic.

## Usage

The stack is initialized automatically by `init`:
```nim
import libs/membrane/net_glue

membrane_init()
while true:
  pump_membrane_stack()
  # Sleep/Yield
```

## Logs & Debugging
*   **Egress:** grep for `[Membrane] Egress Packet`
*   **Timers:** grep for `[Membrane] DHCP Fine Timer`
*   **Packet Dump:** Enable `LWIP_DEBUG` in `lwipopts.h` (requires recompile).
