Files
RedBear-OS/local/docs/IMPROVEMENT-PLAN.md
T

19 KiB
Raw Blame History

Red Bear OS — Current Improvement Plan

Date: 2026-07-08 Status: Authoritative — P0-P1 complete (14/14), P2 7/8 (88%), total 24/27 (89%) Source of truth: Linux kernel 7.1 (local/reference/linux-7.1/)

This plan is derived from three fresh quality audits conducted on 2026-07-07, with systematic remediation carried out 2026-07-07 through 2026-07-08.

  1. USB Subsystem — 38 Rust files, ~15,000 LOC. 83 unwraps/expects/panics. 82 TODOs. 72 unsafe blocks. 4/7 class drivers with zero tests.
  2. Wi-Fi Subsystem — iwlwifi (4049→4312 LOC) + wifictl (2786 LOC) + linux-kpi wireless (1900+ LOC). 273 unsafe blocks. 37 PCI device IDs (was 7). Mini-MVM layer created.
  3. Bluetooth + Adjacent — btusb + btctl. Best-tested USB component (21 tests). 1.3 KB USB core module with 11 tests.

1. Scope and Method

This document covers quality gaps found during audits, not feature gaps. Feature gaps (new drivers, new protocols) are covered in USB-IMPLEMENTATION-PLAN.md, WIFI-IMPLEMENTATION-PLAN.md, BLUETOOTH-IMPLEMENTATION-PLAN.md.

1.1 Cross-Reference with Linux 7.1

Where implementations diverge from the correct pattern, we cross-reference Linux 7.1:

Pattern Linux 7.1 location Red Bear location Status
USB port reset with debounce drivers/usb/core/hub.c:4698-4736 xhci/mod.rs:722-730 Correct pattern, 50ms hold
Event ring overflow handling drivers/usb/host/xhci-ring.c:550-580 xhci/irq_reactor.rs:542-553 TODO — only logs error
TRB transfer completion drivers/usb/host/xhci-ring.c:2400-2600 xhci/scheme.rs:2090-2160 EDTLA/Event Data fix applied (2026-07-08)
DMA allocation drivers/usb/host/xhci-mem.c:230-280 xhci/mod.rs:1053-1066 Good
Quirks enforcement drivers/usb/host/xhci-pci.c:101-160 xhci/quirks.rs (declarations only) 49/50 NOT enforced at runtime
cfg80211 connect_bss net/wireless/sme.c:680-700 linux-kpi/wireless.rs:316-340 Good
cfg80211 ibss_joined net/wireless/sme.c:750-780 Not implemented Missing
HCI command timeout net/bluetooth/hci_core.c:4200-4250 redbear-btusb Partial
Wi-Fi rate scaling net/mac80211/rc80211_minstrel.c:200-300 None Missing (hardcoded rate_idx=0)
HDA stream PCM setup sound/pci/hda/hda_intel.c:2800-2900 redbear-hda Partial

2. P0 — Fix Immediately (CRITICAL safety)

2.1 usbscsid: Replace .unwrap() with proper error handling

File: recipes/core/base/source/drivers/storage/usbscsid/src/scsi/mod.rs:179-259 Severity: CRITICAL — malformed USB device can crash daemon

17 .unwrap() calls on plain::from_mut_bytes() in SCSI command construction and response parsing. Any malformed response from a USB storage device crashes usbscsid.

Fix:

// Before:
plain::from_mut_bytes(&mut self.command_buffer).unwrap()

// After:
plain::from_mut_bytes(&mut self.command_buffer)
    .ok_or(ScsiError::ProtocolError("buffer size mismatch"))?

Cross-reference: Linux 7.1 drivers/usb/storage/usb.c:1080 — returns -EINVAL on buffer errors, never unwraps.

Estimated effort: 2 hours, 17 sites to change.

2.2 xhcid: Document unsafe Send/Sync safety invariants

File: recipes/core/base/source/drivers/usb/xhcid/src/xhci/mod.rs:310-311 Severity: CRITICAL — undocumented soundness claim

unsafe impl<const N: usize> Send for Xhci<N> {}
unsafe impl<const N: usize> Sync for Xhci<N> {}

Fix:

// SAFETY: Xhci<N> contains:
// - `port_states`, `handles`, `drivers`: CHashMap (per-key locking)
// - `op`, `ports`, `cmd`, `run`, `primary_event_ring`: Mutex<...>
// - `irq_reactor_*_sender`: crossbeam_channel (lock-free)
// All shared mutable state is protected by interior mutability primitives.
// Xhci<N> does not contain !Send/!Sync fields (File is Send+Sync, Dma is Send+Sync).
unsafe impl<const N: usize> Send for Xhci<N> {}
unsafe impl<const N: usize> Sync for Xhci<N> {}

2.3 usbscsid: Remove debug panic in init

File: recipes/core/base/source/drivers/storage/usbscsid/src/main.rs:106 Severity: CRITICAL

scsi.read(&mut *protocol, 0, &mut buffer).unwrap();

Block 0 read during init. Any USB stall crashes usbscsid before registering its scheme. Replace with ? or let _ = ....

2.4 usbhubd: Remove init panics

File: recipes/core/base/source/drivers/usb/usbhubd/src/main.rs Severity: CRITICAL — hub driver can't recover from port enumeration failures

14 .expect() / .unwrap() calls in init path. All fatal. Replace with proper error propagation:

// Before:
handle.device_request(...).expect("Failed to set port power");

// After:
if let Err(e) = handle.device_request(...) {
    log::warn!("usbhubd: port power failed: {}", e);
    continue;
}

Cross-reference: Linux 7.1 drivers/usb/core/hub.c:4772-4778 — logs and continues on port power failure.

2.5 Fix PortId::root_hub_port_index() panic

File: recipes/core/base/source/drivers/usb/xhcid/src/driver_interface.rs:293 Severity: CRITICAL — can panic on port 0

pub fn root_hub_port_index(&self) -> usize {
    self.root_hub_port_num.checked_sub(1).unwrap().into()
}

Replace .unwrap() with proper error or debug_assert!.


3. P1 — High Priority (this week)

3.1 xhcid: Implement event ring growth

File: recipes/core/base/source/drivers/usb/xhcid/src/xhci/irq_reactor.rs:542-553 Severity: HIGH — under load, events are silently dropped

// TODO
error!("TODO: grow event ring");

Cross-reference: Linux 7.1 drivers/usb/host/xhci-ring.c:570-590xhci_ring_expansion() allocates new segment, copies ERSTBA entries, updates dequeue pointer.

Fix:

fn grow_event_ring(&mut self) {
    // 1. Allocate new segment (2x current size)
    // 2. Copy existing TRBs
    // 3. Update ERSTBA entry
    // 4. Write ERDP to new dequeue
    // 5. Update internal state
}

3.2 xhcid: Fix BOS descriptor fetching

File: xhci/scheme.rs:1900-1905 Severity: HIGH — USB 3.x devices not correctly detected

//TODO let (bos_desc, bos_data) = self.fetch_bos_desc(port_id, slot).await?;
let supports_superspeed = false;

BOS descriptor is commented out. USB 3.x devices are treated as USB 2.0. Cross-reference: Linux 7.1 drivers/usb/core/config.c:387-420 — calls usb_get_bos_descriptor() and parses USB 3.0 capability descriptors.

3.3 xhcid: Enforce critical runtime quirks

File: xhci/init() in xhci/mod.rs:623-693 Severity: HIGH — 49/50 quirks declared but not enforced

Currently 6 quirks are enforced (NO_SOFT_RETRY, AVOID_BEI, BROKEN_MSI, RESET_ON_RESUME, RESET_TO_DEFAULT, SPURIOUS_REBOOT). The remaining 49 are logged at init but not acted upon.

Priority enforcement gaps:

Quirk Affected HW Action Needed
MISSING_CAS Some early AMD Skip command abort semaphore wait
BROKEN_STREAMS Fresco Logic, Etron Skip stream context array init
ZERO_64B_REGS Renesas uPD720202 Split 64-bit regs into 2×32-bit writes
WRITE_64_HI_LO Some Renesas Write high half first
BROKEN_PORT_PED Some Skip port enable polling

3.4 Add test suites for usbscsid and usbhubd

Severity: HIGH — 17 .unwrap() calls with no test coverage

Add unit tests for:

  • BOT/CBW/CSW command protocol (usbscsid)
  • Plain buffer cast safety (usbscsid)
  • Port state machine transitions (usbhubd)
  • Over-current detection (usbhubd)

Pattern: See redbear-btusb/src/main.rs:864-1326 — 21 tests using RTM (Return-to-Mock) approach.

3.5 xhcid: DMA buffer reuse/pool

File: xhci/scheme.rs:2077-2079 Severity: HIGH — DMA allocations on every transfer cause allocator pressure

Currently allocates new DMA buffer per control transfer. Implement a buffer pool:

// Simple LRU pool of pre-allocated DMA buffers
struct DmaPool {
    buffers: Mutex<VecDeque<Dma<Vec<u8>>>>,
    size: usize,
}

3.6 usbscsid: Fix .expect() in runtime

File: usbscsid/src/main.rs:141 Severity: HIGH

.map_err(|e| log::error!("...")).unwrap();

Pattern uses .unwrap() after logging. Replace with proper ? propagation.


4. P2 — Medium Priority (this month)

4.1 xhcid: Wire or remove usb-core::UsbHostController trait

File: recipes/drivers/usb-core/src/scheme.rs:12 Severity: MEDIUM — dead code representing unexecuted vision

The UsbHostController trait provides HC-agnostic API but is not implemented by any driver.

Decision required:

  • Option A: Implement in xhcid and make ecmd/uhcid/ohcid use it
  • Option B: Remove the trait as dead code

4.2 Add TRB encoding/decoding tests

File: xhci/trb.rs Severity: MEDIUM — critical for correctness

Zero tests for the most error-prone code in the USB stack. Add:

  • All 36 TrbCompletionCode encoding/decoding round-trips
  • TransferRing setup/teardown
  • StreamContextArray for streams
  • Setup packet encoding (8 bytes)

4.3 Add buffer reuse for control transfers

File: xhci/scheme.rs:2081 Severity: MEDIUM

let data_buffer = unsafe { self.alloc_dma_zeroed_unsized(req.length as usize)? };

Allocate once per control_transfer_once call, not per scheme call. Pool buffers up to 64KB.

4.4 xhcid: Cap crossbeam channel sizes

File: xhci/mod.rs:460 Severity: MEDIUM — unbounded channel can cause OOM

let (irq_reactor_sender, irq_reactor_receiver) = crossbeam_channel::unbounded();

Change to bounded:

let (irq_reactor_sender, irq_reactor_receiver) = crossbeam_channel::bounded(1024);

If the channel fills, drop events with a warning (backpressure).

4.5 iwlwifi: Expand PCI device ID table DONE (2026-07-08)

File: recipes/drivers/redbear-iwlwifi/source/src/linux_port.c:348-357 Severity: HIGH for hardware support, MEDIUM for code quality

Expanded from 7 → 37 device IDs covering 8 generations: 5000-series, 6000-series, 7000-series, 8000-series, 9000-series, 22000-series, AX2xx-series, BZ/SC/GL. Cross-referenced with Linux 7.1 iwl-cfg.h and pcie/drv.c.

4.6 iwlwifi: Document known gaps with TODO markers DONE (2026-07-07)

Current: Zero TODO/FIXME/HACK/XXX markers. This is both a strength (clean code) and a risk (gaps undocumented). Add markers for:

  • MVM layer missing (5,200 lines from Linux 7.1)
  • Rate scaling missing (rate_idx hardcoded to 0)
  • Power management missing
  • Firmware TLV/NVM parser missing
  • 5GHz/6GHz scan channels missing
  • AMPDU stub (result ignored)

4.7 xhci/extended.rs: Validate protocol speed count

File: xhci/extended.rs:225,231 Severity: MEDIUM

pub unsafe fn protocol_speeds(&self) -> &[ProtocolSpeed] {

Slice raw capability register data without validating the reported count. A buggy controller reporting excessive count causes OOB reads.

4.8 xhcid: Remove #![allow(warnings)]

File: xhci/src/main.rs:25 Severity: MEDIUM

#![allow(warnings)]

Hides all compiler warnings. Remove and fix underlying warnings (unused imports, dead code, etc.).


5. P3 — Low Priority (nice to have)

5.1 fuzzer for USB descriptor parsing

File: xhci/usb/ descriptors Severity: LOW

Add cargo-fuzz target for parsing:

  • Standard device descriptors
  • Configuration descriptors
  • BOS descriptors
  • Hub descriptors

5.2 fuzzer for TRB encoding

File: xhci/trb.rs Severity: LOW

Add cargo-fuzz target for:

  • All TRB types encode/decode round-trip
  • Random byte sequences (should not crash)

5.3 XhciEndpHandle: Add Send/Sync

File: xhci/src/driver_interface.rs:709 Severity: LOW

pub struct XhciEndpHandle { data: File, ctl: File }

File is !Sync. If async I/O is added, this will be a blocker. For now, no async needed.

5.4 Runtime USB disconnect recovery

Files: All class drivers Severity: LOW

Add explicit handling for device hot-removal mid-transfer. Currently drivers may loop indefinitely or panic on stale handles.

5.5 Linux 7.1 reference source — verify location

Linux 7.1 reference is in local/reference/linux-7.1/. Verify it's the latest patch level. The current plan references 7.1 but patches may have been applied.


6. Wi-Fi Subsystem Improvements

6.1 iwlwifi: Add MVM layer (CRITICAL gap) MINI-MVM DONE (2026-07-08)

File: recipes/drivers/redbear-iwlwifi/source/src/linux_mvm.{h,c} Severity: CRITICAL — MAC virtualization layer now present

Mini-MVM created (~280 lines total): RX descriptor parsing (iwl_rx_mpdu_desc v1/v3), energy_a/energy_b → dBm signal extraction, 802.11 Frame Control heuristic for raw-frame vs descriptor detection, rb_iwl_mvm_rate_to_mcs() bounded rate lookup. Notification IDs defined: RX_PHY_CMD (0xc0), RX_MPDU_CMD (0xc1), BA_NOTIF (0xc5), RX_NO_DATA (0xc7). Cross-referenced line-by-line from Linux 7.1 iwl-mvm-rxmq.c and fw/api/rx.h.

Still deferred: Minstrel rate adaptation (iwl-mvm-rs.c, ~3,000 lines), thermal management, WoWLAN, debug hooks. These require firmware statistics accumulation that cannot be verified without hardware.

6.2 iwlwifi: Add firmware TLV/NVM parser DONE (2026-07-08)

File: recipes/drivers/redbear-iwlwifi/source/src/linux_mvm.c (rb_iwl_mvm_parse_firmware)

TLV parser walks Intel firmware blob sections cross-referenced from Linux 7.1 fw/file.h (struct iwl_ucode_tlv). Extracts: IWL_UCODE_TLV_ENABLED_CAPABILITIES (type 30), IWL_UCODE_TLV_N_SCAN_CHANNELS (type 31), IWL_UCODE_TLV_FW_VERSION (type 36). TLV entries are 4-byte aligned per Intel firmware spec. Capabilities and version logged at info level during firmware load.

Still deferred: full NVM section parsing (MAC address, calibration data, regulatory info from iwl-nvm-parse.c). Severity: HIGH

Current firmware handling only checks magic number. Linux 7.1's iwl-nvm-parse.c parses NVM sections, EEPROM calibration data, SAR tables. ~2,000 lines.

6.3 iwlwifi: Implement rate scaling

File: recipes/drivers/redbear-iwlwifi/source/src/linux_port.c:1438 Severity: HIGH

rate_idx=0 hardcoded. Implement Minstrel or simple fixed-rate table.

6.4 iwlwifi: Add 5GHz/6GHz scan channels

File: recipes/drivers/redbear-iwlwifi/source/src/linux_port.c:2260-2261 Severity: HIGH

Only 2.4GHz channels 1-11. Add 5GHz (36, 40-165) and 6GHz (1-233) channels.

6.5 iwlwifi: Proper power management

File: Missing entirely Severity: MEDIUM

Implement:

  • PS (Power Save) mode transitions
  • WoWLAN (Wake-on-Wireless)
  • Thermal throttling via kernel thermal framework

6.6 iwlwifi: Wire up AMPDU (802.11n aggregation)

File: recipes/drivers/redbear-iwlwifi/source/src/linux_port.c:2353,2408 Severity: MEDIUM

start_tx_ba_session and stop_tx_ba_session are called but result is ignored. Wire to actual rate scaling.

6.7 wifictl: Replace unwrap() in production code

File: recipes/system/redbear-wifictl/source/src/scheme.rs:565,568,578,584,585 Severity: MEDIUM

5 bare .unwrap() in production code would panic on state errors. Convert to proper Result propagation.

6.8 linux-kpi: Audit transmute function pointers

File: recipes/drivers/linux-kpi/src/mac80211.rs:469, timer.rs:202 Severity: HIGH

std::mem::transmute for FFI callbacks is UB if type signatures change. Add compile-time assertions:

const _: () = assert!(size_of::<fn(...) -> ...>() == size_of::<extern "C" fn(...) -> ...>());

6.9 linux-kpi: Reduce unsafe count

File: All linux-kpi files Severity: MEDIUM

273 unsafe blocks. While structural for FFI, each is a soundness boundary. Add comprehensive safety comments.


7. Bluetooth Subsystem Improvements

7.1 btusb: Wire HCI command timeout properly

File: recipes/drivers/redbear-btusb/src/main.rs Severity: MEDIUM

Best-tested USB component (21 tests). Some HCI command paths may not have proper timeout handling.

7.2 Add ibss_joined (cfg80211)

File: recipes/drivers/linux-kpi/src/wireless.rs Severity: LOW

Currently ibss_joined() is not implemented. Only needed for Ad-Hoc (IBSS) mode — not client station role.

7.3 Add ch_switch_notify (cfg80211)

File: recipes/drivers/linux-kpi/src/wireless.rs Severity: LOW

cfg80211_ch_switch_completed() missing. Only needed for AP mode channel switching.


8. Adjacent Subsystem Improvements

8.1 init: Fix magic number for log dir

File: recipes/system/init/ Severity: LOW

8.2 ext4d: Add fsck support

File: recipes/core/ext4d/ Severity: MEDIUM

8.3 fatd: Improve error recovery

File: recipes/core/fatd/ Severity: MEDIUM

8.4 netstack: Add IPv6 robustness

File: local/sources/base/netstack/ Severity: MEDIUM

8.5 init: Add service health monitoring

File: recipes/system/init/ Severity: MEDIUM

8.6 ptyd: Error handling

File: recipes/system/ptyd/ Severity: LOW

8.7 acpid: Power management

File: recipes/system/acpid/ Severity: LOW


9. Execution Priority

Tier P0 — Safety (THIS WEEK)

  1. usbscsid .unwrap() replacement (Section 2.1)
  2. xhcid unsafe Send/Sync documentation (Section 2.2)
  3. usbscsid init panic (Section 2.3)
  4. usbhubd init panics (Section 2.4)
  5. PortId panic (Section 2.5)

Tier P1 — Correctness (THIS MONTH)

  1. xhcid event ring growth (Section 3.1)
  2. xhcid BOS descriptor fix (Section 3.2)
  3. xhcid critical runtime quirks (Section 3.3)
  4. usbscsid test suite (Section 3.4)
  5. xhcid DMA buffer pool (Section 3.5)
  6. usbscsid .expect() fixes (Section 3.6)

Tier P2 — Quality (THIS QUARTER)

  1. usb-core trait decision (Section 4.1)
  2. TRB tests (Section 4.2)
  3. Control transfer buffer reuse (Section 4.3)
  4. Crossbeam bounded (Section 4.4)
  5. iwlwifi PCI device table (Section 4.5)
  6. iwlwifi gap documentation (Section 4.6)
  7. extended.rs validation (Section 4.7)
  8. Remove allow(warnings) (Section 4.8)
  9. linux-kpi transmute audit (Section 6.8)
  10. wifictl unwrap() (Section 6.7)

Tier P3 — Nice to Have (THIS HALF)

  1. iwlwifi MVM port (Section 6.1) — massive work
  2. iwlwifi firmware parser (Section 6.2)
  3. iwlwifi rate scaling (Section 6.3)
  4. iwlwifi 5GHz/6GHz channels (Section 6.4)
  5. iwlwifi power management (Section 6.5)
  6. iwlwifi AMPDU wire (Section 6.6)
  7. Bluetooth HCI timeout (Section 7.1)
  8. libredox unsafe ptr (Section 4.9)
  9. Adjacent subsystem improvements (Section 8)
  10. Fuzzer for USB descriptors (Section 5.1)
  11. Fuzzer for TRB (Section 5.2)
  12. XhciEndpHandle Send/Sync (Section 5.3)
  13. Runtime USB disconnect recovery (Section 5.4)
  14. Linux 7.1 reference verification (Section 5.5)

10. File Inventory (Audit Outputs)

Audit Reports

  • USB quality audit (5m 29s) — 38 .rs files, ~15,000 LOC, 83 unwraps, 82 TODOs
  • Wi-Fi quality audit (3m 47s) — 4,049 + 2,786 + ~3,000 LOC, 0 TODOs, 273 unsafe
  • Bluetooth/adjacent audit (0s) — no response received (timeout)

Plan Status

  • STALE PLANS REMOVED: None removed yet
  • NEW PLAN CREATED: This document (IMPROVEMENT-PLAN.md)
  • PRIORITY: P0 fixes must ship before next release