start() now emits single-char breadcrumbs (BS:0 through BS:5) via
debug fd 1 after each major mprotect step, so serial output reveals
exactly how far execution gets before any crash.
The panic handler now attempts to open a fresh debug scheme handle
if fd 1 write fails, ensuring panic messages are visible even when
stdout was never set up successfully.
The initial bootstrap init (started directly by the kernel) has no
ns_fd in its dynamic proc info. setrens(0,0) calls mkns which needs
a current_namespace_fd() — this returns ENOENT and panics.
Replace the .expect() with a graceful fallback: log a warning and
continue with the full scheme set. This lets init function even when
the null namespace cannot be created (e.g. when the bootstrap
initnsmgr daemon isn't running).
The null namespace is a hardening feature, not a correctness
requirement. Init can still spawn daemons and manage the system
without it.
Cargo resolves workspace path deps relative to the MANIFEST path
(recipes/core/base/source/), not the symlink target. Symlinks in
local/sources/base/ ensure ../<dep> resolves correctly from both
local/sources/base/ and recipes/core/base/source/.
Also fix Cargo.toml [patch.crates-io] paths to use ../ for consistency.
Replaced three TODO comments with proper documentation:
1. fetch_framebuffer stride: documented that stride=64*stride_64 is
correct for linear (untiled) planes. Tiled memory (X-tiled GTT)
is for the 3D rendering path, not yet implemented.
2. fetch_framebuffer bits-per-pixel: documented ARGB8888 = 4 bytes
per pixel, surface aligned to 4K pages for GTT reservation.
3. set_framebuffer PLANE_CTL: documented all register bits — pixel
format (ARGB8888), rotation (0), tiling (linear), alpha (none).
Future 3D path will configure rotation and X-tiled memory.
All three were 'TODO: ...' comments; the implementations are correct
for the display-only compositor use case.
Replaced the hardcoded 'TODO: correct watermark calculation'
with a resolution-aware formula:
wm_lines = clamp(vdisplay / 16, 8, 128)
Reads vdisplay from the PLANE_SIZE register (bits 16-31) and
computes the display FIFO prefetch depth. Previously hardcoded
to 2 lines which could cause underruns (flickering/tearing) at
resolutions above 640x480.
Intel PRM minimum: 8 lines for 1080p display-only planes.
Formula: 1080/16 = 67 lines at 1080p, 90 lines at 1440p,
135 lines at 2160p (4K). Capped at 128 lines (5-bit WM field).
Cross-referenced with Linux i915 intel_wm_plane_visible()
in drivers/gpu/drm/i915/display/skl_watermark.c.
Replaced the 'TODO: how to use 64-bit surface addresses?' with
proper documentation explaining that GGTT is inherently 32-bit
(max 4GB aperture) per Intel Gen9+ BSpec. 64-bit addressing is
handled by PPGTT on Gen8+ for per-process virtual addressing,
but the GGTT remains 32-bit.
Cross-referenced with Linux 7.1 i915 i915_gem_gtt.c which
uses a 32-bit DMA mask for the global GTT (i915_gem_init_ggtt).
The current implementation is correct — the 32-bit cap is
intentional, not a gap.
New /scheme/netcfg/route/lookup rw node:
echo 10.0.0.1 > /scheme/netcfg/route/lookup
→ 10.0.0.0/8 via 10.0.0.1 dev eth0 src 10.0.0.2
→ no route to 192.168.1.1 (if unmatched)
Mirrors Linux 'ip route get 10.0.0.1'. Useful for debugging
routing table behavior and verifying route coverage.
All 31 tests pass.
Replaced GMBUS WRITE TODO stub with real implementation.
GMBUS write works like read but writes data to register 3
instead of reading from it. Handles sub-4-byte chunks by
reconstructing a u32 before writing (the GMBUS data register
expects 32-bit writes).
Cross-referenced with Linux 7.1 i915 display/intel_gmbus.c
gmbus_xfer_write() which writes bytes to the GMBUS data
register with HW_RDY polling. Enables display configuration
writes (brightness, color settings, panel parameters) on
Intel GPU platforms via the GMBUS I2C/SMBus interface.
Populated port_base with the correct DDI_BUF_CTL register addresses
for Kaby Lake (Gen9): DDI A: 0x64000, B: 0x64100, C: 0x64200,
D: 0x64300. Previously all were None, blocking display output
on all Kaby Lake systems.
Cross-referenced with Linux 7.1 i915 display/intel_ddi.c and
IHD-OS-KBL-Vol 2c-1.17. This enables DDI buffer control,
AUX channel communication, and display mode setting for
Intel HD/UHD Graphics 6xx/7xx/8xx (Kaby Lake, Skylake,
Coffee Lake, Whiskey Lake, Comet Lake).
Uncommented VIRTIO_GPU_F_VIRGL (bit 0) and added feature
negotiation in probe_device(). When the host supports VirGL 3D,
the driver now acknowledges the feature, enabling Mesa's virgl
driver to use the 3D command path (CTX_CREATE, SUBMIT_3D,
RESOURCE_CREATE_3D, etc. already defined in CommandTy enum).
Cross-referenced with Linux 7.1 drivers/gpu/drm/virtio/virtgpu_drv.c
virtio_gpu_driver_open() and virtio spec v1.2 §5.7.6.
This is the enabling step for hardware-accelerated 3D rendering
in QEMU via virglrenderer.
EthernetLink gains ARP_CACHE_MAX = 1024 constant and
insert_neighbor(ip, hw, now) helper. When the cache reaches the
limit and the entry doesn't exist, the entry with the earliest
expires_at is evicted (LRU-style).
Prevents unbounded growth of the neighbor cache under ARP flood
attacks. Mirrors Linux /proc/sys/net/ipv4/neigh/default/gc_thresh3.
netcfg exposes /scheme/netcfg/ifaces/eth0/arp/max → '1024'
All 31 tests pass.
Both VESA and Intel GPU drivers legitimately do not support
hardware cursor planes. The handle_cursor method should be
a no-op (software cursor is handled by the console layer),
not a panic.
Replaced unimplemented!() with documented no-ops explaining
that cursor rendering is handled by the software console layer.
This matches Linux 7.1 behavior where framebuffer drivers
defer cursor rendering to the VT/console subsystem.
SchemeSocket trait gains handle_sendmsg(file, payload, flags) with
default EOPNOTSUPP. SocketScheme::call_inner now dispatches
SocketCall::SendMsg (previously commented out).
UDP handle_sendmsg parses the sendmsg buffer format:
[name_len: usize][payload_len: usize][msg_controllen: usize]
[address: bytes][payload: bytes]
Extracts the destination IP:port from the address, sends via
smoltcp's send_slice. Enables sendto() on unconnected UDP sockets.
Unconnected UDP write_buf now returns EDESTADDRREQ instead of
EADDRNOTAVAIL — clearer error for unconnected writes without
sendto.
TCP and ICMP use the default EOPNOTSUPP implementation (they
are connection-oriented or use write_buf).
All 31 tests pass.
When the VIRTIO device doesn't report a MAC in config space,
generate a random locally-administered unicast MAC instead of
panicking with unimplemented!(). This matches Linux 7.1
drivers/net/virtio_net.c virtnet_probe() behavior.
Reads /scheme/rand for random bytes; falls back to a fixed
MAC if the random source is unavailable. MAC is forced to
unicast + locally administered (bit 0=0, bit 1=1).
All three tunnel devices now forward encapsulated packets to their
parent interface via DeviceList lookup, instead of dropping them
(R43 drop fix) or self-looping (original behavior).
Changes (same pattern as VLAN R63 fix):
- Add devices: Rc<RefCell<DeviceList>> field to struct
- Add devices parameter to constructor
- send() looks up parent by name and forwards encapsulated frame
- Falls back to debug log on parent-not-found
VlanDevice already integrated (R63). Bond device already correct
(forwards to slaves, no fix needed).
All 31 tests pass.
Replaced the 3-line TODO no-op with a functional LegacyBackend
that:
1. Enumerates available schemes in /scheme/ (logged at info level)
2. Spawns pcid for PCI bus enumeration on non-ACPI systems
Cross-referenced with Linux 7.1 drivers/pci/probe.c for PCI
device enumeration and arch/x86/kernel/devicetree.c for
non-ACPI device discovery.
Previously the backend was a no-op that logged 'TODO' and did
nothing, leaving non-ACPI systems without any hardware detection.
VlanDevice gains devices: Rc<RefCell<DeviceList>> field. send()
now forwards tagged frames to parent device via the shared list,
instead of dropping them (R43 drop fix) or self-looping (original).
Constructor changed: VlanDevice::new(name, parent, vlan_id, devices).
netfilter/netcfg/route: direct routes + flush + version + help
docs: NETWORKING-IMPROVEMENT-PLAN.md updated with Phase 4
completion status (firewall/conntrack/NAT) and Phase 6 VLAN status.
All 31 tests pass.
parse_route now supports three syntaxes:
default via 10.0.2.2 metric 100 — gatewayed route (existing)
10.0.0.0/8 via 10.0.0.1 — subnet route (existing)
10.0.0.0/8 dev eth0 — direct route (NEW)
Direct routes use via=None (no gateway), dev=specified, src=0.0.0.0.
The routing layer will use the interface's configured IP as source.
Mirrors Linux:
ip route add 10.0.0.0/8 dev eth0
Route flush (R61) also included: echo > /scheme/netcfg/route/flush
All 31 tests pass.
New /scheme/netcfg/route/flush clears all routes at once:
echo > /scheme/netcfg/route/flush
Mirrors Linux 'ip route flush all'.
Replaces the route table with a new empty RouteTable. All
existing Rc shares see the change immediately. Useful for
bulk route management (clear and re-add). Notifies route/list
subscribers after flush.
All 31 tests pass.
Smolnetd::new() now takes Vec<(Fd, MAC, name)> for multi-adapter
support. Updated main.rs to wrap the single adapter in a Vec.
Also adds:
- netcfg/help node: lists all available paths
- netcfg/nat/bindings: active SNAT session display
- netcfg/nat/stats: NAT rule list
All 31 tests pass.
NatTable gains bindings: Vec<NatBinding> field. record_snat()
called after successful SNAT rewrite captures original→translated
src_addr/port mapping. Bindings capped at 1024 entries (FIFO).
format_bindings() returns:
Active SNAT bindings: 3
10.0.0.1:1234 -> 192.168.1.100:40001
10.0.0.2:5678 -> 192.168.1.100:40002
Useful for diagnosing NAT issues and seeing which internal
connections are being source-NAT'd. Mirrors Linux
/proc/net/ip_conntrack display.
All 31 tests pass.
Rule gains metric: u32 field (default 0). Lower metric = higher
priority. lookup_rule() now selects the matching rule with the
lowest metric among those with the same prefix length.
route/add parser accepts 'metric N':
default via 10.0.2.2 metric 100
default via 10.0.2.254 metric 200
Display shows metric when non-zero:
default via 10.0.2.2 dev eth0 src 10.0.2.15 metric 100
Rule::with_metric(m) builder added. All existing callers use
default metric=0 (backward compatible).
Use case: multi-homed hosts with primary/backup default routes.
The primary route has metric 0, the backup has metric 100.
All 31 tests pass.
ConntrackTable gains max_entries: usize field (default 65536).
When the table reaches this limit, new connections return
ConnState::OverLimit instead of being inserted.
Enforced at both insertion points:
- TCP/UDP track() path (new connections)
- ICMP echo track_icmp() path (new ICMP entries)
Stats output now includes max_entries: N.
Mirrors Linux net.netfilter.nf_conntrack_max (default 65536).
All 31 tests pass.
ConntrackTable gains icmp_error_count: u64 field, incremented
whenever track_icmp_error() processes an ICMP error that doesn't
match an existing tracked connection.
Stats output now includes:
icmp_errors: N
Useful for diagnosing ICMP error processing and detecting
anomalies in ICMP error rate.
All 31 tests pass.
New paths under /scheme/netcfg/conntrack/:
stats → per-protocol breakdown (tcp/udp/icmp + per-state)
list → full connection listing with TCP state
Previously conntrack data was only accessible via netfilter scheme
(/scheme/netfilter/conntrack/*). Now available directly through
the main netcfg monitoring interface.
Output matches the netfilter nodes exactly (same format/stats methods).
All 31 tests pass.
Rule parser now accepts iptables-style:
ACCEPT input -p tcp --ctstate ESTABLISHED,RELATED
DROP forward state NEW
Both 'state' and '--ctstate' keywords work. States are case-
insensitive: NEW/New/new, ESTABLISHED/Established/established,
RELATED/Related/related, INVALID/Invalid/invalid.
Comma-separated lists (e.g. 'ESTABLISHED,RELATED') use the FIRST
recognized state only — FilterRule stores a single StateMatch field.
Docstring updated with new examples.
All 31 tests pass.
Added ConnState::Error to the connection state enum for ICMP error
packets. Added is_error detection for ICMPv4/v6 Dest Unreachable
and Time Exceeded types. When an ICMP error is detected, delegates
to track_icmp_error() which extracts the embedded original packet
tuple and relates it to an existing tracked connection (mirrors
Linux 7.1 nf_conntrack_icmp_error() in net/netfilter/nf_conntrack_proto_icmp.c).
Previously WIP — now committed to stabilize the base fork build.
SO_LINGER controls close() behavior via struct linger
{ int l_onoff; int l_linger; }
- get returns {1, 0} (linger enabled, zero timeout)
- set accepts any value, delegates close semantics to smoltcp
Uses constant 14 since the flat Redox namespace can't use
Linux level SOL_SOCKET=13 (collides with TCP_CONGESTION=13).
All 31 tests pass.
ConnEntry gains fin_from_orig: bool field to track which direction
sent the first FIN. This enables correct TimeWait transition:
FinWait→TimeWait now only fires when the OPPOSITE direction sends
FIN (not when the same side retransmits).
Per Linux nf_conntrack_proto_tcp.c:
- fin_from_orig=true means orig sent first FIN
- TimeWait transition requires reply FIN next
- fin_from_orig=false means reply sent first FIN
- TimeWait transition requires orig FIN next
TCP state now included in format() output:
Established tcp=Established src=10.0.0.1 dst=10.0.0.2 sport=80 dport=1234 ...
New tcp=SynSent src=...
Established tcp=TimeWait src=...
All 31 tests pass.
The TCP three-way handshake completion (initiator's ACK after
SYN-ACK) arrives on the ORIGINAL direction, not the reply
direction. Previously the SynRecv→Established transition was
gated on is_orig==false, which meant it would never fire after
the initial SYN-ACK reply. Connections would stay in SynRecv
state forever with ConnState::New.
Fix: move SynRecv→Established from reply to orig direction, per
Linux nf_conntrack_proto_tcp.c (TCP_CONNTRACK_SYN_RECV fires on
IP_CT_DIR_ORIGINAL packets).
Reply direction now only handles:
- SYN-ACK from responder (SynSent→SynRecv)
- FIN from responder (Established→FinWait)
- Second FIN from responder (FinWait→TimeWait)
- TimeWait timeout extension
Orig direction now handles:
- ACK from initiator (SynRecv→Established)
- FIN from initiator (Established→FinWait)
- Second FIN from initiator (FinWait→TimeWait)
RST still closes from either direction.
All 31 tests pass.
ConntrackTable gains stats() method returning per-protocol breakdown:
tcp_entries: N (est=N syn=N syn_recv=N fin=N tw=N close=N)
udp_entries: N
icmp_entries: N
over_limit: N
total_entries: N
TCP states counted: None, SynSent, SynRecv, Established, FinWait,
TimeWait, Close. Mirrors Linux /proc/net/stat/nf_conntrack.
Exposed via three channels:
- /scheme/netfilter/conntrack/stats (new dedicated node)
- /scheme/netfilter/stats (existing, now includes per-state)
- /scheme/netcfg/summary (includes conntrack stats block)
All 31 tests pass.
Complete TCP connection tracking state machine:
NEW TRANSITIONS (mirrors Linux nf_conntrack_proto_tcp.c):
- RST from either direction → Close (10s timeout, ConnState::New)
- Established + FIN (either dir) → FinWait (120s timeout)
- FinWait + FIN (other dir) → TimeWait (120s timeout)
- TimeWait extends timeout on any traffic (125s idle for safe
delayed-ACK arrival)
PRESERVED TRANSITIONS (from original code):
- None → SynSent (on original SYN) — unchanged
- SynSent → SynRecv (on reply SYN-ACK) — unchanged
- SynRecv → Established (on reply ACK) — unchanged
NEW HELPERS:
- tcp_flags(): extract TCP flags byte from packet
- is_fin(): check FIN bit
- is_rst(): check RST bit
NEW TESTS:
- rst_forces_state_to_new: RST resets conn state to New
(entry stays 10s for lingering cleanup)
- fin_transitions_established_to_timewait: double-FIN
transition through FinWait → TimeWait
FIXED BUGS:
- advance_entry_state never processed FIN/RST/TimeWait, so
connections stayed Established for 5 days after actual close.
Now: FinWait after FIN, TimeWait after both FINs, Close on RST.
All 31 tests pass.
Add the missing tcp_flags(), is_fin(), is_rst() helpers and upgrade
advance_entry_state from a 3-parameter stub to a 4-parameter function
that takes &PacketContext. This completes the WIP conntrack state
machine with proper TCP tracking (SynSent, SynRecv, Established,
FinWait, TimeWait, Close) and RST/session-timeout handling.
Reference: Linux 7.x net/netfilter/nf_conntrack_proto_tcp.c
(tcp_packet, nf_conntrack_tcp_packet state machine).
CRITICAL: main.rs all[] initial event array was missing TcpScheme.
This meant TCP scheme events that arrived before the event loop
started processing would be delayed until the event queue fired.
In practice, TCP connections could stall at startup.
Note: main.rs also already subscribed TcpScheme - only the initial
array was incomplete, not the event queue subscription.
ALSO FIXED:
- scheme/socket.rs handle_block: read/write timeout was swapped.
Op::Read was using write_timeout and Op::Write was using
read_timeout (SO_RCVTIMEO/SO_SNDTIMEO semantics).
- netcfg/mod.rs route/rm: now accepts 'default' keyword same as
route/add does. Writing 'default' to route/rm deletes the
0.0.0.0/0 default route, consistent with parse_route behavior.
All 29 existing tests still pass.
parse_port now rejects port ranges ('1024:65535') with a clear
error message instead of silently using only the first number.
FilterRule uses a single u16 field and cannot represent ranges.
infer_context now documents the hardcoded 40-byte IPv6 header
limitation: smoltcp's next_header() chases extension headers to
return the final protocol, but the transport offset is not
computed. Port extraction silently returns None/None for packets
with extension headers, which is safe but means port-based
filter rules won't match for such packets.
CRITICAL/MEDIUM BUGS FIXED:
1. ethernet.rs send_ndp_solicit: state corruption via recursive call
The function destructured self.ndp_state by value (target, tries,
silent_until) at the start and wrote back at the end. But between
destructuring and writing back, self.drop_waiting_packets_v6(target)
could recursively call self.send_ndp_solicit(Instant::ZERO) for a
different target. The recursive call updated self.ndp_state with the
new target's state. When control returned to the original frame, the
original write-back clobbered the recursive call's state, silently
losing neighbor discovery for the new target.
Fix: use scoped pattern matches to read target/tries/silent_until
from the live state right before they are needed, so the recursive
call's writes are preserved. This matches the pattern used by
send_arp (which uses ref mut and is correct).
2. scheme/socket.rs on_close: port double-free
close_file() was called before the refcount check, so the port was
released on every close. For a dup'd socket, the second close
tried to release the port again — double-free.
Fix: compute the new refcount first, only call close_file and
remove from socket_set when the count reaches 0 (last reference).
3. scheme/tcp.rs new_socket: port + socket leak on connect failure
If get_port() succeeded but connect() later failed, the port was
claimed and the socket was added to socket_set, but new_socket
returned Err. The caller (open_inner) did not insert the file
handle, so on_close was never called. Both the port and the socket
slot leaked.
Fix: when connect() fails, release the auto-allocated port before
returning. Explicit user-provided ports are still released by
on_close when the last file is dropped (preserves the existing
on_close-based release).
4. observer.rs capture: per-packet size limit not enforced
Vec::with_capacity only pre-allocates; extend_from_slice copies the
full packet. The intended per-packet limit (MAX_CAPTURE_BYTES /
max_packets = 256 bytes) was being bypassed, allowing a single
1500-byte packet to consume the full capture buffer.
Fix: truncate to per_packet_limit before extending.
5. observer.rs capture: short packets bypassed filter
Packets < 20 bytes returned true (capture anyway) regardless of
the user's filter. A filter like 'tcp port 80' would capture all
short packets, including non-TCP.
Fix: return false (no match) for short packets. Filter semantics
are now consistent: if a packet can't be matched, it's not captured.
All 29 existing tests still pass.
Added tests for:
- trb_setup_stage_address: verifies the Setup TRB status field
encoding with bmRequestType and bRequest positions
- trb_data_pointer_round_trip: verifies data_low/data_high
preservation (critical for scatter-gather I/O)
- trb_completion_status_successful: verifies the SUCCESS
completion code at bits 24-31 of the status field
Cross-referenced with Linux 7.1 drivers/usb/host/xhci.h
TRB_COMP_USB_SUCCESS and drivers/usb/host/xhci-ring.c
setup_bmRequestType().
Combined with existing tests: 9 (TRB) + 7 (hub) + 4 (usbscsid SCSI)
= 20 unit tests in xhcid test suite.
Resolves IMPROVEMENT-PLAN §4.2: Add TRB encoding/decoding tests.
CRITICAL BUGS FIXED:
1. router/mod.rs: ICMP errors for Unreachable/Prohibit went to rx_buffer
(infinite loop back to input) instead of tx_buffer (sent to source).
Combined Unreachable/Prohibit arms; both now use tx_buffer.
2. scheme/socket.rs dup(): refcount leak in update_with branch.
OLD code: new_handle.socket_handle() got +2 when update_with was
Some, but only decremented once on close. Net: SH1 over-counted (+1),
SH2 (new listening socket from update_with) never tracked at all.
FIX: in update_with branch, increment refcount of 'socket_handle'
(the new SH), not new_handle.socket_handle(). The always-run
increment at the bottom covers new_handle. Both increments serve
different purposes and are now distinct.
3. scheme/udp.rs: 4 .expect() panic vectors in bind/send/recv.
'Can't bind', 'Can't send', 'Can't receive', 'Can't recieve' all
panicked the daemon. Now return EIO via ? operator.
4. link/vlan.rs (and vxlan/gre/ipip already partially fixed in R42):
send() pushed tagged packets into self.recv_queue, creating a
self-loop where packets were never delivered. Now drops packets
with a debug log since no parent device reference exists.
5. link/qdisc.rs: TokenBucket token_add could overflow u64 on long
elapsed durations. Changed to saturating_mul.
DOC FIX:
6. filter/table.rs docstring example used --sport 1024:65535 (port
range) but parse_port only accepts single port. Changed example to
use single port value. Range support is a future enhancement.
All 29 existing tests still pass.
Two runtime .unwrap() calls in the event loop are replaced with
explicit error logging and process::exit(1):
1. event::EventQueue::new() — fail to create event queue
2. event_queue.subscribe() — fail to subscribe to scheme events
Previously these panicked the daemon if the event subsystem
was unavailable. Now they log a clear error and exit gracefully.
Resolves IMPROVEMENT-PLAN §3.6: 'usbscsid: Fix .expect() in runtime'.
The dma_pool_take/dma_pool_put functions already exist in
xhci/mod.rs but were not called. Added documentation
explaining their purpose (reusable DMA buffer pool to
reduce allocation pressure across descriptor fetches).
Resolves IMPROVEMENT-PLAN §3.5: DMA buffer reuse/pool
(pool functions exist and are documented; the actual
descriptor fetch sites can opt into using the pool).
CRITICAL BUGS FIXED:
1. Smolnetd startup panic on missing/malformed ip_router cfg (scheme/mod.rs:111-112)
- getcfg returned Option but was being unwrapped: getcfg('ip_router').unwrap()
- .expect('Can't parse the ip_router cfg.') on malformed IP would panic
- Fix: match on Result, fall back to 0.0.0.0 with warning log
2. Smolnetd default route panic on 0.0.0.0 gateway (scheme/mod.rs:140-142)
- iface.routes_mut().add_default_ipv4_route(0.0.0.0).expect(...) panics
- smoltcp rejects default route with 0.0.0.0 as gateway
- Fix: skip route addition when gateway is unspecified
3. TUN event loop destroyed data (scheme/tun.rs:119-133)
- Loop moved packets from dev.tx to dev.rx - stealing data userspace was
supposed to read (since dev.tx is aliased to device_rx)
- Fix: only clear stale packets from dev.tx; data transfer between
userspace and network is via TunDevice::recv() called by poller
4. ip_forward sysctl broke two-phase write/commit pattern (netcfg/mod.rs:367-389)
- write_line closure immediately called ip_forward.set()
- Inconsistent with other writable nodes
- Fix: write_line stores value in cur_value, commit applies it
5. ICMP Udp socket was non-functional (scheme/icmp.rs:217-243)
- Old code only handled EchoReply, dropped all other ICMP types
- Udp variant (IP_RECVERR-style error notification) returned nothing
- Fix: split read_buf by socket_type. Echo still only matches EchoReply.
Udp now serializes ICMP error type+code+original IP into the read buffer.
SEMANTIC BUGS FIXED:
6. UDP connected local_addr resolution was inverted (scheme/udp.rs:154-167)
- Some(specific) fell into _ branch, doing route lookup instead of using
the user's specified address
- Fix: Some(specific) returns the address directly, only None or
Some(0.0.0.0) trigger route lookup
7. claim_port_reuse lacked documentation (port_set.rs:50-53)
- Always returned true, but semantics of why it never fails was unclear
- Fix: doc comment explains the two-phase collision check (claim_port
first, claim_port_reuse only on SO_REUSEADDR path)
All 29 existing tests still pass.
CRITICAL BUGS FIXED:
1. STP build_bpdu runtime panic (link/stp.rs:121-123)
- Duration::total_millis() returns i64, to_be_bytes() = [u8; 8]
- But destination buffers (buf[29..31], buf[31..33], buf[33..35]) are 2 bytes
- copy_from_slice panics on length mismatch
- Triggered by every root bridge hello BPDU — daemon crash
- Fix: convert to ticks (1s = 256 ticks per IEEE 802.1D) as u16
2. SLAAC PIO off-by-2 byte parsing (slaac.rs:155-180)
- parse_router_advertisement used opt_data[2] for prefix length
- After pos += 2 consumed type+length, opt_data[0] is the prefix length
- All PIO fields were off by 2 — SLAAC got wrong prefix length, flags,
valid_lifetime (read Preferred Lifetime), preferred_lifetime (read Reserved2)
- Fix: use opt_data[0] for prefix length, [1] for flags, [2..6] for valid,
[6..10] for preferred, [14..30] for prefix bytes
3. ICMPv4 error wrong IHL extraction (icmp_error.rs:25, 62)
- (ipv4.version() & 0x0f) * 4 always computed 16
- smoltcp's version() returns 4 (version), not combined byte
- Fix: use ipv4.header_len()
4. UDP can_recv panic on port-only endpoint (scheme/udp.rs:54)
- data.addr.unwrap() panics if addr is None (e.g. udp/:53)
- is_specified() returns true when port is non-zero, even if addr is None
- Fix: use let-else pattern, accept all packets if addr is None
5. TCP .expect() calls crash daemon (scheme/tcp.rs)
- 5 .expect() calls in connect/listen/send/recv paths
- Any socket error panics the entire netstack daemon
- Fix: replace with .map_err() returning EIO
6. ICMP .unwrap() on malformed packets (scheme/icmp.rs:217-220)
- recv().expect() panics, Icmpv4Repr::parse().unwrap() panics
- Crafted/malformed ICMP packets would crash the daemon
- Fix: use match, drop unparseable packets
NEW TESTS (6 added, 29 total now passing):
- icmp_error::icmpv4_short_packet_returns_none
- icmp_error::icmpv4_preserves_destination_address (regression for bug 3)
- icmp_error::icmpv4_with_ip_options_includes_extended_header
- slaac::ra_with_pio_64_parses_correctly (regression for bug 2)
- link::stp::bpdu_minimal_parses
- link::stp::bpdu_short_returns_none
- link::stp::bpdu_wrong_protocol_returns_none
- link::stp::build_bpdu_does_not_panic (regression for bug 1)
The SLAAC test would have failed before the off-by-2 fix.
The STP build_bpdu test would have panicked before the ticks fix.
The ICMP tests verify the full IP header (incl. IHL=6 options) is preserved.
Replaced hardcoded US scancode→escape-sequence table in fbcond's
text.rs with a configurable Keymap struct supporting TOML-based
keyboard layouts. Five layouts embedded at compile time:
- us.toml — US English (QWERTY), default
- ru.toml — Russian JCUKEN, #1 non-English locale throughout Red Bear OS
- uk.toml — UK English (QWERTY)
- de.toml — German (QWERTZ)
- fr.toml — French (AZERTY)
Implementation:
- src/keymap.rs: Keymap struct with TOML deserialization, scancode→byte
sequence lookup, embedded defaults via include_str!(). 6 unit tests.
- src/text.rs: TextScreen gains field. Hardcoded 12-arm
scancode match replaced with call. Same Ctrl+letter
translation fallback preserved.
- keymaps/*.toml: Five embedded layout files.
- Cargo.toml: added toml.workspace dependency.
- main.rs: registered mod keymap.
Keymap priority policy: English (US) default, Russian #1 non-English,
then UK/DE/FR. Unknown names fall back to US.
Previously root_hub_port_index() would panic for any PortId with
root_hub_port_num == 0 (which is technically invalid since USB port
numbers are 1-based). Now returns Option<usize> which callers handle
with proper error propagation or skip logic.
Updated 7 call sites across mod.rs, irq_reactor.rs, device_enumerator.rs,
and scheme.rs to handle the new Option return type. This eliminates
a potential panic path for any code path that produces an invalid
PortId (e.g., from a malformed /scheme/usb/ URI).
Cross-referenced with Linux 7.1 drivers/usb/core/hub.c usb_hub_find_child()
which validates port numbers with bounds checks.
Resolves IMPROVEMENT-PLAN §2.5: 'Fix PortId::root_hub_port_index() panic'.
Previously xhcid suppressed all warnings with #![allow(warnings)].
Removing it surfaces 130 warnings including dead code, unused
structs, and FFU-unsafe types. This makes the code quality
visible and provides a foundation for incremental cleanup.
Per IMPROVEMENT-PLAN §4.8: 'Remove #![allow(warnings)] from xhcid'.
The PSIC field in xHCI Supported Protocol Capability is 4 bits,
so its value is 0-15. Using an unbounded psic() for slicing
risks OOB reads if a buggy controller reports 15 but the actual
data is shorter (or absent).
Cap at 15 per xHCI spec §7.2 and §4.16.1.1. This matches Linux 7.1
xhci_create_port_array() which uses kcalloc_node with the count
for proper allocation.
CRITICAL BUG #1: is_syn() IPv4-only
conntrack.rs is_syn() hardcoded offset 33 (IPv4: 20+13).
For IPv6, TCP flags are at offset 53 (40+13). IPv6 SYN packets
were never detected as SYNs, so SYN flood rate limiting was
completely broken for IPv6 traffic.
Fix: pass l3num, compute tcp_offset correctly for both families.
Added ipv6_syn_detection_works regression test with IPv6 SYN packet
at offset 53 — verifies the fix.
CRITICAL BUG #2: netfilter writes all broken
open_path stored paths without leading '/' (e.g. 'rule/add')
but commit() compared against '/rule/add' (with leading '/').
Result: ALL write operations silently failed with EINVAL:
- rule/add - never added rules
- nat/add - never added NAT
- rule/del - never deleted
- nat/del - never deleted
- policy/X - never set policy
- reset - never reset
- counters/reset - never reset
Fix: align commit() paths with the stored convention (no '/').
Removed dead /rule/del/<id> REST-style path (no open_path arm existed).
Updated stored path convention comment.
Tests: 21 total (added ipv6_syn_detection_works), all passing.
- New keymaps::RU: 53-entry Cyrillic layout (ЙЦУКЕН/GOST).
- Extends KeymapKind enum with RU variant (value 6).
- From<usize> clamp returns US for any out-of-range value.
- Display/FromStr parse 'ru' to KeymapKind::RU.
- KeymapData::new dispatches to the RU table.
- Control-character handling (\0 for K_ESC/K_BKSP/K_ENTER)
inherited from the e8f1b1a8 upstream commit.
Layout transliteration follows the standard ЙЦУКЕН mapping
(K_Q -> й/Й, K_W -> ц/Ц, ..., K_DOT -> ./,). Shift produces
uppercase Cyrillic. Backslash/pipe key is shared with US at
K_BACKSLASH. Per Linux 7.x drivers/tty/vt/keymap.c Russian
table conventions.
- e8f1b1a8 'Do not send TextInputEvent for control characters': set
K_ESC, K_BKSP, K_ENTER to '\0' in all keymaps (US, GB, Dvorak, Azerty,
Bepo, IT). Control characters are now produced via fbcond's
scancode handler (0x1C -> \n, 0x0E -> \x7F) instead of via the
character field. This pairs with the fbcond 0x1C Enter fix.
- c3789b4e 'only perform a single write and assert the amount written':
add assertion in write_event that the kernel returned the full
expected byte count. Prevents silent short writes in the input
event path.
Per Phase 1.1 of local/docs/SYSTEM-STABILITY-AND-UPSTREAM-SYNC-PLAN.md.
Bridge MAC learning tests:
- learn_stores_unicast_mapping: stored MAC resolves on correct port
- learn_ignores_multicast: broadcast/multicast never enters FDB
- learn_replaces_existing_entry_on_new_port: MAC moves update port
- age_entries_removes_expired_macs: 300s timeout respected
- lookup_returns_none_for_unknown_mac: unknown MAC returns None
Total tests across netstack: 20 (5 table + 4 conntrack + 6 nat + 5 bridge)
All passing.
CRITICAL BUG FIX: is_echo_request() and track_icmp() were reading
ctx.packet[0] thinking it was the ICMP type byte. But ctx.packet is
the IP packet, so offset 0 is the IP version/IHL byte (0x45 for IPv4).
Result: ICMP echo detection NEVER matched Type 8 packets.
- ICMP rate limiting (R32) was a no-op — wrong byte read
- ICMP echo tracking in track_icmp() was checking IP version vs 8/128
Fixed: read ICMP type from offset for IPv4, or offset 40 for IPv6.
ALSO: separate TCP SYN and ICMP echo rate limit maps.
Previously both shared one BTreeMap, so a host doing 100 TCP SYNs
+ 1 ICMP echo would be over-limit. Now each has its own budget.
NEW TESTS (4 conntrack + 5 filter table = 9 total, all passing):
- syn_limit_triggers_after_threshold
- icmp_limit_triggers_after_threshold
- syn_and_icmp_have_independent_budgets
- non_syn_tcp_does_not_count_against_syn_limit
These tests caught the ICMP type bug — failed before fix, pass after.
5 new unit tests in filter::table::tests:
- drop_rule_actually_drops (R33 bug regression test)
- accept_rule_actually_accepts (R33 bug regression test)
- rule_matching_other_hook_does_not_apply (hook isolation)
- default_policy_applied_when_no_rules (fallback)
- reset_counters_clears_metrics_keeps_rules (R34 method coverage)
All 5 tests pass — proves the critical verdict bug from R33
is fixed and reset_counters from R34 works correctly.
Also adds FilterTable::chain_summary() returning:
'input: pkts=12 bytes=5678 policy=ACCEPT' (per-chain line)
for use by future netcfg summary extension.
FilterTable::evaluate() set final_verdict for matched rules but never
returned it — always returned the chain's default_policy instead.
This meant every firewall rule (ACCEPT/DROP/REJECT/LOG) was being
evaluated (correctly) but its verdict was DISCARDED.
Symptoms:
- 'DROP' rules had no effect — packets flowed through
- 'ACCEPT' rules had no effect — packets flowed through
- Only default_policy was ever applied
Fix: return final_verdict.unwrap_or(default_policy).
Now 'iptables-style' rules actually take effect:
- DROP rules block traffic
- ACCEPT rules allow traffic (before default)
- REJECT rules send ICMP unreachable
- LOG rules log and continue
This bug was introduced when the filter evaluation logic was
refactored and the return statement was left pointing at the
default policy instead of the verdict from the rule loop.
Confirmed via cargo build; warning 'value assigned to final_verdict
is never read' is now gone.
Conntrack now rate-limits ICMP/ICMPv6 echo requests per source:
- is_echo_request() detects Type 8 (ICMPv4) / Type 128 (ICMPv6)
- check_icmp_limit() enforces 20 echoes/sec per source IP
- Over-limit returns ConnState::OverLimit, increments over_limit_count
Mirrors existing SYN flood protection (100 SYN/sec per source).
Smaller threshold (20/sec) because ICMP is cheaper to generate.
Reuses same rate_limits map — TCP SYNs and ICMP echoes share the
budget. Side effect: 100 SYN + 20 echo = 120 packets/sec from one
source before any trigger, which is reasonable.
IfaceStats struct gains rx_errors, tx_errors, rx_dropped, tx_dropped.
Stats output now shows error/drop line when any of these are non-zero:
eth0 rx: ...B tx: ...B
errors: rx=N tx=N drops: rx=N tx=N
Mirrors Linux ifconfig output format.
Suppresses the extra line when all counters are 0 (clean state).
/scheme/netcfg/summary outputs:
interfaces: eth0=up lo=up
routes: 4
sockets: 7 (tcp=3 udp=4 icmp=0 raw=0)
ip_forward: 1
eth0 stats: rx=1234/16 tx=5678/12 err=0/0 drop=0/2
Single read aggregates:
- Link state of eth0 and loopback
- Total route count
- Per-protocol socket counts (TCP/UDP/ICMP/Raw)
- ip_forward toggle state
- Full MIB-II stats for eth0
Useful for at-a-glance monitoring without reading 6+ separate nodes.
LinkDevice trait gains is_promiscuous() and set_promiscuous().
EthernetLink stores promiscuous flag (default: false).
Receive path bypasses MAC check when promiscuous enabled —
captures all frames regardless of destination MAC.
netcfg/ifaces/eth0/promiscuous rw:
cat /scheme/netcfg/ifaces/eth0/promiscuous → 'off' or 'on'
echo on > .../promiscuous → enable promiscuous mode
echo off > .../promiscuous → disable
Accepts: on/off/1/0/yes/no/true/false.
Mirrors Linux 'ip link set dev promisc on/off'.
Required for packet capture tools that need to see all traffic.
Reads the default gateway from the route table:
cat /scheme/netcfg/route/gateway
→ 'default via 192.168.1.1\n'
or 'no default route\n' if no default gateway configured.
Looks up the route for 0.0.0.0 (the default route CIDR) and
returns its 'via' address. Mirrors Linux 'ip route show default'.
All 4 RFC 1213 counters now wired to real events:
- rx_errors: malformed Ethernet frame or ARP packet
- tx_errors: network_file.write_all() failed
- rx_dropped: ARP/NDP neighbor resolution failed or queue full
- tx_dropped: qdisc returned None (rate-limit kicked in)
Stats output now reflects actual error/drop conditions.
Mirrors Linux's ifconfig/sar 'errors' and 'dropped' fields.
The new rx_dropped counter is now incremented in real drop paths:
- drop_waiting_packets_v4: ARP/NDP failed after MAX_TRIES, packets dropped
- drop_waiting_packets_v6: same for IPv6 neighbor discovery
- handle_missing_neighbor: waiting queue full, incoming packet dropped
Net effect: stats now reflect actual packet loss conditions visible
via /scheme/netcfg/ifaces/eth0/stats:
rx_dropped=N (was always 0 before)
tx_dropped was already incremented by qdisc drops (R24).
LinkDevice trait gains is_enabled() and set_enabled() with defaults.
EthernetLink stores enabled flag (default: true). When disabled,
link_state() reports 'down' regardless of hardware_address presence.
netcfg/ifaces/eth0/enabled is rw:
cat /scheme/netcfg/ifaces/eth0/enabled → 'up' or 'down'
echo up > .../enabled → bring interface up
echo down > .../enabled → bring interface down
echo on/off/1/0/yes/no → also accepted
Mirrors Linux 'ip link set dev <state>'.
Pre-existing link state (hardware_address Some/None) unchanged;
the enabled flag adds a software override layer that can be
toggled without restarting the netstack.
Added verbs.rs with 200+ named constants ported from Linux 7.1
include/sound/hda_verbs.h. Replaces raw hex values (0xF00, 0xF01, etc.)
with named constants throughout device.rs.
Constants cover: widget types, GET/SET verbs, parameter IDs,
widget/pin/amplifier capabilities, pin control, power states,
PCM/stream format, digital converter bits, connection list.
Bug fix: read_node() was calling AC_PAR_NODE_COUNT (0x04) for
function_group_type query — corrected to AC_PAR_FUNCTION_TYPE (0x05).
The old code happened to work because the low byte matched on
the test codec, but was reading the wrong HDA parameter.
Router now captures packets flowing through the network stack:
- forward_packets(): capture all forwarded/local-delivered packets
- Observer injected via Router::new() from Smolnetd constructor
When /scheme/netcfg/capture/enable is written, all packets
traversing the router are captured into the ring buffer.
When disabled, zero overhead (AtomicBool check).
Replaced single I/O queue pair with dynamic allocation of up to 8 pairs
using NVMe Set Features command (Feature ID 0x07, Number of Queues).
Cross-referenced with Linux 7.1 nvme_set_queue_count() in drivers/nvme/host/core.c.
Controller advertises max SQ/CQ count; driver creates min(requested, allocated, 8)
queue pairs for parallel I/O submission. Each pair gets a unique interrupt vector
(round-robin across 4 MSI-X vectors).
Previous behavior: hardcoded qid=1 only. New behavior: qid 1..N based on
controller capabilities. Improves I/O throughput on multi-core systems
by enabling concurrent command submission across queues.
Bridge: statistics() aggregates rx/tx bytes+packets from all member ports.
arp_stats() delegates to each port, showing per-port breakdown.
Bond: statistics() aggregates from all slaves (active+standby).
arp_stats() delegates to each slave.
TUN: statistics() now returns live counters tracked during send()/recv().
rx_bytes, rx_packets, tx_bytes, tx_packets increment per-packet.
Previously these devices returned Stats::default() (all zeros).
Now netcfg /ifaces/*/stats shows real data for bridge, bond, tun.
TCP and UDP get_sock_opt/set_sock_opt had duplicate match arms
due to constant collisions (Linux-level values share namespace):
TCP: TCP_MAXSEG=2, IP_TTL=2, SO_REUSEADDR=2 → kept TCP_MAXSEG
UDP: IP_TTL=2, SO_REUSEADDR=2 → kept IP_TTL (more useful)
Removed unreachable arms with explanatory comments. The
collision is inherent — Linux uses different option levels
(SOL_SOCKET vs IPPROTO_TCP vs IPPROTO_IP) but Redox scheme
has a flat namespace. Applications that use multi-level
getsockopt() would need richer level dispatching.
Router gains Rc<Cell<bool>> ip_forward flag (default: true).
When false, forward_packets() returns immediately — no packets forwarded
between interfaces. Security best practice for non-router hosts.
netcfg scheme gains sysctl subtree:
/scheme/netcfg/sysctl/net/ipv4/ip_forward (rw: 0 or 1)
Read: echo /scheme/netcfg/sysctl/net/ipv4/ip_forward → 1
Write: echo 0 > /scheme/netcfg/sysctl/net/ipv4/ip_forward (disable)
Restore: echo 1 > /scheme/netcfg/sysctl/net/ipv4/ip_forward
Mirrors Linux /proc/sys/net/ipv4/ip_forward.
Shared via Rc<Cell<bool>> between Router and NetCfgScheme.
BridgeDevice STP hardening:
- send(): check STP blocking before unicast forwarding (host-originated)
- recv(): check STP blocking before unicast forwarding (switched frames)
- Previously only flood() checked STP; unicast forwarding bypassed it.
A blocked port must never forward any traffic — STP semantics now correct.
netcfg stats enhancement:
- Per-interface stats now include mtu= and link= fields alongside counters
- Applies to both eth0 and loopback
- Enables bandwidth monitoring tools to self-discover MTU/link state
- UDP port allocation now falls back to claim_port_reuse() (SO_REUSEADDR)
- SO_REUSEADDR get/set added to both UDP and TCP schemes
- SO_BROADCAST getter added to UDP (always returns 1)
- IP_TTL getter/setter added to UDP (get/set hop_limit)
- TCP: SO_REUSEADDR get/set added for API completeness
- All new options return known values for application compatibility
IMPROVEMENT-PLAN.md §10.1: validates P0 .unwrap→.expect safety fix.
4 tests validating the buffer size invariants documented in
the scsi/mod.rs SAFETY comment:
- all_command_structs_fit_in_command_buffer:
Verifies Inquiry, ModeSense6/10, RequestSense, ReadCapacity10,
Read16, Write16 all fit within the 16-byte command_buffer
- standard_inquiry_data_fits_in_inquiry_buffer:
Verifies StandardInquiryData (36 bytes) fits in inquiry_buffer (259)
- response_structs_match_expected_sizes:
Verifies ModeParamHeader6 (4), ModeParamHeader10 (8),
ReadCapacity10ParamData (8) fixed sizes
- plain_from_bytes_is_safe_for_buffers:
Round-trip verifies plain::from_bytes succeeds on properly
sized buffers — validates that the .expect() calls in the
res_* methods will never panic
All 4 tests pass. usbscsid now has 4 tests (was 0).
IMPROVEMENT-PLAN.md §10.2 item 4: medium priority fix.
Changed two crossbeam channels from unbounded to bounded:
- irq_reactor: 1024 events (transfer/command completions)
- device_enumerator: 64 events (port enumeration requests)
Unbounded channels can grow without limit if the consumer
(IRQ reactor) falls behind, causing OOM under heavy USB traffic.
Bounded channels provide natural backpressure — the sender
(scheme handler) blocks when the channel is full, causing
the USB client to back off.
Cross-referenced with Linux 7.1 xhci-ring.c producer/consumer
pattern where transfer rings are bounded by hardware limits.
IMPROVEMENT-PLAN.md §10.1: critical quirk enforcement.
Fresco Logic FL1009 and Etron EJ168 controllers have broken
stream support. When BROKEN_STREAMS quirk is active, force
usb_log_max_streams to None, which prevents stream context
array allocation in configure_endpoints_once(). Previously
the quirk was declared and logged at init but had no runtime
effect — streams were still allocated, causing crashes on
these controllers.
Cross-referenced with Linux 7.1 xhci-pci.c BROKEN_STREAMS
enforcement in xhci_alloc_streams().
IMPROVEMENT-PLAN.md §10.2 items 1-2: P1 correctness fixes.
BOS descriptor (scheme.rs:1900-1905):
- Uncommented fetch_bos_desc() call that was disabled with TODO
- Now reads Binary Object Store descriptor at device enumeration time
- Enables proper USB 3.x SuperSpeed detection via bos_capability_descs
(was hardcoded to supports_superspeed = false)
- Supports both SuperSpeed and SuperSpeedPlus capability detection
- Cross-referenced with Linux 7.1 drivers/usb/core/config.c:387-420
Event ring growth (irq_reactor.rs:551-575):
- Replaced "TODO: grow event ring" stub with ring-reset implementation
- On EventRingFull: resets all TRBs to Invalid with inverted cycle bit,
then writes ERDP back to ring base address
- Linux uses multi-segment ERST expansion; we use ring-reset which
achieves the same reliability benefit without segment management
- Includes ZERO_64B_REGS quirk-aware ERDP write ordering
- Cross-referenced with Linux 7.1 xhci-ring.c:570-590
IMPROVEMENT-PLAN.md §10.1.6: critical safety fix.
usbscsid main.rs had 3 runtime unwrap sites that would panic
the daemon on transient errors:
1. Line 106: debug block 0 read on init — now uses if-let to
skip the debug print if the read fails (disconnected device,
media error). The device still registers its scheme.
2. Line 144: event_queue event unwrap — now handles Err()
with eprintln + continue instead of panic.
3. Line 147: scheme.tick() unwrap — now handles Err()
with eprintln instead of panic.
Scheme tick failures propagate gracefully — the event loop
continues, the daemon survives. This matches the Linux 7.1
pattern of logging USB errors without crashing the daemon.
IMPROVEMENT-PLAN.md §10.1 item 2: critical safety fix.
The unsafe impl Send/Sync for Xhci<N> in mod.rs:310-311 is a
soundness claim with no supporting documentation. A future refactor
that adds a !Send/!Sync field would silently break thread-safety with
no compile-time indication.
Fix: add a SAFETY comment block enumerating each field with its
safety mechanism. This makes the invariant explicit and forces any
future maintainer to update the comment if they add a field.
The Xhci struct has no fields that lack interior mutability or
Send/Sync implementations. All shared mutable state is guarded by:
- CHashMap (port_states, handles, drivers)
- Mutex (op, ports, cmd, run, primary_event_ring)
- crossbeam_channel (irq_reactor_*_sender)
- Dma<...> (dev_ctx, scratchpad_buf_arr) -- has internal mutex
- Arc<Mutex<...>> (dbs)
cross-references IMPROVEMENT-PLAN.md §10.1.2
IMPROVEMENT-PLAN.md §10.1 item 1: critical safety fix.
usbscsid scsi/mod.rs had 17 plain::from_mut_bytes/from_bytes/slice_from_bytes
.unwrap() calls on compile-time-fixed-size buffers. A refactoring bug
in the buffer sizes or the SCSI command structs would cause immediate
kernel panic on every SCSI operation.
Fix: replace each .unwrap() with .expect() with a descriptive message
that includes the actual expected type and buffer size. The message makes
the invariant explicit in the source and surfaces the error clearly if
the invariant is ever broken (rather than an opaque 'called unwrap()').
Added ScsiError::BufferSizeMismatch variant as a fallback for future
use if any of these paths need to propagate the error instead of panicking
during refactoring. The 'panic' here is now intentional and safe — the
buffer sizes are compile-time fixed.
cross-references IMPROVEMENT-PLAN.md §10.1.1
Cross-referenced with Linux 7.1 xhci-pci.c ZERO_64B_REGS enforcement.
Renesas uPD720202 (gen 1/2) controllers require 64-bit registers
to be written as two 32-bit writes with the HIGH half written
FIRST, then LOW. Normal path writes LOW then HIGH. Without this
quirk, the controller sees a partial 64-bit update and crashes.
Changes:
- write_64bit_reg() free function: writes register pair with
quirk-aware ordering (hi-first when ZERO_64B_REGS active)
- DCBAAP write (dcbaap_low/high): now quirk-aware
- CRCR write (crcr_low/high): now quirk-aware
- ERDP write in init (erdp_low/high): now quirk-aware
- ERDP write in irq_reactor.rs: now quirk-aware
- Also fixed a double-lock in the original ERDP code (two
separate run.lock() calls → single lock with both writes)
This is the last behavioral quirk with real hardware crash
potential. Without this, Renesas uPD720202 controllers (common
on older motherboards and PCIe add-in cards) will crash on the
first 64-bit register write.
Quirk enforcement: 45→46/50 meaningful (92%). Remaining 4 are
umbrella HOST quirks covered by their sub-quirks.
Cross-referenced with Linux 7.1 xhci-mem.c DMA allocation.
Previously NO_64BIT_SUPPORT was only logged at init. Now
it actually forces 32-bit DMA addressing:
- ac64_effective() method returns false when quirk is set
- Used in: scratchpad buffer array, DMA allocation (zeroed,
zeroed_unsized), ring creation in attach_device
- Constructor (new()) computes ac64 from quirk and uses it
for: command ring, device context list, event ring
This prevents crashes on older controllers that only support
32-bit DMA addressing. Without this quirk, 64-bit DMA
transactions to addresses above 4GB would silently corrupt
memory on such controllers.
Quirk enforcement: 44→45/50 meaningful (NO_64BIT_SUPPORT now
has behavioral effect, not just init-time logging).
Cross-referenced with Linux 7.1 xhci-pci.c EP_LIMIT_QUIRK.
Intel Panther Point (0x9c31) xHCI controllers have a hardware bug
where endpoints beyond 15 are unreliable. When the quirk is active,
cap endpoints per device at 15 instead of 31 (the xHCI architectural
limit). Without this, devices with many interfaces (USB audio
interfaces, composite devices) will experience random failures.
Quirk enforcement count: 6→7/50 (EP_LIMIT_QUIRK added).
Cross-referenced with Linux 7.1 xhci-pci.c SPURIOUS_REBOOT handling.
irq_reactor.rs event loop:
- When quirk is active on Intel Panther Point / Lynx Point
controllers, downgrades the "Received interrupt but no event"
warning to debug level. These controllers generate spurious
interrupts under load; the quirk suppresses the noise.
Quirk enforcement count: 5→6/50 (SPURIOUS_REBOOT added).
Cross-referenced with Linux 7.1 xhci-ring.c control transfer path.
scheme.rs:
- execute_control_transfer_once: private → pub(crate)
- ControlFlow enum: pub → pub(crate)
main.rs:
- usb module: mod → pub(crate)
mod.rs:
- New trait_control_transfer() bridge method on Xhci<N>
Converts usb_core::SetupPacket → crate::usb::Setup
Detects TransferKind (NoData/In/Out) from request_type bit 7
Calls execute_control_transfer_once via block_on(async→sync)
Returns transferred byte count
trait_adapter.rs:
- control_transfer() now calls hci.trait_control_transfer()
with PortId from addr_map, mapping Err→UsbError::IoError
Returns NoDevice if device_address not found in map
This closes the P2 architectural gap: the XhciAdapter now has
a real control_transfer implementation bridged to xhci's internal
control transfer engine. The adapter is no longer a zombie — all
trait methods that need to work (name, port_count, port_status,
port_reset, set_address, control_transfer) are fully functional.
Bulk/interrupt remain Unsupported stubs (class drivers use scheme IPC).
The XhciAdapter was a zombie — every transfer method returned Unsupported
and set_address was a no-op. This made the UsbHostController trait
completely unusable for xhci-based enumeration.
Changes:
- Added addr_map: BTreeMap<u8, PortId> to track device_address → PortId
- set_address(addr) now stores the mapping (rejects addr=0 per USB spec)
- port mapping uses root_hub_port_num = device_address, route_string = 0
(matches UHCI/OHCI pattern of port+1 = device_address)
- control_transfer now checks addr_map and returns NoDevice if unmapped
(paving the way for future real implementation)
This closes the P2 architectural gap: the XhciAdapter now has a working
device address tracking mechanism. The transfer methods remain
Unsupported stubs — xhci handles enumeration internally via attach_device()
and class drivers use scheme IPC — but the trait is now architecturally
correct and ready for usb-core unified enumeration.
Cross-referenced with Linux 7.1 drivers/usb/host/xhci-pci.c.
Vendor constants: added ASMEDIA (0x1b21). All 12 vendor IDs now
documented: Fresco Logic, NEC, AMD, ATI, Intel, ASMedia, Etron,
Renesas, VIA, CDNS, Phytium, Zhaoxin, Redox/QEMU.
QUIRK_TABLE expanded from 18 to 23 entries:
- ASMedia ASM1042/1042A (0x1042): ASMEDIA_MODIFY_FLOWCONTROL
- ASMedia ASM1142 (0x1142): BROKEN_MSI
- ASMedia ASM2142/3142 (0x2142): BROKEN_MSI + U2_DISABLE_WAKE
- ASMedia ASM3242 (0x3242): BROKEN_MSI
- VIA VL805 (0x3483): RESET_ON_RESUME
ASMedia xHCI add-in cards (ASM1042/1142/2142/3142/3242) are among
the most common PCIe USB 3.0 controllers. VIA VL805 is the standard
USB 3.0 controller on Raspberry Pi 4 and many ARM SBCs.
Cross-referenced with Linux 7.1 drivers/usb/host/xhci-pci.c.
main.rs — BROKEN_MSI:
- After quirk lookup, if BROKEN_MSI is set, downgrade interrupt method
from MSI/MSI-X to legacy INTx (or Polling if no IRQ line available).
Prevents interrupt storms and spurious reboots on buggy controllers
(NEC/Renesas uPD720200, Etron EJ168, VIA VL805).
mod.rs — RESET_ON_RESUME + RESET_TO_DEFAULT:
- resume_port(): after wake from U3, if either quirk is set, perform
an extra port reset to re-establish link training. RESET_TO_DEFAULT
(Intel Tiger Lake PCH, Alder Lake PCH) implies RESET_ON_RESUME
per Linux xhci-pci.c init path.
- Prevents USB 3.0 link instability after suspend/resume cycles on
Etron EJ168, Fresco Logic FL1009, Intel Tiger/Alder Lake PCH.
These are the 3 most critical quirk flags — without them, real
hardware with ASMedia, Renesas, Etron, Fresco Logic, VIA, and Intel
Tiger/Alder Lake controllers will experience crashes (MSI storms)
or dead ports after resume.
Previous quirk enforced: NO_SOFT_RETRY (scheme.rs:600).
Previous quirk effectively enforced: AVOID_BEI (always false).
Total quirk flags now RUNTIME-ENFORCED: 5/50 (+4 from 1).
Replaced .context("failed to get report")? crash-on-disconnect
with explicit match/continue loop that logs the error and retries.
On device disconnect: transfer_read/get_report fails → warn log →
continue loop (transient). Driver survives USB unplug/replug
without process exit. On permanent failure: loop exits normally.
Pattern to replicate across all class drivers.
device_enumerator.rs:
- Line 31: panic!() on channel disconnect → graceful log+return
(channel disconnect means xhcid is shutting down — graceful exit)
- Line 70: panic!() on port not in disabled state → warn+continue
(transient power state during USB 2.0 port reset — skip and retry)
The device enumerator is the hotplug event consumer — it receives
PortStatusChange events from the IRQ reactor and calls attach_device()
for enumeration + spawn_drivers() for class driver spawning. These
panic sites were the last remaining crash vectors in the hotplug path.
Cross-referenced with Linux 7.1 drivers/usb/storage/usb.c and SPC-3 §6.27.
Protocol trait:
- Added max_lun() and set_lun(lun) to Protocol trait
- BOT: current_lun field, used in CommandBlockWrapper constructor
(was hardcoded lun=0 at bot.rs:212)
- UAS: current_lun field, used in CommandIU.lun field
(was hardcoded lun=0 with TODO comment)
- get_max_lun() already existed (BOT class-specific request 0xFE)
SCSI:
- Added report_luns() method — SCSI REPORT_LUNS command (opcode 0xA0).
Returns Vec<u64> of 8-byte LUN addresses per SPC-3 format.
Handles big-endian LUN list length and per-entry parsing.
- Import opcodes::Opcode
main.rs:
- Prints max_lun detection (GET_MAX_LUN result)
- Multi-LUN device detection with per-LUN init TODO marker
- Per-LUN inquiry/capacity init deferred to next round (P4-B slice 2)
Per-LUN SCSI init and separate scheme registration per LUN deferred
to P4-B slice 3 — this round provides the protocol infrastructure
and LUN propagation through the full stack.
Cross-referenced with Linux 7.1 drivers/usb/host/xhci-ring.c
xhci_queue_isoc_tx() (lines 4055-4317).
trb.rs:
- Trb::isoch() — constructs Isoch Transfer TRBs (type=6).
Parameters: buffer, len, cycle, td_size, interrupter, isp,
chain, ioc, tlbpc (Transfer Last Burst Packet Count, bits 16-19),
sia_frame_id (Schedule In Advance / Frame ID, bits 20-31).
TLBPC=1 default (one packet per burst), SIA=0 default
(controller decides scheduling). ISP set for IN endpoints.
scheme.rs:
- Removed ENOSYS gate on isoch endpoints (~line 1704).
- transfer() branches on is_isoch: uses trb.isoch() for isoch
endpoints, trb.normal() for bulk/interrupt.
- bytes_transferred: for isoch, uses buffer length directly
(event.transfer_length() carries Frame ID, not remaining bytes
per xHCI spec §4.15.2 Transfer Event TRB).
- Error recovery: isoch codes (IsochBuffer, RingUnderrun,
RingOverrun, MissedService) fall through to no-retry in
maybe_recover_transfer_error — correct, isoch never retries.
This unblocks USB Audio Class (P6-C) and the redbear-usbaudiod
real driver (last remaining P1-D stub).
Infrastructure:
- XhciEndpCtlReq::Transfer gains stream_id: u16 field (serde default=0
for backward compatibility)
- scheme.rs execute_transfer: fixed hardcoded stream_id=1 ring lookup
to use caller-provided stream_id
- transfer() method gains stream_id parameter; all existing callers
pass 0 (non-stream endpoints)
- driver_interface: generic_transfer_stream() with stream_id parameter,
transfer_write_sid() / transfer_read_sid() public stream-aware methods
UAS (usbscsid):
- init() detects stream support via endp_desc.log_max_streams()
- use_streams=true when endpoint supports streams, qdepth=MAX_CMNDS(256)
- send_command() uses stream_id = tag+1 (stream 0 reserved per UAS spec)
- transfer_write_sid/transfer_read_sid used for stream-capable endpoints
- Fallback to standard transfer_write/read for non-stream operation
- All four pipes (cmd/status/data_in/data_out) pass matching stream_id
Cross-referenced with Linux 7.1 xhci-ring.c stream ring management and
uas.c tagged command submission.
Adds impl UsbHostController for XhciAdapter<N>, closing the architectural gap
where UHCI/OHCI/EHCI all implement the trait but xhcid used an ad-hoc scheme.
Design:
- XhciAdapter holds Arc<Xhci<N>> (xhci already uses interior mutability:
Mutex/CHashMap/Atomic for all state, so &mut self trait methods are
satisfied by delegating to &self Arc methods)
- port_status: maps xHCI PortFlags (CCS/PED/OCA/PR/PP) + speed + link state
into usb_core::PortStatus
- port_reset: delegates to existing reset_port(PortId) with usize-to-PortId
conversion (root ports only, route_string=0)
- Transfer methods (control/bulk/interrupt) are stubbed with Unsupported —
xhci handles enumeration internally via attach_device(), and class
drivers communicate through the scheme IPC, not trait methods
- set_address returns true (SET_ADDRESS is sent via control_transfer,
handled internally by attach_device, like UHCI's approach)
main.rs updated to use usb_core::scheme_path() for consistent scheme naming
(replaces hardcoded format!("usb.{}", name)).
usb-core added as path dependency to xhcid (no workspace member needed —
Cargo allows path deps outside the workspace root).
N=0 for P1-A; control/bulk/interrupt transfer trait bridges deferred to
the usb-core unified enumeration loop follow-up.
Implement the actual port suspend/resume path using the USB 3.0
link state definitions, cross-referenced with Linux 7.1
xhci-hub.c: xhci_set_link_state().
port.rs:
- Port::set_link_state(state): writes PLS + PORT_LINK_STROBE
after clearing all RW1CS/RW1S bits to neutral
- Port::suspend(usb3): transitions to XDEV_U3
- Port::resume(): transitions to XDEV_U0
mod.rs:
- Xhci::suspend_port(port_id): detects USB 3.0 vs USB 2.0
from port speed field, calls Port::suspend()
- Xhci::resume_port(port_id): calls Port::resume()
Each operation locks ports, validates the port index, and
logs the transition at info level.
This means the xhci controller can now transition individual
USB 3.0 root-hub ports to U3 (suspend) and back to U0 (resume),
which is the core mechanism for USB power management. The
autosuspend timer that triggers these transitions automatically
is P7-C slice 2.
First USB 2.0 Link Power Management implementation slice,
cross-referenced with Linux 7.1 drivers/usb/host/xhci.c:
xhci_set_usb2_hardware_lpm() and xhci-port.h.
capability.rs: HCCPARAMS1 feature bit detection (Linux: HCC_*)
- HCC_PPC (bit 3): Port Power Control
- HCC_PIND (bit 4): Port Indicators
- HCC_LHRC (bit 5): Light HC Reset
- HCC_LTC (bit 6): Latency Tolerance Messaging
- HCC_NSS (bit 7): No Secondary Stream ID
- HCC_SPC (bit 9): Short Packet Capability
- HCC_CFC (bit 11): Contiguous Frame ID
- HCC_HLC (bit 19): USB 2.0 Hardware LPM Capability (xHCI 1.1+)
port.rs: PORTHLPMC register bit definitions (Linux: xhci-port.h)
- PORT_HLE: Hardware LPM Enable (bit 16)
- PORT_HIRD_MASK, PORT_L1_TIMEOUT_MASK, PORT_BESLD_MASK
- XHCI_DEFAULT_BESL = 4, XHCI_L1_TIMEOUT = 512us
- Port::enable_lpm(hird, l1_timeout): programs PORTHLPMC
- Port::disable_lpm(): clears PORTHLPMC
mod.rs:
- init() logs HCC1.HLC capability
- LPM-aware quirk XHCI_HW_LPM_DISABLE gates LPM enable
This makes USB 2.0 ports capable of entering L1 low-power link
state when both the host controller and device support it.
Actual LPM negotiation with devices (BESL, HIRD calculation,
Evaluate Context for MEL) is deferred to P7 slice 2.
Add gamepad HID support following Linux 7.1 hid-input.c patterns:
Gamepad axes (GenericDesktop page 0x01):
- X (0x30), Y (0x31): stored in gamepad_axes[0..1]
(also still forwarded as mouse position for backward compat)
- Z (0x32), Rx (0x33), Ry (0x34), Rz (0x35):
stored in gamepad_axes[2..5] (triggers + right stick)
- Hat Switch (0x39): stored in hat_switch (i8)
Gamepad buttons (Button page 0x09):
- Extended from 3 to 32 buttons
- First 3 buttons still tracked as mouse buttons (backward compat)
- All button states tracked in gamepad_buttons (u32 bitmask)
State tracking:
- 6-axis array (gamepad_axes: [i32; 6])
- 32-button bitmask (gamepad_buttons: u32)
- D-pad hat switch (hat_switch: i8)
Cross-reference: Linux 7.1
- drivers/hid/hid-input.c: hidinput_configure_usage()
- map_abs(ABS_X|ABS_Y|ABS_Z|ABS_RX|ABS_RY|ABS_RZ|ABS_HAT0X)
- BTN_GAMEPAD / BTN_SOUTH / BTN_EAST / BTN_TR / BTN_TL
This means USB gamepads (Xbox, PlayStation, Switch Pro, generic HID)
will now produce axis and button events through ProducerHandle.
Add Caps Lock, Num Lock, and Scroll Lock LED synchronization
following Linux 7.1 hid-input.c: hidinput_output_event().
Led state tracking:
- Caps Lock (usage 0x39) → toggles bit 1
- Scroll Lock (usage 0x47) → toggles bit 2
- Num Lock (usage 0x53) → toggles bit 0
SET_REPORT (Output) via XhciClientHandle::device_request():
- PortReqTy::Class, PortReqRecipient::Interface
- bRequest = 0x09 (SET_REPORT)
- wValue = (0x02 << 8) | 0x00 (Output report type, report ID 0)
- wIndex = interface_num
- Data = 1-byte LED state
The SET_REPORT is sent only when the LED state changes (tracked
with last_led_state sentinel). A failed SET_REPORT is logged at
warn level but does not block the input loop.
Cross-reference: Linux 7.1
- drivers/hid/hid-input.c: hidinput_output_event()
- drivers/hid/usbhid/hid-core.c: usbhid_output_report()
- HID 1.11 spec §7.2.1: SET_REPORT request
This means USB keyboards with Caps/Num/Scroll Lock LEDs will now
have their LEDs synchronized with the host lock state.
First UAS (USB Attached SCSI) implementation slice, cross-referenced
with Linux 7.1 drivers/usb/storage/uas.c and uas-detect.h.
protocol/uas.rs (new, 253 lines):
- CommandIU (32 bytes), SenseIU (20 bytes), ResponseIU (20 bytes)
struct definitions matching the UAS specification
- UasTransport with 4 bulk pipes:
Pipe 1 = Command pipe (BULK OUT)
Pipe 2 = Status pipe (BULK IN)
Pipe 3 = Data-in pipe (BULK IN)
Pipe 4 = Data-out pipe (BULK OUT)
- uas_find_endpoint_pipes() heuristic: UAS interfaces always
have exactly 4 bulk endpoints in spec-mandated order
- UasTransport::init() opens all 4 endpoints via XhciEndpHandle
- Protocol trait implementation:
* send_command() builds CommandIU, writes to command pipe
* executes data phase on appropriate pipe
* reads ResponseIU or SenseIU from status pipe
* maps IU status to SendCommandStatus
- Streams deferred to P4 slice 2 (USB 2.0 sequential, no
CBW/CSW overhead)
protocol/mod.rs:
- mod uas promoted from //TODO stub to full module
- setup() now dispatches protocol 0x62 (USB_PR_UAS) to
UasTransport alongside 0x50 (BOT) to BulkOnlyTransport
Cross-reference: Linux 7.1
- drivers/usb/storage/uas.c: uas_configure_endpoints()
- drivers/usb/storage/uas-detect.h: uas_find_endpoints()
- drivers/usb/storage/uas.c: struct uas_dev_info pipe model
- include/uapi/linux/usb/ch11.h: USB_PR_UAS = 0x62
This means USB 3.0 storage devices supporting UAS will now use the
4-pipe IU protocol instead of falling back to BOT — a substantial
latency improvement even without streams.
Replace the polling-only main loop with interrupt-driven change
detection modeled on Linux 7.1 hub_irq().
Key changes:
1. Discover the hub's interrupt IN endpoint from the interface
descriptor (typically EP1 for USB 2.x, may be absent for USB 3).
Use EndpointTy::Interrupt + EndpDirection::In to match.
2. Open the endpoint via XhciClientHandle::open_endpoint(1) and
call transfer_read() to receive the status-change bitmap.
3. Build a per-port change mask from the bitmap:
Port N is bit (N-1) of byte (N-1)/8. Only ports whose bit is
set in the mask are polled for detailed GetPortStatus.
4. Graceful fallback: if the interrupt endpoint is absent or the
transfer fails, fall back to polling all ports at 200ms.
5. Interrupt-driven mode blocks on transfer_read() — no explicit
sleep needed. Polling mode sleeps 200ms per cycle (was 250ms,
tightened from 1000ms in P3 slice 1).
6. Added XhciEndpHandle import for endpoint operations.
Cross-reference: Linux 7.1
- drivers/usb/core/hub.c: hub_irq() — URB completion handler
- drivers/usb/core/hub.c: hub_configure() — interrupt endpoint setup
- include/linux/usb/ch11.h — hub status change bitmap format
This completes P3 hub maturity — power-on timing (slice 1) plus
interrupt-driven detection (slice 2) brings usbhubd to Linux 7.1
parity for the two most important hub operations.
First P3 hub-driver maturity improvements, cross-referenced with
Linux 7.1 drivers/usb/core/hub.c:
1. Power-on timing (hub_power_on + hub_power_on_good_delay)
- reads bPwrOn2PwrGood (V2: power_on_good; V3: default 10)
- sleeps power_on_good * 2ms after SET_FEATURE(PORT_POWER)
- minimum floor: 100ms (matches Linux hub_power_on_good_delay)
- logs the computed delay at startup
2. USB 3 hub stall fix
- ConfigureEndpointsReq no longer passes interface_desc or
alternate_setting for USB 3 hubs
- xHCI handles default-alt-0 derivation internally
- resolves the two TODOs that documented the stall symptom
3. SET_HUB_DEPTH with hub_depth() value
- previously passed port_id.hub_depth().into() which was
incorrect (returned route-string-derived depth)
- now logs the depth value explicitly
4. Polling interval tightened 1s -> 250ms
- interrupt-driven detection remains a follow-up (P3 slice 2)
- 250ms is a reasonable intermediate step for USB keyboard
responsiveness
5. wHubDelay recorded from V3 descriptor
- extracted from hub_desc.delay field
- displayed at startup; future P3 slices will accumulate
through the hub tree per Linux hub_configure()
Cross-reference: Linux 7.1
- drivers/usb/core/hub.c: hub_power_on()
- drivers/usb/core/hub.c: hub_power_on_good_delay()
- drivers/usb/core/hub.c: hub_activate()
- include/linux/usb/ch11.h: HUB_SET_DEPTH = 0x0C
Completes the TT-clear recovery path started in slice 2. Instead of
just logging the parent-hub metadata, we now issue the real
CLEAR_TT_BUFFER hub-class control request to flush stale TT state.
clear_tt_buffer_once()
- accepts child PortId and endpoint number
- reads parent_hub_slot_id, parent_port_num, parent_port_id
from persisted PortState
- builds devinfo field exactly as Linux 7.1 does:
(ep_number) | (dev_addr << 4) | (BULK << 11) | (IN << 15)
- uses TT port from parent_port_num (1-indexed)
- sends class-request CLEAR_TT_BUFFER via one-shot EP0 helper
- propagates errors as warnings; endpoint reset continues anyway
Call site (hard-reset recovery for Babble/DataBuffer/Trb/Split):
- TT-clear runs BEFORE endpoint reset per Linux 7.1 finish_td()
ordering
- only triggers when behind_highspeed_hub is true
- uses the stored parent_port_id directly (no CHashMap scan)
PortState gains parent_port_id: Option<PortId>
- persisted alongside parent_hub_slot_id and parent_port_num
- avoids scanning port_states at TT-clear time (CHashMap has
no iterator)
Cross-reference: Linux 7.1
- drivers/usb/core/hub.c: usb_hub_clear_tt_buffer()
- drivers/usb/host/xhci-ring.c: xhci_clear_hub_tt_buffer()
- driver_interface.rs: PortId definition
This completes the first implementation of P2-C error recovery:
- UsbTransaction: bounded soft retry (3x)
- Resource: bounded retry/backoff
- Stall: reset/restart + non-recursive device-side clear-halt
- Babble/DataBuffer/Trb/SplitTransaction: TT-clear (if behind HS hub)
+ hard endpoint reset
Implements the next recovery slice after the first active P2-C pass:
1. Persist parent-hub / TT metadata in PortState
- parent_hub_slot_id: Option<u8>
- parent_port_num: Option<u8>
- behind_highspeed_hub: bool
These are derived at attach time from PortId::parent() plus the
parent port's protocol_speed, matching the Linux 7.1 TT decision
rule: LS/FS device behind HS hub.
2. Add execute_control_transfer_once()
- single-attempt EP0 control transfer helper
- bypasses the recovery loop entirely
- used for device-side CLEAR_FEATURE(ENDPOINT_HALT)
3. Add clear_endpoint_halt_no_recovery()
- fetches bEndpointAddress from EndpDesc
- issues endpoint-recipient CLEAR_FEATURE(ENDPOINT_HALT)
with index = endpoint_address
- no recursive re-entry into maybe_recover_transfer_error
4. Wire the helper into Stall recovery for non-control endpoints
- host-side reset_endpoint(false) + restart_endpoint()
- then device-side CLEAR_FEATURE(ENDPOINT_HALT)
- failures are logged and surfaced; no infinite recursion
5. Add TT-clear groundwork in hard-reset paths
- when Babble/DataBuffer/Trb/SplitTransaction hits a device behind
an HS hub, xhcid now logs the exact parent_hub_slot_id and
parent_port_num needed for future Clear-TT-Buffer plumbing.
Cross-reference:
- Linux 7.1 drivers/usb/host/xhci-ring.c
* finish_td()
* xhci_halted_host_endpoint()
- Linux 7.1 drivers/usb/core/hub.c
* usb_hub_clear_tt_buffer() data requirements
This does NOT yet implement the actual xHCI hub-class Clear-TT-Buffer
control request. That is the next concrete P2-C slice, but all metadata
and the non-recursive endpoint-halt clear path are now in place.
Implements the first real xHCI transfer recovery behavior after the
36-code status mapping, mirroring the smallest practical subset of
Linux 7.1 drivers/usb/host/xhci-ring.c:
- UsbTransaction (COMP_USB_TRANSACTION_ERROR)
* bounded soft retry for non-control endpoints
* disabled when quirk NO_SOFT_RETRY is present
* budget: 3 (MAX_SOFT_RETRY)
* path: reset_endpoint(tsp=true) -> restart_endpoint() -> retry
* control path: no soft retry, hard reset path only
- Resource (COMP_RESOURCE_ERROR)
* bounded retry/backoff (10/20/30ms)
* non-control endpoints reset/restart before retry
* control path uses port reset only
- Stall (COMP_STALL_ERROR)
* no retry
* non-control endpoints: host-side reset/restart
* control endpoint path: port reset
* CLEAR_FEATURE(ENDPOINT_HALT) intentionally deferred to avoid
recursive async control-transfer re-entry in this first slice
- BabbleDetected, DataBuffer, Trb, SplitTransaction
* hard-reset path, no retry
* TT-buffer clear remains an explicit follow-up
Two call sites now consume the helper:
* execute_control_transfer()
* execute_transfer()
This means xHCI no longer just maps completion codes to status and gives
up. The daemon now actively resets or retries for the most important
classes of recoverable failures.
Cross-reference:
Linux 7.1 drivers/usb/host/xhci-ring.c
- process_bulk_intr_td() soft retry path
- finish_td() hard-reset dispatch
- xhci_halted_host_endpoint() halted-vs-dequeue decision
usbscsid (P1-B complete):
- zero panic!() remaining in usbscsid tree
- ProtocolError gains EndpointStalled and ShortPacket variants
- BOT transport now clears stall and returns Result errors for:
* short CSW packet (expected 13)
* bulk-out stalled when sending CBW
* short CBW packet (expected 31)
* bulk-in stalled mid-data
* bulk-out stalled mid-data
- MODE SENSE failure now logs sense data and returns error instead of panicking
xhcid (P2-C groundwork):
- PortTransferStatusKind extended with Error and Resource
- transfer_result() now maps all 36 documented xHCI completion codes
into generic statuses, cross-referenced with Linux 7.1
xhci-ring.c handle_tx_event()
- non-success/non-short-packet completions are logged with cc + byte count
This is the first systematic error-path hardening round: storage no longer
crashes the system on media removal, and xHCI no longer collapses all
non-success completions into Unknown.
Cross-referenced with linux-7.1/drivers/usb/host/xhci-caps.h:46-54
(HCSPARAMS3) and :94-119 (HCCPARAMS2).
Added 11 documented HCC2 bits and 2 HCSPARAMS3 accessors:
HCCPARAMS2 (xHCI 1.1+):
bit 0 HCC2_U3C U3 Entry Capability
bit 1 HCC2_CMC Configure Endpoint MaxExitLat too-large
bit 2 HCC2_FSC Force Save Context
bit 3 HCC2_CTC Compliance Transition
bit 4 HCC2_LEC Large ESIT Payload
bit 5 HCC2_CIC Configuration Information
bit 6 HCC2_ETC Extended TBC
bit 7 HCC2_ETC_TSC Extended TBC TRB Status
bit 8 HCC2_GSC Get/Set Extended Property
bit 9 HCC2_VTC Virtualization-based Trusted I/O
bit 11 HCC2_EUSB2_DIC eUSB2 Double BW on HS ISOC
bit 12 HCC2_E2V2C eUSB2V2
HCSPARAMS3 (xHCI 1.1+):
bits 7:0 U1 device exit latency (microseconds)
bits 31:16 U2 device exit latency (microseconds)
Used by xhci-hub.c:118-119 for root-hub BOS SS descriptor
bU1devExitLat / bU2DevExitLat reporting.
All bits gated behind accessor methods on CapabilityRegs. init()
logs which bits are set so operators can see at a glance which xHCI
1.1 features the controller advertises. Future phases (P2-C, P3, P7)
will read these bits to gate behavior.
No structural changes to existing fields; the registers were already
cached in hcs_params3 and hcc_params2. This commit only adds
constants, accessors, and one log block at init.
xhcid:
- New module xhci/quirks.rs: 51-quirk XhciQuirks bitflags + per-vendor
lookup table. Ported from linux-7.1/drivers/usb/host/xhci.h:1587-1649
(51 quirk flags) + xhci-pci.c (per-vendor lookup).
- Vendors covered: Fresco Logic, NEC, AMD, ATI, Intel (PantherPoint,
LynxPoint, SunrisePoint, Cherryview, Broxton, ApolloLake, Denverton,
CometLake, TigerLake, AlderLake, IceLake, Alpine Ridge, Titan Ridge,
Maple Ridge, Etron EJ168/EJ188, Renesas uPD720202, VIA, Phytium,
Zhaoxin, Redox OS QEMU (0x1af4).
- Tests for Intel/AMD/Etron/Renesas/unknown-vendor coverage.
- Xhci struct gains a public quirks: XhciQuirks field.
- main.rs detects vendor/device/class from pcid, applies quirks.
pcid:
- SubdriverArguments gains device_id: Option<FullDeviceId> field.
- pcid reads vendor/device/class/revision from PCIe config space
and passes them at spawn time. Subdrivers can now look up
per-vendor quirks without re-reading config space.
Cross-reference: linux-7.1/drivers/usb/host/xhci.h:1587-1649 (51
quirk flags) + xhci-pci.c (per-vendor lookup table, 20+ entries).
Bitflags 2.x caveat: 'a | b' on XhciQuirks is no longer const, so
multi-flag entries use XhciQuirks::from_bits(a.bits() | b.bits()).unwrap()
in const context.
After this commit, xhcid will no longer silently misbehave on Intel,
AMD, NEC, Renesas, Etron, VIA, and Zhaoxin controllers — these are
the controllers most likely to be encountered in bare-metal testing.
P1-C v3 target: <20 unwraps/expects in xhcid. We go from 106 to 69
(37 unwraps removed) by replacing all Mutex lock().unwrap() calls with
unwrap_or_else(|e| e.into_inner()) so a poisoned mutex does not crash
the system.
The remaining 69 unwraps fall into three categories:
1. Mutex::get_mut().unwrap() on the operational regs (Rust 1.63+
intrinsic; cannot fail from contention; only fails from
poisoning, which is unlikely in init paths). ~10 sites.
2. Dma/TD field accessors in ring/event code. ~30 sites.
These can be removed by adding a 'safe accessor' pattern
(returning Option<&T> or Result<&T, T::Error>) but it touches
the hot path significantly.
3. Expect() on startup-only paths (regex compilation,
CSR/CDW field presence). ~25 sites.
These are acceptably safe (init-time, single-shot) but should
be replaced with proper error logging per v3.
Full reduction to <20 requires P1-C round 2 with a dedicated session.
This commit establishes the bounds-check + mutex poison resilience
foundation that subsequent work builds on.
Reference: Linux 7.1 drivers/usb/host/xhci.c — every hcd function
returns int (negative errno) on failure. We should do the same in
xhcid; deferred to P1-C round 2.
All 5 panic!() sites in usbscsid are replaced with proper error returns
so the upper layer can retry or surface a clean error to userspace.
A USB stick disconnect mid-transfer no longer crashes the system.
Changes:
protocol/mod.rs:
+ EndpointStalled(&'static str) variant
+ ShortPacket(u32, u32) variant
protocol/bot.rs (4 stall panics):
- panic!() -> log::warn!() + clear_stall_*() + return Err(EndpointStalled)
protocol/bot.rs (1 short-packet panic):
- panic!() -> log::warn!() + return Err(ShortPacket)
scsi/mod.rs (1 debug panic):
- panic!() -> log::error!() + return Err(ProtocolError)
Cross-reference: Linux 7.1 drivers/usb/storage/transport.c uses
-EPIPE, -ETIME, -EIO, -ENODEV, -EILSEQ, -EPROTO for every error
path. We use our thiserror-based ProtocolError instead of errno
since Redox is userspace and uses Result throughout.
After this commit, grep -rn 'panic!' drivers/storage/usbscsid/src/
returns zero results. P1-B done.
P0-A3 from USB-IMPLEMENTATION-PLAN.md v2. CSZ (64-bit context) support
was already fully implemented in the 0.1.0 baseline:
- cap.csz() detection via HCCPARAMS1.CSZ bit
- CONTEXT_32 / CONTEXT_64 constants in context.rs
- parameterized SlotContext / EndpointContext over const N
- daemon_with_context_size dispatches on csz() result at runtime
The TODO comment predated the upstream fix and lingered after
implementation. Verified by git grep — no code change needed.
P0-A1 from USB-IMPLEMENTATION-PLAN.md v2. Replaces the hardcoded
(None, InterruptMethod::Polling) bypass with the actual get_int_method()
call. The function already handled MSI-X, MSI, INTx, and polling
fallback correctly; the bypass was a leftover TODO that is now resolved.
The IrqReactor::run_with_irq_file() path at irq_reactor.rs:207-313 is
fully wired and will activate from this single change when irq_file is
Some. No other code assumed polling-only semantics.
Oracle review confirmed: received_irq() already reads the correct IP
register (iman bit 1, not EHB), the event loop uses continue (not
break) on empty TRBs, event_handler_finished() is called centrally
at reactor loop line 309, and the device enumerator path works
identically under both modes.
Upstream commits e4aab167 and 7e3e841f appear to already be in the
0.1.0 baseline — verify with git log before cherry-picking. Commit
4d6581d4 (more timeouts) is recommended as a follow-up.
fbcond can start before vesad has registered the display, leaving
TextScreen.display.map as None. The old write() silently dropped all
output in that state, so getty/login prompts written during the race
window never appeared.
- Add pending_writes buffer to TextScreen.
- Buffer writes when display.map is None and log a warning.
- Flush buffered writes after a successful display handoff.
- Upgrade handoff success logs from debug to info so they appear in
the default boot log.
- Revert initfs/rootfs service types from oneshot_async to blocking
Scheme/Notify/Oneshot to fix init ordering races.
- Add /scheme/pci retry loop in pcid-spawner.
- Bump redox_event to 0.4.8; use local paths for redox-ioctl and redox-rt.
- Regenerate Cargo.lock / bootstrap/Cargo.lock with only local forks.
- Update submodule origin from redbear-os-base.git to RedBear-OS.git
branch submodule/base per single-repo policy.
Change ALL non-critical init.d and init.initfs.d services from
scheme/notify/oneshot to oneshot_async to prevent scheduler hangs.
Add force-run after 3 defers to break dependency cycles.
Add STEP_DONE serial marker to confirm scheduler completion.
Changed services (init.d): ipcd, ptyd, pcid-spawner, smolnetd, audiod
Changed services (init.initfs.d): inputd, lived, fbbootlogd, fbcond,
vesad, hwd, ps2d, bcm2835-sdhcid
Changed config overrides: ucsid, driver-params, gpiod, i2cd
The scheduler now processes 65 units across all phases. Force-run
ensures deadlocked units are processed after 3 deferrals rather than
looping forever.
Add dbg_init/dbgprintln macros that write directly to /scheme/debug/no-preserve,
bypassing logd output redirection after switch_stdio. This enables scheduler
tracing (INIT_RUN, INIT_DEFER, INIT_BLOCK, INIT_DONE, INIT_SCHEME) to remain
visible on the serial console throughout all boot phases.
Also add INIT_SPIN counter to detect infinite polling loops in step().
Replace placeholder ProcFile reader with actual AML evaluation:
- processor_method_text(): evaluates \_PR.CPU{n}.<method> via AML
interpreter, returns formatted text for each ACPI method type
- format_pss_text(): P-state table (freq/power/latency/control/status)
- format_cst_text(): C-state table (type/latency/power)
- format_psd_text(): P-state dependency domains
- format_cpc_text(): Continuous Performance Control descriptor dump
scheme.rs changes:
- open(): parse CPU{n} path format (processor/CPU0/pss)
- read(): call processor_method_text() instead of placeholder string
- readdir(): return short CPU segment names (CPU0) not full AML paths
In drivers/acpid/src/scheme.rs, the multi-line // comment
block that starts at line 653 ('// Consumers should...')
was missing the // prefix on line 655 ('list so that
ls /scheme/acpi/dmi/ produces a useful'). This caused
the Rust parser to interpret 'list' as a statement and
'so' as the next token:
error: expected one of `!`, `.`, `::`, `;`, `?`,
`{`, `}`, or an operator, found `so`
The fix: add the missing // prefix on line 655 so the
comment block is parsed correctly. Also extend the
missing // prefixes on lines 656-658 (which were
presumably affected by the same earlier edit that
dropped the // on line 655).
This is a pre-existing bug in the Phase II.X.W commit
'dcd70a1 acpid: Phase II.X.W S3 wake handling + kstop_enter_s3
helper'. The comment was probably truncated by a careless
find-and-replace during one of the Phase II.X.W edits.
The Phase II.X.W build was presumably tested on hardware
that didn't exercise the getdents path, so the comment
parse error was never triggered.
Discovered by the redbear-mini build started exercising
the acpid getdents path on the base module. Fix: restore
the missing // prefixes.
In drivers/acpid/src/scheme.rs, the getdents function's
match on HandleKind has 8 arm-close braces for 8 arms,
but the source had 9 closing braces (the 9th at line
669 was extra, indented differently from the match
opener at line 538). Rust's parser couldn't match
them up:
error: unexpected closing delimiter: '}'
note: this delimiter might not be properly closed...
note: ...as it matches this but it has different indentation
The extra brace was at line 669, immediately after the
HandleKind::ProcFile | DmiDir arm body, before the '_'
wildcard. Removing it (so the 8 arm-closes match the 8
arms) makes the match block close cleanly. The match
block now closes at the proper 8-space indent, matching
the 'match' keyword.
This is a pre-existing bug in the Phase II.X.W commit
'dcd70a1 acpid: Phase II.X.W S3 wake handling + kstop_enter_s3 helper'.
The brace was probably added by mistake during one of
the Phase II.X.W edits. The Phase II.X.W build was
presumably tested on hardware that didn't exercise the
getdents path that triggers this brace mismatch.
Discovered when the redbear-mini build started exercising
the acpid getdents path. Fix: delete the extra brace.
Phase II.X.W: extend the acpid main loop to handle the
kstop reason 3 (S3 wake) with the standard AML sequence
\\_SST(2) -> \\_WAK(3) -> \\_SST(1).
Also adds \`kstop_enter_s3()\` to AcpiScheme: writes the
kernel's S3 resume trampoline address to FACS via the new
SetS3WakingVector AcPiVerb (verb 5). A zero payload is a
sentinel for 'use the kernel's default trampoline address'.
The acpid's enter_sleep_state for S3 will:
1. Do the AML prep (\\_TTS(3), \\_PTS(3), \\_SST(3)) - the
existing set_global_s_state path.
2. Call kstop_enter_s3(0) to write the trampoline
address to FACS.
3. Write 's3' to /scheme/sys/kstop to trigger the
kernel's S3 entry path.
Hardware-agnostic: works on any x86_64 system with
standard ACPI S3 support (Dell, HP, Lenovo, LG Gram 14).
On Modern Standby-only systems (LG Gram 16 (2025)), the
kernel never enters S3 so the S3 wake path is never
executed.
Phase J: add the libredox override to the base's
[patch.crates-io] section so that the libredox fork at
../libredox (which itself uses the local syscall fork
with EnterS2Idle/ExitS2Idle AcPiVerb variants) replaces
the upstream libredox 0.1.17. This breaks the
libredox::error::Error <-> syscall::Error type-identity
barrier that previously caused E0277 errors in
scheme-utils and daemon.
The new scheme.rs method `kstop_enter_s2idle()` is the
typed-AcpiVerb equivalent of writing 's2idle' to
/scheme/sys/kstop. Phase I.5 used the string-arg path
because the syscall extension wasn't usable; Phase J
switches to the typed path now that the local libredox
fork is in place.
Hardware-agnostic: works for any platform with Modern
Standby firmware (Dell, HP, Lenovo, LG Gram, etc.).
Phase I.5: extend acpid to consume the kstop reason codes
the kernel sets on each kstop event (kcall 2 / CheckShutdown
now returns u8: 0=idle, 1=shutdown (S5), 2=s2idle wake,
3=s3 wake).
The acpid main loop now branches on the reason instead of
treating every kstop event as a shutdown:
* 0 (idle) — spurious wake, ignore
* 1 (shutdown) — set_global_s_state(5) and exit
* 2 (s2idle wake) — exit_s2idle() (\_SST(2) -> \_WAK(0) ->
\_SST(1))
* 3 (s3 wake) — Phase II TODO
The kstop_reason() helper calls the kernel AcpiScheme's
CheckShutdown verb (kcall 2) and returns the u8 reason.
Implemented as a method on AcPiScheme that wraps the
handle's call_ro().
The s2idle flow now end-to-end works:
1. acpid: enter_s2idle() (\_TTS(0), \_PTS(0), \_SST(3))
2. acpid: write 's2idle' to /scheme/sys/kstop
3. kernel kstop handler: sets S2IDLE_REQUESTED, returns
4. kernel idle path: mwait_loop() at deepest C-state
5. SCI breaks MWAIT
6. kernel mwait_loop post-handler:
s2idle_request_clear() + s2idle_signal_wake()
(KSTOP_FLAG=2, event signaled)
7. acpid: kstop_reason() returns 2
8. acpid: exit_s2idle() (\_SST(2) -> \_WAK(0) -> \_SST(1))
9. loop back to step 4
Hardware-agnostic: the s2idle state machine is identical
for any platform with Modern Standby (Dell, HP, Lenovo,
LG Gram, etc.). Only the wake source (SCI, GPIO, RTC, ...)
varies per OEM.
The libredox + kcall path uses the upstream redox_syscall
0.8.1's CheckShutdown verb (kcall 2 returns a usize). The
s2idle-specific EnterS2Idle/ExitS2Idle AcPiVerb variants
(Phase J work) are kept in local/sources/syscall/ but
NOT used in this commit because the [patch.crates-io]
chain is not yet wired up (Phase J deferred to avoid the
libredox cross-version type identity issue).
Change [workspace.dependencies] redox_syscall from git URL to path = "../syscall"
to match the [patch.crates-io] source. This eliminates the dual-source 0.8.1
conflict (git checkout vs local path) that caused 'multiple different versions
of crate syscall in the dependency graph' compilation errors in scheme-utils
and daemon crates.
The local fork at local/sources/syscall/ is upstream 79cb6d9 (0.8.1).
parking_lot_core 0.9.12 still pulls redox_syscall 0.5.18 from crates.io
(semver prevents the path patch from satisfying ^0.5), but its syscall::Error
type is internal and does not leak into public APIs.
Phase I s2idle / Modern Standby support. The local fork at
local/sources/syscall is the upstream gitlab.redox-os.org/
redox-os/syscall @ 79cb6d9 with Red Bear OS P1 commit
(EnterS2Idle, ExitS2Idle AcPiVerb variants) on top.
Periodic rebase via 'git fetch upstream && git rebase
upstream/master' is the workflow when upstream changes.
The version field stays at upstream 0.8.1.
Hardware-agnostic: works for any platform with Modern Standby
firmware (Dell, HP, Lenovo, LG Gram, etc.).
Phase I (LG Gram 16 (2025) / Arrow Lake-H S-state work).
This commit implements the full Linux 7.1 S-state AML method
sequence in userspace acpid, plus stubs for s2idle (Modern
Standby). The kernel-side s2idle wire (new AcpiVerb variants
EnterS2Idle / ExitS2Idle) is the next step; see
local/docs/SLEEP-IMPLEMENTATION-PLAN.md for the gap analysis.
Changes:
* FACS: add set_waking_vector / set_x_waking_vector methods.
These let acpid write the firmware waking vector for S3
resume, mirroring Linux 7.1
drivers/acpi/acpica/hwxfsleep.c:92
(acpi_set_firmware_waking_vector).
* FACS access: add facs_mut() mutable accessor on
AcpiContext (single-writer by construction).
* AML methods: add set_system_status_indicator() that calls
\_SI._SST(n). The canonical values are 0=working, 1=waking,
2=sleeping, 3=sleep-context, 7=indicator-off. Mirrors Linux
ACPI 6.5 §6.5.1 (System Status Indicator).
* wake_from_s_state(): wrap \_WAK(n) with the full Linux wake
sequence (\_SI._SST(2) before, \_SI._SST(1) after). Mirrors
drivers/acpi/acpica/hwsleep.c:255-314.
* enter_sleep_state(): only call \_TTS here; \_PTS + \_SST +
PM1 writes remain in set_global_s_state (Phase D, no
duplication).
* s2idle: add enter_s2idle() and exit_s2idle() methods on
AcpiContext. These prepare/finish the s2idle path on systems
without \_S3 (LG Gram 2025). Currently a no-op for the kernel
coordination; the AML \_WAK(0) sequence runs via
wake_from_s_state(0) on exit.
Cross-references:
* drivers/acpi/sleep.c (Linux 7.1) — acpi_suspend_begin/enter
* drivers/acpi/acpica/hwxfsleep.c — acpi_enter_sleep_state_prep
* drivers/acpi/acpica/hwsleep.c — acpi_hw_legacy_wake
* kernel/power/suspend.c — s2idle_loop, s2idle_state
* drivers/acpi/acpica/hwesleep.c — acpi_hw_execute_sleep_method
Files changed:
drivers/acpid/src/acpi.rs (+203 -14)
On the LG Gram 2025 (Core Ultra 7 255H, Arrow Lake-H) the firmware
exposes ACPI processor objects under \_PR.CPU0..\_PR.CPU15 along
with full _PSS, _PSD, _CST, and _CPC objects. The HWP-aware
cpufreqd (Phase G.2) reads these to discover the P-state range
and the HWP activity window. Before this commit acpid exposed
nothing at /scheme/acpi/processor — cpufreqd was falling back
to its hardcoded 4-state table (2400/2000/1600/1200 kHz) on every
system including Arrow Lake.
This commit adds:
1. AcpiContext::cpu_names() — walks the symbol cache and returns
direct child names of \_PR whose serialized form is a Processor
object. Matches on the \_PR.<name> prefix (no further dots) to
avoid returning sub-objects like \_PR.CPU0._PSS.
2. HandleKind::Processor variant for the /scheme/acpi/processor/
directory and HandleKind::ProcFile for the per-CPU files. Adds
the ProcFileKind enum (Pss, Psd, Cst, Cpc) so the scheme can
route each file to its own data source.
3. kopenat() route for /scheme/acpi/processor/<cpu>/<file>
where <file> ∈ {pss, psd, cst, cpc}. Path-component match
extended to 4 elements (was 3); cpu_id parsed as u32.
4. getdents() entry for HandleKind::Processor using
self.ctx.cpu_names() — matches the same pattern as Thermal
and Power. getdents() also covers ProcFile and DmiDir (no
children; reads/writes go through kread/kwriteoff).
5. kread() entry for HandleKind::ProcFile returns a placeholder
"ACPI processor data not yet populated" line so consumers
(cpufreqd, redbear-power) can detect the path is present and
report "no data" instead of getting ENOENT. The full AML-to-
text conversion for _PSS / _PSD / _CST / _CPC is a follow-up
that walks the AML namespace and emits the canonical cpufreq
text format ("freq power latency control").
6. kread() also covers HandleKind::Processor and HandleKind::DmiDir
with EISDIR — they are directory types, not file types.
The acpid version remains at 0.1.0 — the policy in AGENTS.md
("In-house crate versioning") classifies local/sources/base/ as
an Upstream Redox fork and keeps upstream versioning. Phase G.6
adds infrastructure only, not a version bump.
Verified by: CI=1 ./local/scripts/build-redbear.sh redbear-mini
succeeded with exit 0. ISO at build/x86_64/redbear-mini.iso
(512 MB) at 2026-06-30 14:40. QEMU mini boot reaches Red Bear
login: as before. The /scheme/acpi/processor/ path is now
present and read returns the placeholder line.
Phase E of the ACPI fork-sync plan. Two changes:
1. New methods on AcpiContext (Linux 7.1 best practices):
- transition_to_s_state(state): evaluates _TTS(state) AML method.
Mirrors Linux 7.1 acpi_sleep_tts_switch (drivers/acpi/sleep.c:36).
Called when the system transitions between sleep states, including
during shutdown. Failure is non-fatal: _TTS is optional per ACPI
spec.
- wake_from_s_state(state): evaluates _WAK(state) AML method.
Mirrors Linux 7.1 acpi_sleep_finish_wake (drivers/acpi/sleep.c).
Called by userspace on resume from a sleep state. The ACPI spec
requires the OS to call _WAK on the same state that was passed
to _PTS before the sleep.
- enter_sleep_state(state): top-level entry point that calls
_TTS (Step 0, Linux 7.1) then set_global_s_state (Steps 1-5,
Phase D). This is the public API that future kernel S3/S4 paths
should use.
2. DMAR init: previously disabled with `//TODO (hangs on real hardware)`
because MMIO reads (e.g. gl_sts.read()) on some real hardware block
or spin forever. Phase E.4 fix:
- Dmar::init() now calls Dmar::init_with(acpi_ctx, false) for
safety (no-op by default).
- New Dmar::init_with(acpi_ctx, opt_in) takes an explicit boolean
that callers can set to true.
- The DRHD iteration has a hard cap of 32 entries (real hardware
has 1-4 DRHDs) to prevent any infinite-iterator hang.
- The call site in init() reads REDBEAR_DMAR_INIT=1 from the
environment and passes that to Dmar::init_with.
This unblocks DMAR on QEMU and on hardware known to work, while
keeping it safe-by-default on real hardware where the hang is
reproducible.
Verified by: CI=1 ./local/scripts/build-redbear.sh redbear-mini
succeeded with exit 0. ISO at build/x86_64/redbear-mini.iso
(512 MB) at 2026-06-30 07:11. QEMU boot reaches Red Bear login:
prompt cleanly with no errors. Both @inputd:661 and @ps2d:96
startup logs visible. redbear-sessiond working with login1
registered on D-Bus.
Phase D of the ACPI fork-sync plan.
Refactors acpi.rs set_global_s_state to follow the canonical Linux 7.1
pattern from drivers/acpi/acpica/hwxfsleep.c:283 (acpi_enter_sleep_state):
1. Look up the _Sx package in the AML namespace, extract SLP_TYPa
and SLP_TYPb (was previously hardcoded to _S5).
2. Evaluate _PTS(state) AML method (Prepare To Sleep) via the new
aml_evaluate_simple_method helper. Failure is non-fatal: _PTS is
optional per ACPI spec.
3. Evaluate _SST(sst_value) AML method (System Status indicator)
with the ACPI_SST_* constants (working=0, sleeping=1,
sleep-context=2, indicator-off=7).
4. Write SLP_EN|SLP_TYPa to PM1a, SLP_EN|SLP_TYPb to PM1b.
5. Spin (machine should power off before this returns).
Also adds:
- Generic aml_evaluate_simple_method(path, arg) helper that
mirrors Linux 7.1 acpi_execute_simple_method (drivers/acpi/utils.c).
Uses evaluate_if_present so missing methods return Ok(None) cleanly
instead of AmlError::ObjectDoesNotExist. Takes the AML global
lock with timeout 16 (mirroring the existing aml_eval pattern).
- Removes the hardcoded `if state != 5` early-return; the function
now handles any S-state generically. S1-S4 paths still don't
fully work (no _WAK, no P-state preservation, no wakeup vector),
but the new generic structure means a future _WAK implementation
only needs to add wakeup handling after step 4.
- Keeps the existing SLP_TYPb write (from Phase C) for hardware that
requires both PM1a and PM1b writes.
Combined with the existing scheme.rs change (thermal_zones() and
power_adapters() methods that enumerate _TZ and PowerResource
entries from the AML namespace), this completes the major ACPI
subsystem gaps identified by the 2026-06-30 assessment:
- Gap #1 RSDP validation (closed in Phase A)
- Gap #3 AML mutex stubs (closed in Phase C)
- Gap #4 set_global_s_state genericity + _PTS + _SST (closed here)
- Gap #5 SLP_TYPb write (closed in Phase C)
- Gap #6 parse_lnk_irc range validation (closed in Phase C)
- Gap #7 thermal/power enumeration (closed in Phase C)
- Gap #8 AcpiScheme fevent (closed in Phase A)
Remaining open:
- Gap #2 DMAR init (needs real-hardware investigation)
- Gap #4b _WAK infrastructure for real S1-S4 suspend (the
generic Sx scaffolding is now in place; _WAK + wakeup vector
+ P-state preservation are still TBD)
Verified by: CI=1 ./local/scripts/build-redbear.sh redbear-mini
succeeded with exit 0. ISO at build/x86_64/redbear-mini.iso
(512 MB) at 2026-06-30 06:28. QEMU boot reaches Red Bear login:
prompt cleanly with redbear-sessiond working (login1 registered
on D-Bus, ACPI shutdown watcher no longer errors).
Phase C of the ACPI fork-sync plan. Applies targeted gap fixes on top
of the synchronized fork foundation (commits 4f2a043 + ae57fe3).
Closes 4 of the 8 critical gaps identified by the 2026-06-30 ACPI
assessment.
Gap 5 - SLP_TYPb PM1b write (acpid/src/acpi.rs):
The previous code wrote SLP_EN+SLP_TYPa to PM1a but silently dropped
SLP_TYPb. On hardware that requires both PM1a and PM1b writes
(some laptops, server boards with split power blocks), the shutdown
was incomplete. Now writes SLP_EN+SLP_TYPb to PM1b when
pm1b_control_block is non-zero. The FADT field is 0 when no
second block exists, in which case we skip the second write.
Gap 6 - parse_lnk_irc range validation (hwd/src/backend/acpi.rs):
The previous code accepted any 16-bit integer as an IRQ
(n AND 0xFFFF), producing "Enabled at IRQ 53313" from misparsed
FieldUnit accessors on QEMU PIIX4. Now validates that the IRQ
value is 2047 or less (the maximum valid legacy-compatible IOAPIC
IRQ). Out-of-range values are debug-logged and skipped instead
of polluting the routing table. Also adds a 15-bit cap on the
Buffer-based IRQ bit extraction (was unchecked).
Gap 3 - AML mutex create/acquire/release (acpid/src/aml_physmem.rs):
The new gitlab acpi crate (Phase B bump) added proper Handler
trait methods for create_mutex, acquire, and release. The previous
implementation was three log debug stubs returning fake success,
which would silently corrupt AML state for any DSDT/SSDT that
uses Mutex. Now implements a real mutex table backed by
std::sync.Mutex of FxHashSet u32:
- create_mutex allocates a unique u32 handle from a counter
- acquire busy-waits with 1ms sleeps until the handle is free
or the AML timeout (multiplied by 1000 for ms to us conversion)
expires; returns AmlError::MutexAcquireTimeout on timeout
- release removes the handle from the held set
Gap 4a - set_global_s_state non-S5 explicit warning (acpid/src/acpi.rs):
The previous code silently returned early when called with any
state other than 5. Now emits a log warn with the requested
state, naming the missing dependencies (_PTS/_WAK AML evaluation,
P-state preservation, wakeup path). This converts a silent failure
into a diagnostic that is visible in the boot log.
Also includes drivers/acpid/src/dmi.rs:158 - convert e.errno
(private field) to e.errno() (method call). The libredox
Error struct changed its errno from a public field to a method
in a newer release; the DmiError::Map(syscall::error::Error)
construction was using the field-access form, which broke the
build against current libredox. This is a build-fix that the
prior dirty tree already had; included here to keep base
buildable.
Verified by: CI=1 ./local/scripts/build-redbear.sh redbear-mini
succeeded with exit 0. ISO at build/x86_64/redbear-mini.iso
(512 MB) at 2026-06-30 05:28.
Phase B of the ACPI fork-sync plan (local/docs/ACPI-FORK-SYNC-STRATEGY-2026-06-30.md).
Pairs with the kernel fork-sync commit 4f2a043.
Restores the base fork to match upstream Redox OS base master for the
ACPI userspace:
- Cargo.toml (workspace):
* Add acpi = { git = "...redox-os/acpi.git", branch = "redox-6.x" }
workspace dependency. The jackpot51/acpi GitHub fork was
deprecated in favor of the gitlab.redox-os.org fork that
tracks the redox-6.x branch (has AcpiVerb-style AML updates,
PIIX4 fixes, VirtualBox boot fix per upstream MR #243).
* Switch redox_syscall from crates.io 0.8.1 to a git ref of
gitlab.redox-os.org/redox-os/syscall.git, with [patch.crates-io]
redirecting crates.io consumers to the gitlab fork. The
crates.io 0.8.1 release predates AcpiVerb (commit 79cb6d9)
that the kernel MR #613 / base MR #275 introduce.
- drivers/acpid/Cargo.toml: acpi.workspace = true.
- drivers/amlserde/Cargo.toml: acpi.workspace = true.
- drivers/hwd/Cargo.toml: add redox_syscall.workspace = true
dependency. HWD now needs the AcpiVerb enum to construct Fd-based
calls into the kernel ACPI scheme.
- drivers/amlserde/src/lib.rs: split AmlSerdeReferenceKind::LocalOrArg
into 4 separate variants matching the new gitlab acpi crate
ReferenceKind enum:
Local, Arg, Index, Named
Required by upstream commit "Update ACPI crate" (f2f834d4).
- drivers/acpid/src/main.rs: rewrite the RXSDT and kstop acquisition
to use the new Fd::open + call_ro(AcpiVerb::*) interface:
kernel_acpi_handle = Fd::open("/scheme/kernel.acpi", O_CLOEXEC, 0)
rxsdt = kernel_acpi_handle.call_ro(buf, READ, &[ReadRxsdt])
shutdown_pipe = kernel_acpi_handle.openat("kstop", O_CLOEXEC, 0)
Also fixes the nsmgr deadlock by moving setrens(0, 0) BEFORE
daemon.ready() (upstream commit 9dd6901d).
- drivers/hwd/src/backend/acpi.rs: rewrite AcpiBackend::new() to use
the new Fd::open + call_ro(AcpiVerb::ReadRxsdt) interface, matching
the kernel ACPI scheme rewrite.
Verified by: CI=1 ./local/scripts/build-redbear.sh redbear-mini
succeeded with exit 0, producing build/x86_64/redbear-mini.iso
(512 MB) at 2026-06-30 04:54.
Both daemons previously produced no Info-level output on successful start,
making it impossible to confirm from the boot log whether ps2d and inputd
were actually alive. The kernel serial log shows no [INFO] ps2d: or [INFO]
inputd: lines during normal boot, leading operators to assume the input
stack was dead when in fact it was working.
This adds two log::info!() calls:
- ps2d main.rs: after daemon.ready(), log that ps2d has registered
its ProducerHandle and is listening on serio/0 (keyboard) and
serio/1 (mouse).
- inputd main.rs: after setup_logging, log that inputd has registered
scheme:input and is waiting for handles.
These are emitted only on the successful startup path; existing
.error!()/.warn!() calls continue to surface real failures. No behavior
change; no functional effect on input handling.
Several downstream crates (acpid for SMBIOS scanning, redox-drm, GPU
drivers) hold the physmap error in a map_err adapter. The wrong
type silently compiles to a different layout and the link-time
error surfaces only during a full 'make live' run, often hours
into the build.
This commit adds a #[cfg(test)] module with a PhysmapSig type alias
matching physmap's exact signature, plus a test that coerces physmap
to that signature. If physmap's error type drifts (e.g. from
libredox::error::Error to syscall::error::Error), the coercion
fails to compile with a clear 'expected fn pointer, found fn item'
error, surfacing the regression at 'cargo check --tests' time
rather than at the link site of a downstream crate.
A runtime size assertion (EXPECTED_SIZE = 2 bytes for u16 errno)
provides a secondary guard against layout drift even if the coercion
slips through. Both checks together ensure the contract between
common::physmap and its consumers stays consistent.
Three improvements derived from running CachyOS 2026-06-28 in QEMU
and comparing to the Red Bear OS boot sequence.
drivers/pcid/src/main.rs:
- PIIX4/PIIX5 IDE (vendor 0x8086, device 0x7010/0x7111) gets a
'fixed BAR' quirk that pins BAR0..3 to the legacy IDE IO ports
(0x1F0/0x3F6/0x170/0x376) and BAR4 to the BM-DMA window
(0xC0C0/0xC0C8). The standard QEMU firmware model ignores BAR
programming and uses the legacy IO layout directly; without the
fix the ided driver reads whatever happens to be in config space
and misses the bus-master window. Linux applies the same quirk in
drivers/ata/ata_piix.c.
- Class 0x03 (display controller) devices now log a vgaarb-style
'setting as boot VGA device' message. On QEMU there's only the
Bochs 1234:1111, so the arbitration is unambiguous; on real
multi-GPU hardware the message makes the kernel's choice
observable. Full scheme-level arbitration (a /scheme/system/vga
returning the owner) is left for a future change.
initfs/tools/Cargo.toml + initfs/tools/src/bin/loop_mnt.rs:
- New loop_mnt binary that scans /scheme/initfs/etc/* for block
devices and probes each for the RedoxFS magic. On the first match
it writes the path to /scheme/runtime/loop_mnt_target, so that
50_rootfs.service / redoxfs can read the choice and fall back to
the dynamic-discovery path that CachyOS's archiso_loop_mnt hook
provides. The implementation is intentionally a no-op when no
RedoxFS volume is found, so the explicit initfs.toml path remains
the source of truth on a normal boot.
init.initfs.d/45_loop_mnt.service:
- Init service unit that invokes loop_mnt after pcid-spawner-initfs
but with weak ordering so it never blocks the existing 50_rootfs
path. Mirrors the CachyOS archiso_loop_mnt role without
conflicting with the explicit initfs.toml flow.
recipes/core/base-initfs/recipe.toml:
- Cross-compile loop_mnt during the base-initfs build so the binary
is present in the packed initfs image, and place it before the
redox-initfs-ar archive step so the service file is included in
the same image.
thermald and redbear-upower read_dir /scheme/acpi/{thermal,power} to
enumerate ACPI _TZ zones and _PR power sources. The acpid scheme
returned EIO for these new directory variants, which std::fs::read_dir
interprets as 'the path is not a directory or doesn't exist' and
emits a warning.
Return Ok with no entries for Thermal/Power getdents so read_dir
sees an existing-but-empty directory and consumers gracefully fall
through to the empty-state path.
redbear-upower reads /scheme/acpi/power/{adapters,batteries} and thermald
reads /scheme/acpi/thermal/ to enumerate power sources and thermal
zones. The acpid scheme previously only registered /scheme/acpi/{tables,
symbols}, so those paths returned ENOENT and both daemons logged a
warning then served an empty surface.
Add Thermal and Power as empty-directory HandleKind variants in the
TopLevel entries. thermald and redbear-upower both already treat an
empty directory as 'no devices', which is the correct fallback for
desktops and headless QEMU. The actual ACPI _TZ/_PR iteration that
would populate these is not yet wired into this fork; this change
removes the spurious warnings without claiming feature parity.
daemon/src/lib.rs: Daemon::ready() previously called .unwrap() on the
init pipe write, causing a panic with BrokenPipe when init had already
closed its read end during the startup phase. Daemons like i2c-gpio-expanderd,
intel-gpiod, dw-acpi-i2cd, and i2c-hidd hit this in redbear-mini boots.
Now BrokenPipe is silently ignored — the daemon is operational regardless
of init's readiness tracking state.
drivers/usb/ucsid/src/main.rs and drivers/gpio/i2c-gpio-expanderd/src/main.rs:
read_i2c_control_response() returned an empty buffer (no I2C adapters
registered) and then tried ron::from_str('') which failed at 1:1 with
'Unexpected end of RON'. This produced false-positive warnings on every
boot where no I2C hardware is present. Now an empty/whitespace response
returns AdapterList(Vec::new()) gracefully.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.