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.