Complete the Linux-aligned seat-takeover primitive set: a raw consumer can take
an EXCLUSIVE grab of the input stream by writing a single control byte to its
own consumer_raw handle (1=grab, 0=ungrab) — self-identifying, unlike the
shared control fd. While a grab is held:
* events route ONLY to the grabbing handle;
* the text console AND every other raw tap are suspended; and
* the grab is released automatically when the handle closes, so a compositor
that crashes cannot wedge input away from the console (Linux
__input_release_device).
A second grab attempt by a different handle returns EBUSY. Additive and
behaviour-preserving: grab defaults to None, so nothing changes until a client
grabs. new_raw() now opens read+write and ConsumerHandle::set_grab() drives it.
Together with set_vt_mode (KDSKBMODE) this gives seatd/a compositor the full
grab + VT-mode takeover surface. Compile-checked for x86_64-unknown-redox;
boot-validation pending build-green.
Add control kinds 3/4 (set VT graphics/text mode) and a graphics_vts set.
When a VT is claimed by a graphical client, the console `Consumer` for that VT
is suspended — cooked bytes stop being delivered to the text console — while
the raw device tap (consumer_raw) keeps feeding the compositor. This is the
RedBear equivalent of Linux KDSKBMODE(K_OFF)/KD_GRAPHICS silencing the console
keyboard + n_tty for a VT owned by a Wayland compositor.
Behaviour-preserving by default: graphics_vts is empty until a compositor
opts in via ControlHandle::set_vt_mode(vt, true), so text-console delivery is
unchanged. Two control kinds are used instead of a bool to keep the
ControlEvent ABI unchanged.
Full device-grab arbitration (exclusive routing / EVIOCGRAB) and the
VT_PROCESS switch-ack handshake remain TODO — the raw broadcast is sufficient
for a single compositor. Part of the Linux-aligned input-stack consolidation.
Compile-checked for x86_64-unknown-redox; boot-validation pending build-green.
Add a new `consumer_raw` handle to scheme:input — a raw, always-on device
tap modelled on the Linux evdev handler. Unlike the console `consumer`, it:
* is NOT bound to a VT, so it receives events regardless of which VT is
foregrounded (a background compositor keeps getting input); and
* receives the *pre-keymap* event stream — the console keymap is now
applied only on the console `consumer` path, never on the raw tap.
The producer write path snapshots the raw event bytes before the keymap
stamping loop and fans them out to every ConsumerRaw handle unconditionally,
in parallel with the existing VT-gated, keymapped console fan-out (which is
byte-for-byte unchanged — no console-login regression).
This is the RedBear equivalent of evdev being a peer handle off the raw input
core: libinput/xkbcommon (via evdevd) require raw scancodes, which the old
wiring — evdevd reading the keymapped, VT-gated console consumer — could not
provide. Adds ConsumerHandle::new_raw() for consumers.
Part of the Linux-aligned input-stack consolidation
(local/docs/INPUT-STACK-LINUX-ALIGNMENT-PLAN.md). Compile-checked for
x86_64-unknown-redox; boot-validation pending build-green (acpi-rs).
30_redox-drm.service requires_weak now targets
40_driver-manager-initfs.service; stale dormant-era comments updated in
00_driver-manager.service and 45_loop_mnt.service.
00_base.target, 10_evdevd, 10_smolnetd referenced 00_pcid-spawner.service
in requires_weak — after the retirement init logged 'unit
00_pcid-spawner.service not found'. All three now depend on
00_driver-manager.service.
Add public connect_op_regions() (ACPICA evrgnini.c): \_SB._REG(space, 1)
per installed handler space plus <device>._REG(space, 1) per device holding
an OpRegion of that space. initialize_namespace() now delegates to it and
its ACPICA-order opening (_INI, _SB._INI) is restored after 0c11c2b5
captured a broken intermediate edit. Completes the _REG wiring begun in
c3a27717 (which delivered the acpid-side call).
Commit 0c11c2b5 captured a broken intermediate edit of initialize_namespace
(unterminated comment, missing _INI and the _REG hook) via git add -A, which
left the tree not compiling. Restore the correct opening (ACPICA init order)
and extract the _REG opregion connect into a public connect_op_regions()
(ACPICA evrgnini.c): \_SB._REG(space, 1) per installed handler space plus
<device>._REG(space, 1) per device holding an OpRegion of that space.
initialize_namespace() delegates to it. Call it from acpid's interpreter
init (AmlSymbols::init) after region handlers are installed — runs once
before the main loop, so a blocking _REG cannot wedge the scheme.
Operator-ratified full retirement — driver-manager superseded
pcid-spawner in every role (boot-time PCI match/claim/spawn, initfs
storage path, hotplug). Removes:
- drivers/pcid-spawner/ crate (source preserved in git history)
- init.d/00_pcid-spawner.service and
init.initfs.d/40_pcid-spawner-initfs.service
- Cargo workspace member + Makefile bin entries
- 40_drivers.target reference to pcid-spawner-initfs
- the /etc/driver-manager.d/disabled fallback gates on driver-manager
services (no fallback exists anymore; driver-manager runs
unconditionally)
endpoint::serve used register_sync_scheme, which registers the scheme to
the daemon's own namespace but never returns the capability fd to init.
For type={scheme} services init blocks in call_ro(FD) waiting for that
fd, so the boot deadlocked right after 'Started Intel LPSS I2C
controller' (CPU halted, init asleep) — the ptyd-class bug.
Replace register_sync_scheme with an explicit capability-fd creation +
notify_init_scheme_fd() that writes the fd to the INIT_NOTIFY pipe
(same mechanism as SchemeDaemon::ready_with_fd / ready_sync_scheme,
which i2cd, ucsid, and ptyd already use). init then registers
/scheme/<name> and the boot proceeds.
Affects intel-lpss-i2cd and dw-acpi-i2cd, both type={scheme} services
using this endpoint.
The general GPE dispatch runs on acpid's single main-loop thread, which
also serves /scheme/acpi. A blocking _Lxx/_Exx AML method (e.g. spinning
on a PCI/EC condition that never becomes true) freezes the scheme and
deadlocks every ACPI-reading daemon and therefore the whole boot. Linux
avoids this with a dedicated kacpid thread. Until Red Bear has one, gate
the general dispatch behind REDBEAR_ACPI_GPE_DISPATCH=1 (default OFF);
EC + PM1 fixed events stay always-on (bounded and proven).
The Handle::Config read handler never returned 0, so fs::read /
read_to_end on /scheme/pci/<addr>/config streamed dwords forever —
any unbounded read of a config file hung. Found by the initfs
driver-manager hang: propose_msix_vectors' unbounded config read never
terminated, stalling the oneshot initfs service and the whole boot.
- cfg_access: Pcie::has_ecam() reports ECAM availability.
- scheme: config_space_size() = 4096 with ECAM, 256 in PCI 3.0
fallback; the read handler returns Ok(0) at the boundary and fstat
advertises the correct size.
40_drivers.target referenced only pcid-spawner-initfs, so the initfs
driver-manager service (staged, gated, with its storage TOML and the
binary already copied into initfs/bin) never entered the boot graph.
The target now lists driver-manager-initfs first and keeps
pcid-spawner-initfs as the gated fallback — the initfs cutover is
complete. Also correct the initfs-storage.toml header comment (the
content is driver-manager format).
- fallback.rs: config reads at offset >= 256 (PCIe extended space) now
return the PCI-standard 0xFFFFFFFF 'absent' value and writes are
dropped, instead of panicking the PCI daemon. This is the exact
behavior of real hardware and Linux's CF8 path on MCFG-less machines,
and it lets MSI-X feature discovery degrade to INTx cleanly. Found by
the first driver-manager QEMU gate (i440fx): pcid panicked at
fallback.rs:65 and the boot hung.
- driver_handler.rs: drop vestigial func param from read_full_device_id.
- driver_interface/mod.rs: use Option::insert's return value directly
(must_use) instead of discarding and re-reading as_ref.
- 00_driver-manager.service: resident daemon args (--hotplug); runs
unless /etc/driver-manager.d/disabled exists.
- 40_driver-manager-initfs.service: gate flipped from opt-in
(initfs-active) to default-on (!/etc/driver-manager.d/disabled).
- 00_pcid-spawner.service + 40_pcid-spawner-initfs.service: gated to
start only when /etc/driver-manager.d/disabled exists — the legacy
spawner remains staged as the operator fallback, never deleted.
init's Service parser used deny_unknown_fields, so the C0
driver-manager service files (which use ConditionPathExists) were
rejected wholesale — driver-manager stayed dormant by parser accident
instead of by design.
- service.rs: new optional ConditionPathExists field + condition_met()
gate. A leading '!' negates: the service starts only when the path
does NOT exist.
- scheduler.rs: skip services whose condition is not met (status_skip,
same pattern as skip_cmd).
- 00_driver-manager.service: fix inverted polarity — the intent is
'run unless /etc/driver-manager.d/disabled exists', i.e.
ConditionPathExists = "!/etc/driver-manager.d/disabled".
- Drop two pre-existing unused imports (Write in service.rs,
status_fail in main.rs).
On cAVS/SOF platforms (e.g. LG Gram 8086:7728), STATESTS reads 0
because the codec sits behind the audio DSP; the legacy HDA codec-wake
mechanism cannot reach it. enumerate() previously hardcoded codec 0 and
would hang reading a non-existent codec via CORB/RIRB. Now, if no
codecs respond after reset_controller(), log the DSP-platform diagnosis
and fail honestly with ENODEV instead of hanging. A SOF/cAVS driver
(Phase 8.2) is required for these platforms.
acpi-rs (vendored fork):
- _REG opregion connect (ACPICA evrgnini.c): run \_SB._REG(space, 1)
per installed handler after \_INI — firmware gates EC access behind
this. Device-level _REG for each device holding an OpRegion of an
installed space. Fills the last big TODO in initialize_namespace.
- RegionSpace: add From<RegionSpace> for u8 (region-space ID for _REG).
acpid:
- LPIT parser BUG FIX: GAS (Generic Address Structure) is 12 bytes
(4-byte header + 8-byte address); the parser previously read
entry_trigger/residency/latency/counter_frequency 4 bytes early and
required length>=48 instead of 56. Fixed offsets, added
entry_trigger_space_id, and mwait_hint()/best_mwait_hint() for the
FFH MWAIT hint. Tests rewritten with correct 56-byte layout.
- Thermal active cooling: /scheme/acpi/thermal/<zone>/active evaluates
_AC0.._AC9 and returns defined trip points (tenths of K).
- ACPI PM timer: pm_timer_read() from FADT pm_timer_block;
/scheme/acpi/pmtimer endpoint (3.579545 MHz).
- HW-reduced ACPI: Fadt::is_hardware_reduced() (FADT bit 20); skip
PM1/GPE setup on such platforms.
- General GPE dispatch: enabled_active_gpes() + \_GPE._Lxx/_Exx method
evaluation (evgpe.c acpi_ev_gpe_detect).
- GpeBlocks::enabled_active_gpes(): scans all GPE block status+enable
register pairs, returns every GPE with both bits set (evgpe detect
semantics — a GPE only fires the SCI when enabled AND active).
- handle_sci general GPE dispatch (acpi_ev_gpe_detect): every
enabled+active GPE that is not the EC GPE gets its \_GPE._L{gpe:02X}
(level, tried first) or \_GPE._E{gpe:02X} (edge) control method
evaluated; status cleared after. This is the ACPICA core GPE model
that drives lid, device wake, and all non-EC GPE events — previously
only the EC GPE and PM1 fixed events were dispatched.
- pm_timer_read(): reads the FADT pm_timer_block free-running counter
(3.579545 MHz, PM_TIMER_FREQUENCY_HZ). Exposed at
/scheme/acpi/pmtimer for precise sleep-path timing.
Add ThermalZone handle kind to the scheme: per-zone ACPI thermal
data at /scheme/acpi/thermal/<zone>/{temperature,passive,critical}.
Each path evaluates the corresponding AML method (_TMP, _PSV, _CRT)
and returns the raw integer value. ThermalFileKind enum dispatches
to the correct method. thermald can now read real thermal zone
temperatures and thresholds instead of relying on hardcoded values.
Ported from Linux drivers/acpi/thermal.c thermal_zone_device_ops.
- WakeRegistry::arm_wake_devices(): evaluates _DSW(1,0,Sx) per wake
device (falls back to _PSW(1)), enables wake GPEs in the GPE block.
Wired into enter_s2idle() — wake devices are now armed before
the kernel MWAIT loop. Ported from Linux acpi_enable_wakeup_devices.
- WakeRegistry::disarm_wake_devices(): evaluates _DSW(0,0,0) per
wake device (falls back to _PSW(0)), clears wake GPE status bits.
Wired into exit_s2idle() — wake devices are disarmed on resume.
Ported from Linux acpi_disable_wakeup_devices.
- SleepStates::discover(): enumerates _S0 through _S5 to find
available sleep states. s3_supported() and s2idle_only() helpers
identify the platform's sleep capability profile.
- AcpiContext.wake_registry: new field storing the populated
WakeRegistry for use by enter_s2idle/exit_s2idle.
An extended-capability walk (pci_types capabilities()) that follows a
chain running to/past the end of config space read at offset 4096,
which tripped the dword-offset assert in bus_addr_offset_in_dwords
("pcie offset larger than 4095") and aborted pcid with an Invalid
opcode fault / UNHANDLED EXCEPTION on boot — after switchroot to /usr,
so it blocked reaching login.
PCIe config space is exactly 4096 bytes (offsets 0..=4095). Fix at two
levels:
- ConfigRegionAccess::read/write (cfg_access/mod.rs): guard the single
access choke point — an out-of-range read returns the PCI "no
response" pattern (0xFFFFFFFF, which also terminates a capability
walk cleanly) and an out-of-range write is a no-op. This catches any
caller (capability walk, scheme reads, driver access).
- scheme.rs config read/write loop: clamp the loop bound with
saturating_add(...).min(4096) so a consumer requesting offset+len
past the boundary reads only the valid part instead of looping to
offset 4096.
Verified: boot no longer panics in pcid (progresses past the previous
crash point through switchroot and the /usr driver set).
Port useful ACPICA components into the existing Rust ACPI stack:
- LPIT (Low Power Idle Table) parser in new acpid/wake.rs.
Parses native C-state LPI entries (entry trigger, residency,
latency, residency counter, counter frequency). Computes total
residency and deepest LPI state. 4 unit tests cover parsing,
empty input, short input, and deepest-entry selection.
Reference: Linux include/acpi/actbl2.h struct acpi_lpit_native.
- _PRW wake device enumeration in acpid/wake.rs.
WakeRegistry::enumerate() evaluates _PRW on known wake-capable
device paths (LID, PWRB, SLPB, XHCI, HDAS, CNVW, I2C0/1, THC0/1).
Extracts GPE number and sleep state from the _PRW package.
Reference: Linux drivers/acpi/scan.c acpi_bus_get_wakeup_device_flags.
- FADT S0-idle detection: Fadt::supports_s0_idle() checks bit 21
(ACPI_FADT_LOW_POWER_S0) to detect platforms that support s2idle.
Reference: Linux include/acpi/actbl.h.
- acpid/main.rs: LPIT parse + wake enumeration + S0-idle detection
wired into init after AcpiContext::init() and before power events.
ACPICA assessment: do NOT port ACPICA as a C library. Port its
useful data structures and algorithms into the existing Rust stack
(acpi-rs vendored fork + acpid daemon). The AML interpreter already
has comprehensive opcode coverage (only DefLoad/DefLoadTable remain
unimplemented, both optional). The GPE/EC/fixed-event infrastructure
is already in acpid. LPIT + _PRW + S0-idle detection fill the
remaining gaps for Phase 9.1 s2idle completion.
The PCI IDE Programming Interface byte (PCI spec §3.1.1) encodes
per-channel mode: bit 0 = primary native, bit 2 = secondary native.
The previous code panicked on native-mode channels and also had a
bug checking bit 0 for both channels (secondary should check bit 2).
Native mode now reads I/O and control bases from PCI BARs (BAR0/1 for
primary, BAR2/3 for secondary) instead of hardcoded legacy ports.
Interrupt line comes from legacy_interrupt_line when available.
Phase 5 — Laptop ACPI events (LG Gram 16Z90TP compatibility plan):
- Vendor acpi-rs crate (rev 90cbe88) into base fork with a real
Opcode::Notify executor; upstream panicked on every Notify opcode,
which is the backbone of ACPI event flow on real laptop firmware.
Handler::handle_notify hook added; acpid + amlserde pointed at the
path dep so every consumer sees the same fork.
- gpe.rs: FADT-driven GPE block register map (status half + enable
half), write-1-to-clear status bits, read-modify-write enable
preserving every other GPE's firmware state. PM1 fixed-event bits
(PWRBTN/SLPBTN/RTC) per ACPI 6.4 §4.8.3.1.
- power_events.rs: init builds the GPE map, discovers the EC via ECDT
(ACPI 6.4 §5.2.16) with a _HID=PNP0C09 probe fallback over conven-
tional paths, enables the EC GPE + PM1 fixed events, discovers lid
and ACPI 4.0 fan devices. handle_sci dispatches PM1 → EC query loop
(bounded at 32) → AML notification drain, following Linux 7.1
evgpe.c / ec.c / button.c.
- notifications.rs: shared AmlNotifications queue (parking_lot::Mutex)
populated by the vendored acpi-rs handle_notify hook, drained by the
SCI handler and redbear-upower.
- ec.rs: sci_evt_set() and query() exposed on Ec for the SCI handler.
- scheme.rs: new handle kinds Lid, LidState, ButtonDir, Button,
Notifications, Fan, FanState, FanSpeed with proper dir/file
separation. Fan _FST on read, _FSL on write (percent clamped 0-100).
- main.rs: subscribes /scheme/irq/{sci_irq} (default 9) on the event
queue, dispatches SCI events through handle_sci. PowerButton incre-
ments edge counter and triggers the shutdown path; SleepButton incre-
ments counter and calls enter_s2idle.
- acpi.rs: AcpiContext gained gpe, ec_device, lid_device, lid_state,
power_button_events, sleep_button_events, fan_devices fields (all
RwLock-guarded). evaluate_acpi_method and enter_s2idle changed from
&mut self to &self (AML mutation goes through RwLock inner state).
- aml_physmem.rs: handle_notify impl pushes onto the shared queue.
Phase 4.4 — HID report descriptor parser (i2c-hidd):
- report_desc.rs: HID 1.11 §6.2.2 descriptor parser + decoder. Global-
state stack (Push/Pop), usage-min/max expansion, sign-extended
fields, contact reconstruction (id, tip, x, y). 3 unit tests.
- input.rs: forward_layout_report dispatches descriptor-driven reports
through forward_decoded: first touching contact → absolute
MouseEvent; two simultaneous contacts → vertical ScrollEvent (two-
finger scroll); buttons → ButtonEvent; keyboard-page reports fall
back to the existing boot-protocol path.
- hid.rs: stream_input_reports parses the descriptor once and uses
forward_layout_report when layouts are non-empty, otherwise keeps the
boot-protocol summary path.
Reference: Linux 7.1 drivers/acpi/{evgpeblk.c,evgpe.c,ec.c,button.c}
and drivers/hid/hid-core.c.
All affected crates compile for x86_64-unknown-redox; i2c-hidd 3/3
unit tests pass on host; acpid host-side tests still can't link
(pre-existing libredox limitation — must run via redoxer).
The pcid_interface crate now reads the two env vars emitted by
driver-manager's SpawnDecision committee:
- REDBEAR_DRIVER_PCI_IRQ_MODE: lets the spawned child know
whether to fall back to MSI / INTx instead of MSI-X
- REDBEAR_DRIVER_DISABLE_ACCEL: lets the spawned child suppress
hardware acceleration (matches PciQuirkFlags::DISABLE_ACCEL)
Both values are stored on PciFunctionHandle and exposed via
accessors (irq_mode_hint / disable_accel_hint) so the driver
daemons can read them at startup. 6 new unit tests cover the
env-var parsing.
Refs: local/docs/DRIVER-MANAGER-MIGRATION-PLAN.md § 5.2 D2.7.
Post-implementation review returned FAIL with two verified-CRITICAL
findings; all legitimate findings fixed in this round:
CRITICAL — engine wrote IC_CON/IC_TAR while enabled (DesignWare
databook forbids; Linux i2c_dw_xfer_init disables first). Engine
restructured: wait-idle -> disable -> program -> enable with
IC_ENABLE_STATUS polling on every transfer.
CRITICAL — Intel LPSS PCI bring-up skipped parent-device init.
intel-lpss-i2cd now claims functions via pcid_interface
(connect_by_path + enable_device), validates the real BAR size, and
performs intel_lpss_init_dev's sequence (reset-deassert + 64-bit
remap address at BAR0+0x200), ported from Linux drivers/mfd/intel-lpss.c.
MAJOR fixes:
- wait_for checks TX_ABRT before success predicates — a NACKed write
no longer reports success via post-abort idle state
- SCL timing corrected to Linux's formulas: HCNT uses sda_fall_ns,
round-to-nearest division (FS 100/200, SS 552/652 for bxt 133 MHz)
- stop=false rejected honestly instead of hanging on the idle wait
- recover(): ABORT-bit cycle + disable + state flush after any failed
transfer
- validate_request: segment/byte/address/10-bit limits before any MMIO
- i2cd + endpoint: exact-first adapter resolution; last-component
matching accepted only when unambiguous
- i2cd registration validates provider_scheme as a single safe
scheme-name component
- I2cTransferResponse gains typed status (I2cTransferStatus,
serde-defaulted, wire-compatible)
- endpoint::serve takes a Result-returning on_ready callback;
setrens failure is fatal (fail-closed namespace reduction)
- unexpected i2cd registration responses are fatal for that controller
Tests: dw-i2c 5 (timing vectors, validation, resolution),
intel-lpss-i2cd 1 (PCI ID table coverage), full workspace cargo check
clean, base cooks for x86_64-unknown-redox.
Refs: local/docs/LG-GRAM-16Z90TP-COMPATIBILITY-PLAN.md review-fix round
Five daemon-local hardening items on top of the AML-mutex fix. acpid is
single-threaded and serves the `acpi` scheme on the same thread that
evaluates AML, so any way it can stall or die stalls or kills every
consumer. These reduce or bound each such way (verified against
local/reference/linux-7.1 ACPICA):
- stall(): refuse >255us and warn >100us instead of an unbounded CPU
busy-spin on the serving thread (ACPICA exsystem.c:129-147). The spec
caps Stall at 100us; a long busy-spin here would delay scheme requests.
- AML mutex release(): a release of a not-currently-held mutex, or by a
non-owning thread, is now logged (ACPICA AE_NOT_ACQUIRED / owner
mismatch, exmutex.c:287,376) rather than silently decrementing depth.
- Static processor-method cache: _PSS/_PSD/_CST/_CPC are fixed after boot
but cpufreqd polls them; cache the first evaluation so later reads never
re-run the AML interpreter under the global lock. Removes acpid's
dominant recurring head-of-line source. Dynamic methods are not cached.
- Panic-free scheme path: every release_global_lock().expect(...) on the
AML-evaluation path is now log-and-continue, and a result.ok()?.unwrap()
that panicked on Ok(None) (absent method) is now `?`. A scheme-daemon
panic kills the `acpi` scheme and wedges every consumer.
- Observability: log AML evaluations >=50ms and mutex-acquire timeouts —
the early-warning signal before a stall becomes a wedge.
Context: the residual under-load boot wedge is NOT in acpid (a mutex-only
baseline wedges identically under load); it is head-of-line blocking in
the single-threaded initnsmgr. See
local/docs/INIT-NAMESPACE-MANAGER-SCALABILITY-PLAN.md and
local/docs/INITNSMGR-CONCURRENCY-DESIGN.md.
Adds the two dormant service files for the driver-manager
post-switchroot + initfs spawner paths. Both files are dormant by
default — they require /etc/driver-manager.d/{disabled,initfs-active}
to be absent before they activate. The cutover (C1-C4) is
operator-ratified; this commit only adds the file presence so
the C0 wiring exists.
Refs: local/docs/DRIVER-MANAGER-MIGRATION-PLAN.md § 5.2 C0.
The I2C transfer chain was stubbed end-to-end:
- i2cd's transfer path returned 'not implemented yet' for every
transfer, and its wire format didn't match the only in-tree consumer
(i2c-hidd sends a bare I2cTransferRequest, i2cd expected
I2cControlRequest::Transfer).
- intel-lpss-i2cd / dw-acpi-i2cd / amd-mp2-i2cd registered an adapter
name and parked forever without initializing the controller or
executing a transfer.
- intel-lpss-i2cd matched only legacy ACPI HIDs, which do not exist on
Meteor Lake / Arrow Lake platforms (LPSS I2C binds by PCI ID there,
per Linux drivers/mfd/intel-lpss-pci.c).
Replace with real implementations:
- New shared crate drivers/i2c/designware (dw-i2c): DesignWare I2C
master engine ported from Linux 7.1 i2c-designware-master.c and
i2c-designware-common.c — IC_CON + SCL timing computed from ic_clk
with Linux's exact hcnt/lcnt formulas (bxt_i2c_info 133 MHz for
LPSS, 100 MHz for ACPI-designated blocks), SDA hold with RX-hold
workaround, polling transfer engine with RESTART/STOP sequencing,
TX_ABRT decode (Nack/arbitration-lost/abort/timeout), 7/10-bit
addressing, bounded timeouts. Also provides the shared
/scheme/<name> transfer endpoint with register-then-ready ordering.
- intel-lpss-i2cd: PCI discovery for ARL-H (0x7750/0x7751,
0x7778-0x777b) and MTL-P (0x7e50/0x7e51, 0x7e78-0x7e7b) with 32/64-bit
BAR0 decode, ACPI alias resolution via FixedMemory32 == BAR0 across
/scheme/acpi/resources, legacy ACPI-HID path kept, i2cd registration
with bounded retry, serves /scheme/i2c-lpss.
- dw-acpi-i2cd: converted from register-and-park to the shared engine,
serves /scheme/dw-acpi-i2c.
- i2cd: real transfer routing — adapter resolution by name/alias
(exact, normalized, last-component) and forwarding to the provider
daemon's /scheme/<provider>/transfer endpoint.
- i2c-interface: I2cAdapterInfo gains provider_scheme + aliases
(serde-default, wire-compatible).
Tests: dw-i2c 3, intel-lpss-i2cd 3; full workspace cargo check clean;
base cooks for x86_64-unknown-redox.
Refs: local/docs/LG-GRAM-16Z90TP-COMPATIBILITY-PLAN.md Phase 4
The AML mutex `acquire` handler had two defects that let a routine
`_ACQ` on ACPI processor P-state objects (`processor/CPUn/pss`, opened
by cpufreqd) deadlock acpid permanently:
1. Timeout units. ACPI `_ACQ` timeouts are milliseconds and 0xFFFF is
the spec's "wait forever" (ACPICA ACPI_WAIT_FOREVER,
actypes.h:459). The code multiplied the value by 1000, treating it
as seconds, so 0xFFFF became ~18 hours.
2. No ownership. ACPI mutexes are recursive: the owning thread may
re-acquire, each Acquire paired with a Release (ACPICA
acpi_ex_acquire_mutex_object, exmutex.c:140). The old code tracked
only a "held" set with no owner, so a nested acquire by the single
AML thread waited for a release only it could perform — a
self-deadlock.
Because acpid is single-threaded and the same thread serves the
`acpi` scheme socket, a stuck acquire stops acpid answering scheme
requests. The init namespace manager then blocks in the openat it was
proxying, and — since every restricted-namespace path resolution goes
through that single manager — the whole system's open path wedges
(observed: mini never reaches a usable brush login).
Fix: track (owner ThreadId, recursion depth) per mutex, treat a
nested acquire by the owner as a depth bump, interpret the timeout as
milliseconds, and bound any wait to MAX_MUTEX_WAIT (5s) so a
misbehaving AML method can never freeze the scheme-serving thread.
usbhidd already accumulated prior interfaces' endpoint counts (global
enumeration index, matching xhcid's PortState::get_endp_desc), but the
counter was never reset between candidate configurations — a HID device
whose usable config is not the first would get endpoint numbers offset
by the first config's endpoints. xhcid indexes within the selected
configuration only, so reset per config.
Implement the Linux 7.1 xhci.c:4650 xhci_set_usb2_hardware_lpm() enable
path, closing the P7-A gap on top of the P2-B substrate:
- usb/bos.rs: BosUsb2ExtDesc bmAttributes accessors (LPM support, BESL
support/validity, baseline/deep BESL fields) + 3 unit tests
- xhci/mod.rs:
- change_max_exit_latency(): MEL update via Evaluate Context (slot
output context copied, SLOT add flag, DWORD1 low 16 bits = MEL) —
Linux xhci.c:4520
- calculate_hird_besl(): HCS_PARAMS3 U2 latency + device BESL
attributes — Linux xhci.c:4594
- enable_usb2_hw_lpm(): BESL vs HIRD parameter selection, MEL
Evaluate Context, PORTHLPMC/PORTPMSC programming via the existing
Port::enable_lpm — Linux xhci.c:4686-4722
- BESL_ENCODING_US table, XHCI_L1_TIMEOUT_US=512, XHCI_DEFAULT_BESL=4
- xhci/scheme.rs (get_desc): attach-time gate chain — hw_lpm_support &&
per-port HLC (USB 2.0 protocol only) && device USB_LPM_SUPPORT in BOS
&& non-hub class && root-hub-direct (get_desc only runs for root-port
devices). LPM enable failure logs a warning and continues — LPM is
opportunistic; the device works in U0 regardless.
Verified: cargo check -Z build-std --target x86_64-unknown-redox -p
xhcid clean (no new warnings). Unit tests compile-verified; execution
requires redoxer like the crate's existing test suite. Runtime L1
entry validation requires LPM-capable hardware (QEMU's xHCI does not
advertise HLC) — recorded as hardware-validation debt in the USB plan.
Continuation of 92924224 — the same conditional-ack bug class found in
six more drivers: a foreign interrupt on a shared INTx line skipped the
write-back ack, leaving the kernel-masked IRQ line dead forever.
- sb16d, ac97d: ack before the not-ours continue
- rtl8139d, rtl8168d, ixgbed: ack unconditionally, tick only when ours
(the stale 'TODO: spurious interrupts' comments removed — the
spurious-interrupt confusion was this bug)
- ihdgd: ack unconditionally, handle_events/tick only when ours
Verified: cargo check -Z build-std --target x86_64-unknown-redox for
sb16d, ac97d, rtl8139d, rtl8168d, ixgbed, ihdgd — clean, no new
warnings. nvmed audited: not affected (per-queue MSI pattern, no
conditional ack).
Same bug class as the ahcid fix (ad40fffd): the kernel masks the IRQ
line when it delivers an interrupt and only re-arms it on the userspace
write-back (irq scheme write -> acknowledge() -> pic/ioapic_unmask).
When a driver acks only if the interrupt was its own, one foreign
interrupt on a shared INTx line leaves the line masked forever and all
later interrupts for the device are lost.
- e1000d: ack unconditionally; ICR is read-to-clear, so the ownership
check doubles as the device-level status clear
- ihdad: ack before the not-ours continue
- vboxd: ack unconditionally; device-side ack and event handling stay
conditional on host_events
- xhcid: ack unconditionally in the IRQ reactor; for INTx the ownership
check already clears IMAN.IP (RW1C) and device interrupts are masked
before re-arming, so no storm. MSI/MSI-X vectors are never shared, so
behavior there is unchanged (every delivery is ours by construction)
Verified: cargo check -Z build-std --target x86_64-unknown-redox for
e1000d, ihdad, vboxd, xhcid — clean, no new warnings.
fbcond blocked indefinitely in open_display_v2() while handing the console
over to the real graphics driver: boot stopped at "fbcond: Performing
handoff" and never reached the "Opened new display" that follows a
successful open.
fbcond is single-threaded and owns the console, so while it waited there it
stopped draining console writers. getty, login and the login shell all
blocked on their writes, which made the failure look like a slow or hung
shell -- the stall point just tracked whichever process next wrote to the
console. If the graphics driver was itself waiting on the console, the two
deadlocked outright and the console never came back.
The wait comes from the scheme-open handshake: inputd signals the handoff as
soon as the driver registers its path, but the driver may not be serving its
scheme yet, and O_NONBLOCK does not bound the open (it governs later reads).
Split the two halves in inputd's ConsumerHandle: display_path_v2() only does
an fpath on our own handle and returns promptly, while open_display_path_v2()
carries the blocking open. fbcond now resolves the path inline and hands the
open to a worker thread, then picks the result up from the event loop via
poll_pending_handoff(). Console output produced meanwhile is buffered in
pending_writes (already the behaviour while the display is unmapped) and
flushed once the new display is mapped.
The kernel masks an IRQ line when it delivers the interrupt to userspace
(trigger() -> pic_mask()/ioapic_mask()) and only re-enables it when the
driver writes the count back (kwrite -> acknowledge() -> pic_unmask()/
ioapic_unmask()). That write-back is therefore mandatory, not optional.
ahcid only performed it inside the `is > 0` branch. IRQ lines are shared
(on q35 the AHCI controller sits on IRQ 10 with other devices), so an
interrupt raised by a different device reaches the handler with the HBA
interrupt status register reading 0. In that case ahcid returned without
writing back, leaving the line masked permanently: every subsequent AHCI
completion was lost and all disk I/O blocked forever.
Move the write-back out of the branch so the line is re-armed whether or
not the interrupt turned out to be ours, and keep scheme.tick() gated on
`is > 0` since there is no completion to service otherwise. Device-level
status is still cleared before unmasking, so this cannot cause a storm.
The handoff is one-shot: inputd signals it the moment the real display
driver registers its path, but the driver's scheme may not serve the v2
open / capability query for a few more milliseconds. Without a retry, a
transient not-ready driver leaves the framebuffer permanently blank —
the login prompt is drawn to the framebuffer VT, so the console appears
dead even though boot continues on the serial mirror (observed as the
2026-07-20 '-vga std' boot freeze at 'Performing handoff').
Retry the reopen for up to 250 x 10ms; the driver becomes ready well
within this bound in practice. On success after retries, log the retry
count at info level. If the driver is still not ready after the bound,
emit a single explicit warning instead of per-attempt warn spam (the
per-attempt message in display.rs is demoted to debug). Serial mirror
remains unaffected in the failure case.
'Running IRQ reactor with IRQ file and event queue' and 'in polling
mode' were debug! since the file was created, so test-xhci-irq-qemu.sh
(which greps for the interrupt-driven line) could never see them at the
default info log level — the IRQ-driven path had zero runtime evidence.
They are one-time startup lines; promote to info so the interrupt
delivery mode is observable and the proof can detect it.
V2GraphicsHandle::from_file() unwrapped/asserted the DumbBuffer
capability, but the display fd is O_NONBLOCK and the graphics driver
often has not finished coming up at handoff time — so from_file failed
with EAGAIN and the assert panicked fbcond. Since fbcond owns the
console and serial mirror, its death froze the whole boot right after
'Performing handoff' with no login prompt.
Return an error from graphics-ipc when the driver does not yet report
DumbBuffer, and have fbcond log-and-return so the handoff is retried
when the driver publishes its surface, instead of panicking.
(Change found as uncommitted work in the fork; committing to preserve
it and unblock the clean-fork build gate.)
The driver requires MSI-X (virtio-core probe errors out without it) and
binds both virtqueues to MSIX_PRIMARY_VECTOR, but only noted the
transport in a debug log — leaving zero runtime evidence of the MSI-X
path at the default level, which is why test-msix-qemu.sh found no live
MSI-X evidence. Log the delivery method at info where it is set up.
The diagnostic milestones used to root-cause the intermittent boot
'freeze' (attach_device milestones, usbhubd HUBFLOW decision points,
reactor/enumerator startup) moved from info to debug! so production
logs stay clean. One-line-per-boot startup confirmations (scheme
registered, daemon ready, reactor started, enumerator started, reactor
dispatch mode, enumerator running) remain at info as genuinely useful
low-volume startup evidence.
Traces at scheme registration, daemon.ready, reactor/enumerator start,
reactor dispatch + IRQ subscribe, and enumerator run entry, to pinpoint
where xhcid stops in boots that lose the intermittent IRQ-reactor
startup race. Diagnostic; level to be revisited after root cause.
SetPortFeature(PORT_INDICATOR) was issued unconditionally for every
connected+enabled port. QEMU's usb-hub does not advertise indicator
support and NAKs the request indefinitely; with no control-transfer
timeout the daemon hung before the post-enable debounce, so devices
behind the hub never attached. Gate on wHubCharacteristics bit 7
(HUB_CHAR_PORTIND, USB 2.0 Table 11-13), matching Linux hub_configure's
has_indicators check.
Log SetPortFeature(PORT_RESET) result, wait_for_reset's first fetch,
and its completion/timeout outcomes at info level to pinpoint where
hub port-reset polling stalls in QEMU.
The producer's write buffer arrives byte-aligned from an arbitrary
scheme write; constructing a &[Event] slice directly over it is
undefined behaviour (misaligned loads, hardware faults on strict-
alignment targets). Copy the events into a properly aligned Vec<Event>
via copy_nonoverlapping and drop the trailing partial event.
(Change found as uncommitted work in the fork; committing to preserve
it and unblock the clean-fork build gate.)
Replace two panics (initial scan_requests expect, event-queue read
expect) and a socket-event break with error logging + continuation. A
transient error reading the event queue or scanning requests must not
kill ptyd and take the whole pty subsystem down with it.
(Change found as uncommitted work in the fork; committing to preserve
it and unblock the clean-fork build gate.)
Post-debounce state, pre-attach state, and attach() result logged at
info level to pinpoint where hub-child enumeration stalls in QEMU.
Diagnostic; level to be revisited.
Temporary info-level ATTACH milestones in attach_device (begin, slot,
addressed, desc8, desc-full, drivers spawned) to trace hub-child
enumeration in QEMU — the kbd behind a hub reaches port-enable but
produces no visible outcome at the default log level. Level to be
revisited after the hub-child attach path is diagnosed.
The debounce's inner clear of C_PORT_CONNECTION could hang or be
ignored by the hub, and our control transfers have no timeout — so a
literal port of Linux's clear-inside-the-loop design deadlocked hub
enumeration: the debounce never converged and the reset/attach path was
never reached (observed on QEMU as usbhubd logging the port's first
status with connection_changed=true and then going silent forever).
Judge the 100ms stable window on the connection STATE alone (the same
stability property hub_port_debounce_be_connected protects): a stuck or
hung change bit can no longer deadlock enumeration — it only
re-triggers a poll, and is cleared once, best-effort, after a
successful attach (matching Linux port_event's C_PORT_CONNECTION
clear). New regression test debounce_stuck_change_bit_still_converges
locks the deadlock scenario; 15/15 tests pass.
UdsStreamScheme::getsockopt held an outer socket_rc.borrow() across the
whole option match. The SO_PEERCRED branch calls get_connected_peer(id),
which itself does borrow_mut() on the same socket — a RefCell
double-borrow that panicked ipcd and took the UDS scheme down (observed
in QEMU boot logs as ipcd crash at uds/stream.rs plus tokio
UnixStream::pair / 'failed to create UnixStream' failures from clients
calling getsockopt(SO_PEERCRED)).
Borrow only inside the branches that read socket fields (SNDBUF/RCVBUF);
the SO_PEERCRED branch now runs without an outer borrow held.
(Change found as uncommitted work in the fork; committing to unblock the
clean-fork build gate and to preserve the fix.)
Root cause of hub-child enumeration stalling: after a synchronous
action (power-on, reset) the port's state changes WITHOUT a new
interrupt ever being generated, and the loop's next step was a blocking
EP1 transfer_read with no timeout — the daemon never woke to observe
the state it had just caused, so devices behind a hub sat
enabled-but-never-attached forever.
Move the blocking transfer_read onto a worker thread that forwards each
interrupt bitmap as a u64 mask over an mpsc channel. The main loop
waits with recv_timeout(POLL_FALLBACK_MS): a real bitmap processes only
the changed ports (interrupt fast path), while timeout/disconnect/error
falls back to an all-ports poll (progress guarantee). Matches the Linux
model where hub_irq is the accelerator but port status reads are always
authoritative.
Two latent bugs exposed by test-usb-hub-qemu.sh against a real hub
topology (QEMU usb-hub with usb-kbd behind it):
1. Status-change bitmap was indexed off by one: the loop checked
bit (port - 1), but USB 2.0 spec 11.12.4 defines bit 0 = hub status
change and bit N = port N status change (Linux hub_irq uses bit i
for port i). Every change was processed on the wrong port — a device
on port N was never enumerated (its bit was read as port N+1).
2. The event loop's first action was a blocking EP1 interrupt read;
when the hub delivers no immediate status-change interrupt the
daemon hung before ever scanning a port. Linux hub_activate()
performs a full port scan before arming the status-change endpoint;
the first iteration now forces an all-ports mask with the same
semantics. Also widened the fallback all-ports mask to bits 1..=ports
(bit 0 = hub, skipped).
open_handle_port required a PortState for every port<N> directory open,
but hub child ports have no PortState until the hub daemon triggers
attach_device via port<N>/attach — an endpoint that itself is
state-free (open_handle_attach_device). This made XhciClientHandle::new
fail with ENOENT for unenumerated hub children, deadlocking the attach
flow: usbhubd could never start enumeration for a device behind a
non-root hub (panic at startup, caught by test-usb-hub-qemu.sh).
Open the directory with the static listing when no PortState exists
yet; state-dependent subpaths (descriptors, state, configure) still
gate on the PortState being present.
Sync the base fork with 13 upstream commits (xhci event-processing
dedup + IRQ race fix, randd permission simplification, nvmed TimeSpec
fix, /dev/ptmx, fpath legacy-path cleanup, dynamically-linked init
fix, and more). Brings process_one_event into the tree, satisfying the
verify-fork-functions gate for base.
Conflicts resolved (3 of 8 overlapping files; 5 auto-merged):
- drivers/usb/xhcid/src/xhci/irq_reactor.rs: took upstream's
process_one_event/EventProcessResult refactor (b2ed85ea) including
the a01d3ce6 race fix (process events between NoEvent and
unmasking), and re-applied the Red Bear SPURIOUS_REBOOT quirk on the
NoEvent warning (downgrade to debug when quirked).
- randd/src/main.rs: took upstream's permission-handling
simplification (e26db606); re-applied the RB fcntl improvement
(F_GETFL/F_GETFD/F_SETFL/F_SETFD handling, Linux random_fops xref)
and the is_cpu_feature_detected early-return cleanup. Dropped
test_scheme_perms (deleted by upstream's simplification).
- Makefile: kept upstream's new /dev symlink block (dev/null, ptmx,
random, urandom, zero, tty, stdin/stdout/stderr).
Verified: cargo check clean; 57/57 tests pass (xhcid 35, usbhubd 14,
xhci trb 8); verify-fork-functions.sh --no-fetch base reports all
upstream functions present.
Port the Linux 7.1 hub.c port state machine into usbhubd, replacing the
minimal connect/reset handling:
New module port_ops.rs (pure logic, side effects injected, 14 unit
tests):
- debounce_until_connected: hub_port_debounce_be_connected() port
(hub.c:4696-4737) — 25ms polls, connection stable for 100ms, 2s
budget, connection-change bit cleared in-loop.
- wait_for_reset: hub_port_wait_reset() port (hub.c:2953-3047) — 10ms
polls until RESET clears with CONNECTION set, escalate to 200ms after
two short waits, 800ms budget; then 50ms TRSTRCY recovery (hub.c:3159)
and C_PORT_RESET clear. Replaces the previous bare sleep(10ms).
- wait_for_u0: USB 3.0 polling→U0 wait after port power-on — 36ms steps,
400ms ceiling (tPollingLFPSTimeout = 360ms; Linux hub.c:1226 debounce
path).
- accumulate_hub_delay_ns: wHubDelay chain rule (hub.c:1507-1519:
wHubDelay + parent->hub_delay + 40ns, cap 65535ns).
main.rs wiring:
- Port status normalized to PortStatusSnapshot (decouples the state
machine from the V2/V3 wire formats; V3 link state extracted from
bits 8:5).
- Debounce on connection-change before attach; C_PORT_ENABLE cleared
once handled (Linux port_event semantics).
- Reset path uses wait_for_reset instead of sleep(10ms).
- USB 3 power-on path waits for U0 before proceeding.
- wHubDelay: ancestor-chain walk fetching USB 3 ancestor hub
descriptors, accumulated per Linux; delivered to newly attached
SuperSpeed children via SET_ISOCH_DELAY (USB 3.0 9.4.11; Linux
message.c:1142 — hubs and non-SS skipped, children inherit the hub's
accumulated delay verbatim per hub.c:5128-5129).
- attach/detach failure logs now identify the port.
hub.rs (xhcid usb module):
- HubDescriptorV3 extended with device_removable: u16 — the SS hub
descriptor is 12 bytes (spec Table 10-15); the old struct under-read
by 2 bytes. Stale TODO corrected: SS descriptors have no
PortPwrCtrlMask (that is USB 2.0-only, still unparsed).
Verified: cargo check clean (0 usbhubd warnings), 14/14 usbhubd tests,
xhcid unaffected (43/43 tests).
Three bugs in the xHCI endpoint-restart path used by all error recovery
(stall hard reset, transaction-error soft retry, resource retry,
split/babble hard reset):
1. Latent deadlock: restart_endpoint held the port_states write guard
across set_tr_deque_ptr(), which internally re-acquires a read guard
on the same key (std RwLock read-while-write on one thread).
Unobserved because error injection is not yet exercised at runtime
(P8-C). Fixed by scoping phase-1 ring priming so the guard drops
before the async command.
2. Doorbell ordering violated xHCI spec 4.6.8/4.6.10: after Reset
Endpoint the TR Dequeue Pointer is undefined, so Set TR Dequeue
Pointer must complete BEFORE the doorbell transitions the endpoint
Stopped->Running. The old order (doorbell first) ran the endpoint
with an undefined dequeue pointer — undefined xHC behavior on real
hardware. Linux rings the doorbell from the Set TR Dequeue command
completion path (xhci_handle_cmd_set_deq, ring.c:1416-1554); xhcid
now issues Set TR Dequeue, awaits completion, then rings.
3. Priming NoOp never executed: ring.register() was captured after
ring.next() advanced the enqueue index, so the dequeue pointed past
the NoOp (dead TRB). Now captured before next(), priming the
hardware dequeue AT the NoOp so the xHC executes it on restart —
same semantics as Linux xhci_move_dequeue_past_td pointing at the
first valid TRB.
Verified: cargo check clean (138 warnings, unchanged), 43/43 tests pass.
Gate xHCI 1.1+ features on their capability bits, cross-referenced with
Linux 7.1 xhci driver behavior:
LEC (HCC2_LEC, scheme.rs):
- lec now uses Linux xhci-mem.c:1350 exact condition:
hci_version > 0x100 && hcc_params2 & HCC2_LEC (HCCPARAMS2 register
space is reserved on 1.0 controllers).
- Max ESIT Payload Hi zeroed when LEC=0 (spec Table 6-8 RsvdZ).
U3C (HCC2_U3C, mod.rs suspend_port):
- Refuse SuperSpeed U3 entry with ENOSYS when hci_ver >= 0x110 and
HCC2_U3C=0 (spec 4.15.1). USB2 suspend unaffected. Linux 7.1 defines
but never gates this bit; xhcid follows the spec.
CIC (HCC2_CIC): CIE gate pre-existing (set_cie from cic()); added the
hci_ver > 0x100 version guard. HCC2 capability log block similarly
guarded.
HW LPM (extended.rs, mod.rs, port.rs):
- New SupportedProtoCap::{l1_capable,hw_lpm_capable,besl_lpm_capable}
reading protocol-defined bits (Linux xhci-ext-caps.h:62-66 L1C/HLC/BLC).
- Xhci::hw_lpm_support computed per Linux xhci-mem.c:2137:
hci_ver >= 0x100 && !HW_LPM_DISABLE && any USB2 protocol cap has HLC.
- attach_device(): defensive LPM clear on USB 2.0 protocol ports
(rev_major() != 3) when hw_lpm_support is false — Linux xhci.c:4725
disable path; USB3 excluded because PORTPMSC L1DS aliases U2 timeout.
- Port::enable_lpm/disable_lpm register targets fixed: HLE/HIRD/RWE/
L1DS belong in PORTPMSC (offset 0x04), not PORTHLPMC (0x0C, bit 16
RsvdZ) — spec Tables 5-21/5-23, Linux xhci-port.h:135-158. Helpers
rewritten to Linux xhci.c:4686-4737 two-register sequence.
- Per-device L1 enablement (BESL, MEL Evaluate Context) defers to P3.
Bug fix: removed bogus CapabilityRegs::hlc() + HCC_PARAMS1_HLC_BIT —
they read xECP pointer bits 16-31 of HCCPARAMS1 (spec Table 5-13), not
HLC. HLC lives in the Supported Protocol capability port_info DWORD.
Verification: cargo check clean (138 warnings, -2 vs baseline: the new
disable_lpm call site also revived PORT_HLE/PORT_HIRD_MASK), 43/43
tests pass.
Replace xhcid's self-contained 294-line xhci/quirks.rs (7-flag bitflags
type + ~30-entry quirk table) with a thin re-export shim that delegates
to redox-driver-sys::quirks, which now carries all 51 Linux 7.1 quirk
flags and the full ~85-entry canonical controller table.
Changes:
- Cargo.toml: add redox-driver-sys path dependency
- xhci/quirks.rs: replace table with pub use XhciControllerQuirkFlags
as XhciQuirks + delegating lookup_quirks(vendor, device, revision,
hci_version)
- main.rs: read real HCIVERSION from MMIO offset 0x04 via
cap.hci_ver.read() instead of hardcoded 0x100 — matches Linux 7.1
xhci_gen_setup() at xhci.c:5455. Two table entries depend on the
value: AMD_0x96_HOST (xhci-pci.c:308) and >= 0x120 spec rule
(xhci-pci.c:511).
- main.rs: resolve quirks BEFORE get_int_method() so BROKEN_MSI skips
MSI/MSI-X probing entirely (matching Linux xhci_try_enable_msi at
xhci-pci.c:143-209). Previously the quirk only overrode the method
label while irq_file still held the MSI handle — a mismatch causing
silent interrupt-delivery failures on BROKEN_MSI controllers.
- get_int_method (both cfg variants): accept quirks parameter
maybe_recover_transfer_error previously handled only the first-tier
codes (UsbTransaction, Resource, Stall, BabbleDetected, DataBuffer,
Trb, SplitTransaction) and silently returned Ok(false) for every
other completion code via a catch-all arm.
Cross-referenced Linux 7.1 drivers/usb/host/xhci-ring.c
handle_tx_event() (line 2608+) and handle_transferless_tx_event()
(line 2561+) to add explicit recovery for the remaining ~29 codes:
- Stopped/StoppedLengthInvalid/StoppedShortPacket: restart endpoint
+ retry (up to MAX_SOFT_RETRY), then hard-reset
- InvalidStreamType/InvalidStreamId: soft reset + retry, then
hard-reset
- IncompatibleDevice: disable slot (device must re-enumerate)
- MissedService/NoPingResponse: log informational, surface to caller
- ContextState/Parameter: hard-reset to resync driver/xHC state
- Bandwidth/BandwidthOverrun/SecondaryBandwidth: log, no transfer
recovery (config must change)
- IsochBuffer: hard-reset endpoint
- MaxExitLatencyTooLarge: log, surface
- EventLost/Undefined: hard-reset (event ring may be corrupted)
- SlotNotEnabled/EndpointNotEnabled/NoSlotsAvailable: log driver
state mismatch
- CommandRingStopped/CommandAborted: log xHC state confusion
- Reserved/vendor: default arm logs explicitly
Added completion_code_to_errno() mapping transfer completion codes
to POSIX errnos matching Linux 7.1 semantics:
Stall -> EPIPE
BabbleDetected -> EOVERFLOW
UsbTransaction/SplitTransaction/IncompatibleDevice -> EPROTO
Trb -> EILSEQ
DataBuffer -> ENOSR
SlotNotEnabled/EndpointNotEnabled/NoSlotsAvailable -> ENODEV
default -> EIO
Rewrote handle_transfer_event_trb() to use the new errno mapping
instead of always returning EIO.
Added 14 unit tests covering all errno mappings and transfer
event handling paths. Full suite (41 tests) passes.
The keyboard input path pushed the raw character bytes, so the Enter key
(a bare CR on the keymap) never produced an LF. Line-oriented readers on
the console (e.g. a shell's read_line) then never saw a completed line and
appeared to hang. Convert CR->LF here, matching the serial input path
(push_input_bytes).
The restored switch_root chdir set init's CWD to /scheme/initfs on the
live image. login later restricts its namespace to DEFAULT_SCHEMES (no
'initfs' scheme) via mkns/setns; the inherited /scheme/initfs CWD fd then
becomes unresolvable. Because relibc resolves paths through the CWD fd
(AT_REDOX_CWD_FD), every subsequent file op in login hangs -- notably
Command::spawn() loading the login shell binary never returns, so the
shell never starts. Leaving the CWD inherited (as before the chdir was
added) keeps spawn working across the login namespace switch; getcwd() in
/usr binaries works without the chdir. Reverts the CWD half of 521c6ffe;
the init-diag cleanup from that commit is retained.
The Warn console level correlated with a deterministic login-auth
regression in the mini image (login reads the username but never reaches
MOTD/spawn_shell; 0/3 boots authenticated vs 1/1 with Info). Restore
Info-level console output while the interaction is re-verified; console
spam will be reduced later via a safer mechanism (routing daemon output,
not lowering the shared log level).
Daemons log via OutputBuilder::stderr() at output_level, which shares the
interactive console/login VT. At Info they spam routine chatter (cpufreqd,
thermald, i2c-hidd, ...) over the login prompt as boot continues in
parallel with getty. Drop the console filter to Warn; full Info logs are
still written to per-daemon log files (file_level), and a bootloader env
var can raise it for debugging.
Commit 99e08650 temporarily removed the post-switch_root chdir (which
points init's working directory at a valid dir in the new root) to test a
spawn hang, and added init-diag SPAWNING/SPAWNED/WAITING eprintlns. The
chdir was never restored: init and every daemon/getty/login/shell it
spawns inherit an invalid CWD (AT_REDOX_CWD_FD), so getcwd() fails in
/usr binaries and interactive shells (zsh/brush) hang instead of reading
input. Restore the chdir and drop the diagnostic eprintlns (which also
spammed the login console).
fbcond now mirrors all framebuffer-console output to the kernel debug (serial)
scheme AND feeds serial input back into the active VT's input queue. Previously,
once fbcond took over the console after display handoff the serial line went
silent (headless operators saw the boot stop at 'Performing handoff' and never
saw the getty login prompt, which draws only to the framebuffer VT). Now the
same console — boot log, login prompt, and shell — is fully usable over serial,
reusing the working framebuffer getty for both surfaces.
- smolnetd: an empty ip_router (DHCP-managed or deliberately network-less like
the bare target) is a valid 'no default gateway' state, not a malformed config
-> no warning.
- router: a limited/directed IPv4 broadcast (DHCP DISCOVER to 255.255.255.255
before any lease/route exists) legitimately has no routing-table entry; don't
warn 'No route found' for broadcast destinations.
- e1000d: add the 82574L (0x10d3, QEMU '-device e1000e') to the E1000 match
list; it keeps the legacy descriptor/register interface this driver uses.
I219 is intentionally excluded (integrated MDIO PHY, different init).
- init: add condition_path_exists so optional-daemon units (dbus, seatd,
thermald, evdevd) are silently skipped when their binary is absent in a
minimal image, instead of emitting [FAILED] 'No such file or directory' on
the bare target. Boot-critical units omit the field and still hard-fail.
- ahcid: an empty ATAPI/optical drive (QEMU's default DVD-ROM, most bare-metal
optical bays) failed READ CAPACITY and logged 4 ERROR lines every boot;
register it with a zero block count as a normal no-media state and drop the
HBA register dump to debug level.
- netstack: a machine with no NIC (bare, or an unsupported NIC) logged an ERROR
and exited non-zero; treat 'no network adapter' as a normal idle state
(info + clean exit).
- dhcpd: cut the socket timeout 30s -> 8s so the network stage fails fast when
no DHCP server answers instead of stalling boot.
For fbbootlog, fbcon and the disk drivers there is no load bearing use
of the fpath output. And for chan relibc already handles both the legacy
and new format.
There isn't really a need to support chown/chmod of the rand scheme. It
adds a fair bit of complexity without adding any security over
unconditionally allowing reads by anyone and writes by root. If we want
to restore support for chown/chmod, we should probably do so in a
generic way that covers all device schemes.
Re-adds the archived-but-unapplied scrollback support: a 1000-line ring
buffer in TextScreen capturing all output (incl. pre-handoff boot log), a
Handle::Scrollback variant opened via /scheme/fbcon/<vt>/scrollback, and a
read path returning the retained buffer. Adapted to the current single-step
openat scheme protocol.
ptyd was migrated to the SchemeDaemon/ready_with_fd path: it registers the
"pty" scheme and signals readiness by sending its scheme cap fd back to
init, which init receives via call_ro(FD) in its scheme-service startup.
The service was still declared type="notify", so init waited for a plain
readiness byte ptyd never sends and blocked forever at ptyd — before the
console/login stack could start (post-switchroot boot hang). Declare the
correct type={scheme="pty"} so init uses the matching fd-receive path.
The ACPI _LNK object enumeration logged 50+ INFO lines per boot on QEMU
(one per _UID/_CRS/_STA/_DIS/_SRS/_HID method), flooding the console and
slowing serial boot. This is PCI interrupt-routing detail, not needed at
INFO on every boot; move it to debug.
ptyd was the last initfs daemon still using the old Daemon +
register_sync_scheme + daemon.ready() pattern, where ready() writes a
plain readiness byte. init's scheme-service startup does call_ro(FD)
expecting to receive the scheme cap fd (the SchemeDaemon/ready_with_fd
protocol every other daemon uses), so init blocked forever waiting for
an fd that never arrived, hanging the boot after ptyd.
Both branches independently fixed the FILETABLE desync bug. This merge creates a single canonical history that preserves the diagnostic commits from 0a358aa0 and the eexist-focused fix from 104da7de.
After this merge, the per-fork submodule/<name> branch (this is the AGENTS.md-mandated canonical ref) is a child of both, so origin can fast-forward to it.
(NO AI attribution in commit message body, per project policy)
Add diagnostics to pin down where the INIT_NOTIFY fd handoff hangs:
- init/src/service.rs: log read_pipe fd and call_ro results
- daemon/src/lib.rs: log cap_fd, write_pipe, and call_wo result
- logd/src/main.rs: explicit ready_sync_scheme result and setrens fallback
These are temporary diagnostics for the boot-hang investigation.
create_pipe() used raw syscall::openat/syscall::dup which allocate kernel
fds WITHOUT registering in relibc FILETABLE. Later FILETABLE-managed
syscalls (Command::spawn -> relibc pipe2) reserve the same fd numbers,
causing EEXIST in kernel insert_file.
Replace with libc::pipe2 which goes through relibc FILETABLE-aware path.
create_pipe() used raw syscall::openat() (SYS_OPENAT) and syscall::dup()
which bypass relibc's FILETABLE-managed fd allocation (SYS_OPENAT_INTO).
This created phantom fds known to the kernel but not to relibc's userspace
FILETABLE. When Command::spawn() later called relibc's pipe2() for
fork+exec error reporting, the FILETABLE allocated a position it thought
was free, but the kernel rejected it with EEXIST (errno 17).
This killed EVERY daemon spawn during boot: logd, randd, zerod, rtcd,
nulld, acpid, pcid, inputd, lived, redoxfs, pcid-spawner, fbcond, vesad,
fbbootlogd, hwd, ps2d — all failed with 'File exists (os error 17)'.
Fix: use libc::pipe2() which goes through relibc's FILETABLE-managed
path (FdGuard::open → SYS_OPENAT_INTO), keeping tables in sync.
Commit bb20fe9c in relibc fork removed FEXEC_STEP diagnostic from
redox_rt::proc. The bootstrap binary in base referenced it in
exec.rs:257, causing build failure:
error[E0425]: cannot find value in module
Removed the diagnostic step variable and simplified the panic message.
Build now compiles cleanly.
Use direct syscall::openat with ns_fd to get pipe READ end, then
syscall::dup with 'write' to get WRITE end. This avoids the
redox_rt::sys::open bug where step 2 (openat_into_posix on the
pipe read end) consumes has_run_dup, leaving the subsequent dup()
unable to get the write end.
The init process's ns_fd may be stale after exec, causing EBADF when
pipe2() calls redox_rt::sys::open (which needs current_namespace_fd()).
Use libredox::Fd::open + syscall::dup instead, bypassing the FILETABLE
and ns_fd dependency entirely.
Socket and RawEventQueue create fds via libredox raw syscalls that
bypass the redox-rt userspace FILETABLE. FdGuard::dup then reserves
these positions, causing SYS_DUP_INTO to destroy the existing fds.
The suspend_to_ram, read_battery_status, and read_battery_info methods
were incorrectly placed inside 'impl Drop for PhysmapGuard'. They
reference fields (aml_symbols, fadt) that only exist on AcpiContext.
Move them to impl AcpiContext and fix field access (self.fadt.as_ref()
instead of self.fadt()).
- try_mem now returns Result (matching caller expectations)
- try_map_bar: non-panicking BAR mapping on PciFunctionHandle
- try_pci_allocate_interrupt_vector: non-panicking IRQ allocation
- virtio-core: reverted .ok_or() back to .map_err() for Result type
Added try_mem() returning Option<(usize, usize)> for non-panicking
memory BAR access. Fixed virtio-core/probe.rs to use .ok_or() instead
of .map_err() to match the Option return type.
The [patch] section pointed to ../../relibc/source/redox-ioctl which
doesn't exist. Fixed to ../relibc/redox-ioctl matching the main
dependency path at line 114.
- on_sendfd: subscribe/dup errors return error Response instead of panic
- fork/new_thread: subscribe errors propagate via ? operator
- signal delivery (4 sites): status fd write errors are best-effort (let _ =)
The procmgr is the first userspace process manager — a panic here kills
the entire system. These changes make it resilient to transient fd errors.
Per local/docs/PATCH-PRESERVATION-AUDIT-2026-07-12.md the base
fork was carrying only 38 of 100 patches in local/patches/base/.
The other 62 patches' content was silently missing from the fork
working tree, even though their .patch files were preserved.
This commit re-applies 41 patches that genuinely still apply
cleanly + 17 hunks that partially applied. Recovery covers:
- D-Bus initfs service wiring (P4-initfs-dbus-services)
- USB service wiring (P4-initfs-usb-drm-services)
- netcfg/dhcp/dhcpv6 driver fixes
- acpid shutdown/PM/quirk fixes
- inputd/ps2d hard-fail logging
- pcid driver interface refinements (server cmd channel)
- virtio-core for VirtualBox support
- ixgbed/rtl8139/rtl8168 net drivers
- ahcid NCQ + per-function interrupt coalescing
- logd persistent logging
- bootstrap procmgr race-condition fixes
- cargo version pin to +rb0.3.0 (synchronized release branch)
58 files changed, +1444/-318 lines.
Untracked mnt/ tree and *.orig / *.rej files cleaned up after
patch application (leftover from absolute-path patch headers).
- bytemuck 1.25.0 -> 1.25.1 (patch bump)
- bytemuck_derive 1.10.2 -> 1.11.0 (minor bump)
- Other minor patches refreshed
Part of Phase 0 fix for G1 (Cargo.lock drift).
The suffix-only drift +rb0.3.0 -> +rb0.3.1 was already
applied on master via cargo generate-lockfile. The
other entries are non-Cat-2 transitive bumps that
catches with the lockfile refresh.
No functional change to Cat 2 fork entries (those
already match Cargo.toml at +rb0.3.1).
Our Red Bear patches had reverted the userspace fd allocation refactor
(commit 372b200f) in exec.rs. This caused FD tracking mismatches
between the userspace FILETABLE and the kernel fd table, resulting in
EEXIST errors and fork failures.
Restored the upstream version which correctly uses redox_rt::sys::*
functions (openat, dup, sys_call_ro) that go through the FILETABLE,
and openat_into_upper for pre-init FD allocation. Also includes the
filetable_binary_fd setup and same_process flag in ExtraInfo.
The bootstrap's start.rs used libredox::call::openat which resolved to
the bootstrap's own redox_openat_v1 in initfs.rs, calling syscall::openat
(SYS_OPENAT). This let the kernel allocate POSIX FDs 0,1,2 for
stdin/stdout/stderr, but the userspace FILETABLE was never updated.
Later, exec.rs called auth.dup(b'cur-context') via redox_rt::sys::dup,
which asked the empty FILETABLE for a free slot (returning 0), then
passed it to SYS_DUP_INTO. The kernel rejected it with EEXIST because
posix_fdtbl[0] was already occupied by stdin.
Fix: use syscall::openat_into to directly specify FD slots 0,1,2 in
start.rs, and use syscall::dup_into with a computed FD index for
cur-context in exec.rs. Both bypass the FILETABLE, which is only
populated later by redox_rt::initialize_freestanding.
This moves us closer towards having a single unified image for all arm64
systems. Only init still has the board compiled in rather than detecting
it from the device tree or ACPI tables.
On success, the number of bytes written should be returned.
Previously `buf.len()` was always returned. The function `send_slice`
> ... returns the amount of octets actually enqueued, which is limited
> by the amount of free space in the transmit buffer; down to zero.
"down to zero" is okay as that is checked by `can_send`.
Signed-off-by: Anhad Singh <andypython@protonmail.com>
Otherwise, an open call to /scheme/acpi/tables will result in nsmgr
blocking on an `openat(acpi_root, "tables")` call, which will never
occur if acpid is itself blocking on a `ForkNs` call to nsmgr before it
can serve any scheme requests.
This functionality is needed according to POSIX. Additionally, some
logic had to be changed in order for the ptsname to be correct for the
manager terminal (ptmx). If you want to obtain a pty, you must go
through the `posix_openpt`-`grantpt`-`unlockpt`-`ptsname`-`open`
process. Alternatively, relibc as a function called `openpty`.
This is part of my ptyd series. This can be safely merged once the MRs
for relibc/ and userutils/ are merged at the same time.
This way PCI drivers don't need to use the privileged physmap interface,
but only need access to a pcid handle. This is not yet enough for
running drivers as unprivileged processes. Interrupts also need
privileges and we need IOMMU support in the kernel.
Force probes can be rather expensive on real hardware so according to
the drm_mode_get_connector docs it should only be done at startup, on a
hotplug event and when explicitly requested by the user.
EOF used to be triggered by unmounting a scheme, but this is no longer
the case since namespaces got moved to userspace. Unmounting now only
closes the scheme root fd.
The only thing it does it changing the size of the region that the
graphics adapter sees as framebuffer. It doesn't actually tell vesad to
resize the framebuffer nor does it implement an actual full graphics
driver. For basic usage the bootloader setup framebuffer is sufficient
and for anything more advanced, virtio-gpu is a much better option that
we already have a full graphics driver for.
This way all components necessary to get a working network connection
are in the base repo. In the future this might help with mounting a
network disk from the initfs. The netutils recipe doesn't get included
in the initfs.
This is done by adding entries to the global GTT page table. At startup
it only contains entries for a small chunk of memory reserved for the
GPU. This small chunk is rarely enough to contain all framebuffers we
need to allocate.
Unlike DeviceFb a GpuBuffer only has a size, not a width, height and
stride. In the future GpuBuffer can be used for dumb buffers as well as
any other kind of memory we may need to allocate on the gpu.
This should not block and ensures that logs will still show up on the
serial port even if one of the log sinks blocks because for example the
graphics driver crashed, taking fbbootlogd with it. In the future we
might want to have a dedicated worker per log sink, but for now this
helps a log with debugging the graphics subsystem in a VM.
This is the actual size of the Orbital desktop. Previously resizing a
virtio-gpu window after Orbital started but before logging in would
cause the launcher to be out of view.
This matches the Linux DRM interface. With this I believe the only
divergence from the Linux DRM interface that would be a breaking change
to the in-tree users of the graphics api to change to the proper
interface is the use of the UPDATE_PLANE ioctl in the place of proper
modesetting interface. It should be possible to support this in
parallel to UPDATE_PLANE, so updating Orbital to the DRM interface
should now be possible. Orbital can be updated to the proper modesetting
interface once it is implemented.
Beforehand, if you spammed 'enter' (or any key) upon startup, your self
test would fail with 1C or 9C (the scancodes for pressing and releasing
enter respectively). We now disable the keyboard earlier, and this fixes
the issue.
This can be done using rmdir /scheme/my_scheme. Scheme implementations
do not yet exit when all fds are closed, but you can now kill the
service and restart it after you removed its scheme.
Rather than starting all services in the config dir, we only start those
which are a dependency of the target we want to reach. This is necessary
to handle unit templating, service start stop and an alternative target
for recovery or graceful shutdown.
Logd is a special case. Every other service effectively has an implicit
dependency on it for sending log messages to it and even init itself
depends on it for it's own log messages.
With this only the env vars set using export or explicitly specify for a
service are passed to services (in addition to RUST_BACKTRACE, PATH and
LD_LIBRARY_PATH). As such we no longer need to manually unset bootloader
env vars to keep the environment clean. And finally this means that env
var substitutions in shell scripts always use the bootloader provided
env vars rather than locally specified ones.
This does regress multi monitor support when there is no proper graphics
driver.
The working directory doesn't matter for services and login sessions
already cd to the user home directory. This removes one source of global
state manipulation.
This sets PATH, LD_LIBRARY_PATH and runs init scripts for the new root.
In the future this could replace the entire set of services that should
run, restarting any services for which a newer executable is available
in the new root and stopping any services which don't exist in the new
root. This behavior could also be useful for soft-reboots in the future
to handle updates without rebooting the entire system.
Unfortunately the scheme still has to be created by the daemon due to a
kernel bug, but once that is fixed, it would allow delayed spawning of
scheme daemons.
We did not update the relibc version needed for redox-rt or generic-rt.
Additionally, base @6b9593946 was missing an updated callsite for
`can_recv()`.
* sendmsg(2) on `SOCK_STREAM` with zero-byte payload is a no-op even if
ancillary data is present. Note that this does not apply to
`SOCK_DGRAM`.
* Pass the `msg_flags` to `get_connected_pear` as non-blocking behaviour
may be requested.
Signed-off-by: Anhad Singh <andypython@protonmail.com>
* Fix `num_succeeded` was never being incremented
* If no processes or process group could be found corresponding to that
specified by `target`, `ESRCH` should be returned.
* Document this behaviour.
This is the reason why `killpg` test was hanging instead of reporting an
error since `kill` was silently failing.
Signed-off-by: Anhad Singh <andypython@protonmail.com>
This removes one piece of state that init has to manage for the
processes it spawns. This also allows getting rid of the concept of a
default scheme from relibc if we want.
This only works in QEMU, so disable bgad in VirtualBox. It currently
doesn't do much useful anyway. It supports reporting the display size
(which vesad already supports) and changing the display size (which
doesn't really work anyway as the framebuffer mapping used by vesad
doesn't get resized.) And in any case vboxd already has code to use
the BGA interface for resizing that is broken to the same extend the
resizing in bgad is.
Previously only frame buffers up to 0x1_000_000 bytes were allowed,
while we use 0x10_000_000 as multiplier for the fake offsets and thus
can safely accept framebuffers this large. This should be enough for 4k
displays.
Pty::path is a manual implementation of write! that also allocates.
Using write! avoids the alloc and is simpler too.
The original function didn't return an error even if called with a small
buffer and this version preserves that.
This is a POSIX extension to disable control chars when set in the c_cc
array. Fish and other programs use it.
See:
* redox-os/relibc!689
* redox-os/termios!3
feat: Reimplement bind and connect operation using token and switch GetProcCredentials to capability-based approach.
See merge request redox-os/base!19
I hadn't meant to upstream it yet. I accidentally added it in a commit
touching the netstack. In any case this commit integrates the kernel log
copying directly into LogScheme.
The kernel log copying is meant to show the kernel log on the fbbootlogd
rendered bootlog. Even once the kernel graphical debug has been disabled
or if it never got enabled due to the bootloader not presenting a
framebuffer.
This prevents boot hangs when the disk driver hangs between creating the
disk scheme and being fully initialized, while still preventing race
conditions.
The stdout and stderr of the spawned processes are not captured by init,
so attempting to write captured input is useless. Also show the exit
code in case the child process returned an non-zero exit code.
The reason behind this is that an RTC driver should ideally consult ACPI
tables before assuming any I/O ports exist, which userspace can do much
better.
Currently only fbbootlogd and fbcond make use of support for multiple
damage areas and they are not all that performance critical anyway.
Orbital always passes a single damage area per write call. Out of all
graphics drivers we have and are likely to get only vesad could
potentially benefit from fine-grained damage areas. This commit doesn't
significantly impact performance of fbcond.
This avoid a deadlock when the process logging things is directly or
indirectly involved in receiving them too. Currently there is a
workaround for a part of this problem in fbbootlogd, but doing it
directly in logd is a lot simpler and catches more cases.
The PC speaker device is not a general purpose audio device, but only
capable of playing beeps. While pcspkrd does currently get built, it
never actually gets started at startup. There is also no program
anywhere inside Redox OS capable of playing any sound through pcspkrd.
And finally basically the thing it is used for on modern systems is to
emit a beep when pressing backspace in a VT while there is no input
buffered. I personally find that beep rather annoying and have disabled
the Linux counterpart to pcspkrd on my system because of this.
Support for TCP congestion control has been introduced in smoltcp 0.12.
Smoltcp supports Reno and CUBIC. Of the two CUBIC has higher throughput.
Enabling the socket-tcp-cubic feature is enough to default to CUBIC.
With this change pkg install libgcc is about 35% faster than previously
without congestion control. (5.5MiB/s vs 4MiB/s previously)
configuration_value is not an index into config_descs, so scan for a
config_desc with the right configuration_value instead. And fix get_desc
getting confused by companion descriptors.
It is quite likely that the next graphics API won't be the last one and
as such would become a legacy API too. Consistently using version
numbers makes it easier to refer to the exact version you mean.
Instead of requiring the graphics driver to create a fixed set of VTs in
advance. This fixes the graphical interface when there is a graphics
driver but no boot framebuffer. Previously in that case vesad would exit
before it creates any VT and thus no consumer could show anything as
their VT was missing. In the future creating new VTs on the fly could
also allow a display manager to use a separate VT for each user session.
Effectively the only way to recover from errors in the communication
with pcid is by restarting the driver from scratch possibly after
restarting pcid. As such moving the aborts from individual drivers to
pcid_interface simplifies drivers while at the same time allowing nicer
error messages.
This allows a single PCI daemon to run on the whole system, prevents
multiple drivers from claiming the same PCI device and makes it possible
for userspace to enumerate all available PCI devices. In the future this
will enable an lspci tool, possibly PCIe hot plugging and more.
Co-Authored-By: 4lDO2 <4lDO2@protonmail.com>
This will allow serializing/deserializing to be shared across programs.
For pcid-spawner will need to parse the config files and if we want to
embed config files into the driver executables at some point it may also
be useful.
This is the only part that actually modifies the PCI configuration. In
the future we will want to delay enabling a PCI device until it is
actually going to be used while still reading metadata about the PCI
device before that point.
Fbbootlogd doesn't do non-blocking operations, so fevent isn't needed.
And the kernel shouldn't pass closed handles to us and even if it does
due to a bug, it is harmless to silently ignore the fact that the handle
was closed.
driver-network does conversions from syscall::Error to std::io::Error
which needs the std feature enabled. Without this change rust-analyzer
would report errors when trying to compile driver-network without any
other crate in the same build to enable the std feature.
While for now this for now only includes helpers for the current limited
display interface which is relatively simple to implement manually, in
the future we will likely need a more complex interface with gpu drivers
that would be hard to get right without a common crate proving the
interface.
Graphics clients will need to handle resizing themself anyway for
handoff between graphics drivers and as such don't need the graphics
to modify the framebuffer during resize.
This unifies the driver interface handling between graphics drivers and
makes it easier to change all graphics drivers in lockstep when adding
new features.
If unaligned_length is for example 8193, the initial reservation would
be rounded up to the next page resulting in 12288. However the physmap
would previously round up to the next power of two forming 16384,
potentially overwriting one page of data directly after the reservation.
In case of bigger allocations, more pages could be overwritten.
Resources are global for the entire virtio-gpud device, not local to a
single display. In the future resource creation will become entirely
detached from specific displays.
With fbbootlogd split out it is no longer essential to avoid blocking
operations on the main thread of fbcond. Moving them back to the main
thread simplifies things a fair bit.
The daemon responsible for the boot log must never ever block to avoid
deadlocks, but doing so while still accepting keyboard input is
non-trivial. This commit splits the boot log out from fbcond into a
separate daemon to make this a lot easier to implement. This will also
allow making fbcond blocking again, which will simplify some things.
This ensures that the foreground VT doesn't lockup if a background VT
spams us with flush requests. In the future we may want to add a
scheduler or collapse redundant flush requests.
This will hopefully avoid confusion if someone in the future changes the
XferToHost2d in flush to pass a smaller GpuRect. Without adjusting
offset this would cause glitches.
It is now possible to write multiple damage locations in a single write
call. Vesad also no longer processes damage for background vt's. The
entire framebuffer will be redrawn once the vt switches to the
foreground anyway. And finally fsync now consistently redraws the entire
screen rather than having different behavior between vesad and
virtio-gpud.
With this virtio-gpud no longer has to support getting deactivated at
any time to hand back control to vesad. This makes it much easier to add
many new features that a proper graphics driver is supposed to support.
Be aware that virtio-gpud waits for the vsync on every flush request.
Fbcond and orbital are not really happy about this right now and when
something changes multiple times within a single frame, flush requests
queue up, causing the ui to hang until all flush requests are finished.
It is still possible to switch to another VT though which won't hang.
The code will become simpler once handoff is implemented such that
virtio-gpud no longer needs to support reset and reinitialization of the
virtio gpu device.
Previously inputd would directly push vt activation events to the
graphics driver, which required being quite lazy to prevent deadlocks as
well as the graphics driver having a location where events can be pushed
to. By having graphics drivers pull the vt activation events instead,
the effective control flow becomes simpler and it becomes easier to
correctly handle multiple graphics drivers on the system. For example it
becomes possible for multiple graphics drivers to present displays for a
single VT as well as making it easier to provide a handoff from the
early framebuffer to a real graphics driver.
ControlHandle is used to switch the active vt, while DisplayHandle is
used by display drivers to register new vt's. There are entirely
unrelated tasks and the fact that they had been merged together has been
confusing me for a while.
Also changed activating a VT to no longer create a new vt when none
existed previously. The target graphics driver may not be able to handle
the new VT. inputd -A already didn't allow activating non-existent VT's
as it first tried to open a consumer handle for the target VT.
Closes: #33
`Duration` is stored as microseconds internally.
The original code caused an overflow by...
```rust
Duration::from_millis(u64::MAX);
```
...which caused `u64::MAX` to be multiplied by 1000 and overflow.
Previous behavior would reply to other IPs that only match the subnet with our (IP, MAC) pair
but not respond to unicast requests addressed with an unknown (all zeroes) MAC or broadcast requests.
* Implement symlinks
* Initfs only has links with absolute paths.
* Relative links are assumed to be relative to link location.
* Absolute paths must point into the archived location. E.g. if we
archive /home/foo/data and wish the resultant link to point to
/scheme/rand, then the absolute link must be
/home/foo/data/scheme/rand.
* Move archive_common to a crate within the workspace -- Rust doesn't
seem to accept #[path(..)] attributes with `..` segments anymore so
tests wouldn't build on my machine.
* Improve the test to assert complete filesystem structure.
* Bump to edition 2021
* cargo fmt & clippy
This will make it easier to change the way logging is done for all
drivers. This also fixes the log category for a couple of drivers as
well as makes failing to set the logger a fatal error. Only when a
logger is already set is it impossible to set another logger.
This is the only case where init sets an env var without the user
instructing it to do so, making it hard to trace back where the env var
originated from. It also only sets it for processes spawned after the
first run.d command for whatever reason. And finally not setting DISPLAY
avoids hard coding knowledge about unrelated system components.
Currently pcid exits the main thread once it is done spawning drivers
and expects all background threads handling driver communication to stay
around. This only works as exitting the main thread on redox os
currently doesn't cause the whole process to die. This will have to be
fixed at some point for compatibility with programs that expect that
exitting the main thread kills all other threads in the process, at
which point pcid would break without the changes in this commit.
The vm call will clobber edi, which is the register in which we saved
the ebx value. Also make sure to preserve the entire rbx value, rather
than just the lower half in ebx.
This makes them harder to accidentally run them from the shell, which
would not work. In the future this may also allow embedding the driver
config in the driver executable itself without having to look at all
non-driver executables too.
This significantly reduces cpu usage. On my laptop before this change a
single core would be fully loaded while running at 3-4GHz. With this
change it would only be loaded for about 50% while running at 1-2GHz.
This improves battery lifetime while also preventing the fan from
spinning up to a distracting level.
This shouldn't noticably affect latency given that most keyboards and
mice don't support polling at 500Hz anyway.
Transitional virtio devices (which have both legacy and virtio 1.0
support) have been the default since QEMU 2.7.0, which was released
8 years ago. Basically every non-commercial Linux distro with an older
QEMU has been EOL already.
The legacy transport is also one of the few places where port I/O is
necessary, which is non-trivial to sandbox even once we have IOMMU
support. As it isn't possible to distinguish legacy and modern virtio
devices for pcid, this would mean that all virtio drivers have to be
started as privileged even if it turns out the modern transport is
supported by the VMM.
The current frame allocator limits requests to powers of two, between 4
KiB and 4 MiB. As such, a 8-bit color 1920x1080 framebuffer needs at
least two allocations.
Devices should never change the feature status behind the back of the
driver, so storing the current status after setting it is fine. Drivers
should reset all state when they start to recover from a crashed driver,
so they shouldn't need to get the current feature status at startup
either.
error: casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
--> virtio-core/src/probe.rs:126:21
|
86 | let capability = unsafe { &*(capability.data.as_ptr() as *const PciCapability) };
| --------------------------------------------------- backing allocation comes from here
...
126 | (&*(capability as *const PciCapability as *const PciCapabilityNotify))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: casting from `transport_pci::PciCapability` (13 bytes) to `transport_pci::PciCapabilityNotify` (17 bytes)
= note: `#[deny(invalid_reference_casting)]` on by default
It isn't used in any driver and even on Linux no driver seems to use it
at all. The only times it seems to be useful are if you were to mask an
interrupt and want to check if the interrupt fired without unmasking or
if you want to make the device itself trigger an interrupt.
The set and write methods were useless as no rpc call is exposed by
pcid to actually write the new values. As for the rest, there were
no uses and they can be emulated using the other methods.
Fetching BARs will temporarily invalidate them, which could cause
crashes if a driver happens to access it at the same time. As we
don't yet use a single pcid instance, we don't know which devices
have a driver attached or not. As such approximate this as the set
of devices for which the current pcid instance would load a driver.
Most things are already stored in SubdriverArguments and the couple of
things that aren't may change over time and thus should be read again
each time they are accessed, while fetch_header would receive a fixed
copy from pcid.
Some of these are removed with PCIe while many others only need to be
used by the firmware to initialize the PCI bridges. If we ever need
them anyway, we can always add them back, but for now it improves
readability.
They weren't used in a load bearing way. If we want to keep persistent
state about buses and devices in the future they would probably get a
different shape.
This will in the future allow switching between graphical mode and text
mode virtual terminals while keeping alternative graphics drivers like
virtio-gpud enabled at all times rather than having to reset back to VGA
mode every time.
It is never enabled and would add a fair amount of complexity to a
system service which has effective root access despite sandboxing due to
being able to read and write display contents and input device events.
This will transparently release the mouse grab of the VM when leaving
the screen edge, making it much easier to quickly switch between the VM
and other apps running on the host.
It is no longer possible to query the display size from inputd, so defer
conversion to display pixel coordinates to orbital instead. This also
avoids a lot of work every mouse event to query the display size as
orbital saves this information already.
There seems to be a bug somewhere in the global_asm block which causes a
SIGSEGV when making unrelated code changes to ps2d. Using an inline asm
block is easier to follow and less error prone around following the
calling convention.
The entries in the search dirs will be merged with the entry in the last
search dir taking priority in case multiple entries have the same name.
This allows putting system init configs in /usr/lib/init.d while the
user can overwrite it by placing a file with the same name in
/etc/init.d
- Smoltcp now talk to a IP device that does the routing
- Add RouteTable
- Add trait LinkDevice representing devices (eth0, loopback...)
- Remove old device
sys_physmap() requires the address to be page aligned. This fixes the
panic inside the `virtio-gpu` driver.
Signed-off-by: Anhad Singh <andypython@protonmail.com>
This allows for us to do cool stuff such as
`join!(queue.send(read_command), queue.send(write_command),
queue.send(read_command_2))`
Signed-off-by: Anhad Singh <andypython@protonmail.com>
* Minor code cleanup
* Able to read/write from the disk
* Recycle the descriptors (this is currently done inefficiently, will be
fixed in a follow up commit)
* Add the disk scheme for virtio-blk with working functionality for seek(),
read() and open()
* After all of this work, we are successfully able to boot redox from
virtio-blk!! :)
Signed-off-by: Anhad Singh <andypython@protonmail.com>
According to the virtio sspecification v1.2, MSI-X support is REQUIRED
and is the only supported method anyways (i.e, legacy int and MSI wont
work).
Signed-off-by: Anhad Singh <andypython@protonmail.com>
This commit adds the `get_capabilities` function to `PcidServerHandle`
which returns all of the `Capability`s (raw representation) of the PCI
device.
Signed-off-by: Anhad Singh <andypython@protonmail.com>
Previously ramfs allowed identical filenames to be created if the
O_CREAT flag was used. This patch fixes the behavior and instead
opens the existing file as long as O_EXCL is not specified.
In the future, this will probably be moved into its own driver, probably
called `intelvtdd` or `intelvfiod`. This is because `acpid` already
provides an interface to read from ACPI tables, which `pcid` has used
for quite long (when that scheme was provided by the kernel). AMD
implements IOMMU as a PCI function, so letting these be separate drivers
would certainly be beneficial.
The same thing might apply for HPET or MADT, which are the only ACPI
tables still parsed in the kernel.
This change adds a structopt commandline interface to the pcid tool.
This add some help for the arguments that pcid takes.
Signed-off-by: Wren Turkal <wt@penguintechs.org>
When working in an IDE like vscode, it uses rust infrastructure to
check the code, which results in "target" folders in the base of
the crates I am working on. For example, if I am working on pcid
code, I get a "target" folder in the pcid folder. This change
causes git to ignore all those target directories.
Signed-off-by: Wren Turkal <wt@penguintechs.org>
The pcid capability parsing code has an assertion that checks for dword
alignment. Unfortunately, the check was previously checking for
alignment to qwords. This fixes that.
I found this issue by using qemu to emulate adding different pci
devices. I managed to come across a device that had a capability
aligned on dword, but not qword. That exposed the bug.
Signed-off-by: Wren Turkal <wt@penguintechs.org>
Previously, the PCI bus scan was skipping bus 0xFF. Now it does not.
I used a match expression to make sure that all cases are accounted for.
I also changed the PCI dev scan and PCI func scan to use a match
expression in a similar way to make sure all cases are account. While
this is functionally the same as before, the match expression will not
allow unhandled cases and should be easier to read and make it harder
to introduce bugs.
Signed-off-by: Wren Turkal <wt@penguintechs.org>
Note that by writing submission, I'm referring to blocking until a
submission queue has more entries available. The command completion
handling is already async.
This is the first command that actually worked by calling the IRQ
reactor and then getting a response. While this may not be that much on
its own, it means the async/await model actually works in this context.
Now the major problem is getting rid of all the deadlocks, and later
remove block_on(future) in the Scheme impl, and instead go async with
future spawning instead.
Some commands are unused though, and probably won't be used, for example
ReportSuppOpcodes. Also, there appears to be lots of different versions
of the SCSI specification.
Sidenote: instead of STALLing because the driver didn't configure the
endpoints properly, regular transfers now work. Thus, QEMU was able to
recognize that it received a Bulk-Only Transport CBW. Yay!
Additionally, to make life easier when debugging, usbctl was added; now
it can get endpoint statuses which were previously non-accessible from
shell scripts, after the transition to the new ctl+data endpoint
interface.
Previous approach, reverted in commit c7cf2ca, would break unnamed
sockets - since it assumed there would always be an interim step were
one would first name an unnamed socket, before "listen" / "connect".
Instead of using the same approach as the "tcp:" scheme in Redox's
netstack, which requires an extra mapping of temporary unnamed sockets,
handle the different use cases in dup(). Thus, if a "buf" is provided
that's not a "connect" or "listen", it must be a new path for turning
the unnamed socket into a named socket and should be handled as such.
While supporting AF_UNIX, once an accept() is called in relibc, in turn,
a dup() is also called with "listen". While processing this ipcd
effectively creates a new handler, losing track of the path of the
previous handler.
However, it is important to keep this path in the newly created Handler
as well, so the socket can be queried later by relibc (when calling
fpath()) and fill in appropriately its sockaddr_un struct.
Similarly to how the "tcp:" in Redox's netstack supports opening a first
empty scheme, only to later on being dup()'ed and set with an
appropriate path, this follows the same approach - a map of NullFile
structs is kept and initially associated with an id. Next time dup() is
called, the true Handle is created, keeping the same definitions of the
previously created NullFile.
Not that it is important to add support for this in the ipcd to support
AF_UNIX sockets, otherwise the socket() created in relibc won't be
associated with a address / path.
Add permissions to scheme operations
Add ability to change owner/group/mode
Add ability to write entropy to the PRNG scheme
Add streaming of ChaCha20 PRNG output based on file open operation.
Add not seeded message if rdrand not present on CPU
Add extra TODOs for new future work
This fixes one problem with openssl on relibc, since relibc correctly respects readable/writable status unlike the newlib implementation which always says it's readable.
- Update the PCI config space parsing to be able to handle multiple
types.
- Use a trait to abstract out reading from the config space in order to
allow testing/fuzzing of the parser.
- Use EthernetInterfaceBuilder instead of EthernetInterface::new
- smoltcp removed the ArpCache trait in favor of ManagedMap.
NB: This breaks the use of loopback and sending packets to yourself.
This keyboard layout is only used in the United States, other
english-speaking countries may have their own standard keyboard layouts.
This commit changes the name of the 'english' layout to 'us' to match
X11.
* Fire up multiple processors
* Use IPIs to wake up secondary processors
* Much better exception information
* Modifications to show more information on fault
* WIP: Use real libstd
* Add TLS (not complete)
* Add random function, export getpid, cleanup
* Do not spin APs until new context
* Update rust
* Update rust
* Use rd/wrfsbase
* Implement TLS
* Implement compiler builtins and update rust
* Update rust
* Back to Redox libstd
* Update rust
* Rewriting network functions
* Add buffer to dup
Fix non-blocking handling by triggering once on enabling events to read to EOF
* Modifications for UDP API
* Implement TCP client side
* Add active close
* Add DMAR parser
* Implement basic TCP listening. Need to improve the state machine
* Reduce debugging
* Fixes for close procedure
* Updates to fix path processing in libstd
* Port previous ethernet scheme
* Add ipd
* Fix initfs rebuilds, use QEMU user networking addresses in ipd
* Add tcp/udp, netutils, dns, and network config
* Add fsync to network driver
* Add dns, router, subnet by default
* Fix e1000 driver. Make ethernet and IP non-blocking to avoid deadlocks
* Add orbital server, WIP
* Add futex
* Add orbutils and orbital
* Update libstd, orbutils, and orbital
Move ANSI key encoding to vesad
* Add orbital assets
* Update orbital
* Update to add login manager
* Add blocking primitives, block for most things except waitpid, update orbital
* Wait in waitpid and IRQ, improvements for other waits
* Fevent in root scheme
* WIP: Switch to using fevent
* Reorganize
* Event based e1000d driver
* Superuser-only access to some network schemes, display, and disk
* Superuser root and irq schemes
* Fix orbital
<!-- Thank you for taking the time to submit an issue! By following these comments and filling out the sections below, you can help the developers get the necessary information to fix your issue. Please provide a single issue per report. You can also preview this report before submitting it. Feel free to modify/remove sections to fit the nature of your issue. -->
<!-- Please search to check that your issue has not been created already. By preventing duplicate issues, you can help keep the repository organized. If your current issue has already been created and is still unresolved, you can contribute by commenting there. -->
<!-- Replace the empty checkbox [ ] below with a checked one [x] if you have already searched for your issue. -->
- [ ] I agree that I have searched opened and closed issues to prevent duplicates.
--------------------
## Description
<!-- Briefly summarize/describe the issue that you are experiencing below. -->
Replace me
## Environment info
<!-- To understand where your issue originates, please include some relevant information about your environment. -->
<!-- If you are using a pre-built release of Redox, please specify the release version below. -->
- Redox OS Release:
0.0.0 Remove me
<!-- If you have built Redox OS yourself, please provide the following information: -->
- Operating system:
Replace me
-`uname -a`:
`Replace me`
-`rustc -V`:
`Replace me`
-`git rev-parse HEAD`:
`Replace me`
<!-- Depending on your issue, additional information about your environment (network config, package versions, dependencies, etc.) can also help. You can list that below. -->
- Replace me:
Replace me
## Steps to reproduce
<!-- If possible, please list the steps to reproduce ("trigger") your issue below. Being detailed definitely helps speed up bug fixes. -->
1. Replace me
2. Replace me
3. ...
## Behavior
<!-- It may seem obvious to know what to expect, but isolating the behavior from everything else simplifies the development process. Remember to provide a single issue in this report. You can use the References section below to link your issues together. -->
<!-- Describe the behavior you expect your steps should yield (i.e., correct behavior). -->
- **Expected behavior**:
Replace me
<!-- Describe the behavior you observed when running your steps (i.e., buggy behavior). -->
- **Actual behavior**:
Replace me
<!-- **Logs?** Posting a log can help developers find your particular issue more easily. Please wrap your code in code blocks using triple back-ticks ``` to increase readability. -->
```
Replace me
```
<!-- **Solution?** Have a solution in mind? Propose your solution below. -->
- **Proposed solution**:
Replace me
<!-- **Screenshots?** Make it easier to get your point across with screenshots. You can drag & drop or paste your images below. -->
## Optional references
<!-- If you have found issues or pull requests that are related to or blocking this issue, please link them below. See https://help.github.com/articles/autolinked-references-and-urls/ for more options. You can also link related code snippets by providing the permalink. See https://help.github.com/articles/creating-a-permanent-link-to-a-code-snippet/ for more information. -->
Related to:
-#0000 Remove me
- Replace me
- ...
Blocked by:
-#0000 Remove me
- ...
## Optional extras
<!-- If you have other relevant information not found in other sections, you can include it below. -->
Replace me
<!-- **Code?** Awesome! You can also create a pull request with a reference to this issue. -->
<!-- **Files?** Attach your relevant files by dragging & dropping or pasting them below. -->
<!-- You also can preview your report before submitting it. Thanks for contributing to Redox! -->
# Porting the core Redox kernel to arm AArch64: An outline
## Intro
This document is [my](https://github.com/raw-bin) attempt at:
* Capturing thinking on the work needed for a core Redox kernel port
* Sharing progress with the community as things evolve
* Creating a template that can be used for ports to other architectures
Core Redox kernel means everything needed to get to a non-graphical console-only multi-user shell.
Only the 64-bit execution state (AArch64) with the 64-bit instruction set architecture (A64) shall be supported for the moment. For more background/context read [this](https://developer.arm.com/products/architecture/a-profile/docs/den0024/latest/introduction).
This document is intended to be kept *live*. It will be updated to reflect the current state of work and any feedback received.
It is hard~futile to come up with a strict sequence of work for such ports but this document is a reasonable template to follow.
## Intended target platform
The primary focus is on [qemu's virt machine platform emulation for the AArch64 architecture](https://github.com/qemu/qemu/blob/master/hw/arm/virt.c#L127).
Targeting a virtual platform is a convenient way to bring up the mechanics of architectural support and makes the jump to silicon easier. The preferred boot chain for AArch64 (explained later) is well supported on this platform and boot-over-tftp from localhost makes the debug cycle very efficient.
Once the core kernel port is complete a similar follow on document will be created that is dedicated to silicon bring-up.
| [Linux kernel boot protocol for AArch64](https://www.kernel.org/doc/Documentation/arm64/booting.txt) | The linked document describes assumptions made from the bootloader which are field tested and worthwhile to have for Redox an AArch64. <br/> The intent is to consider most of the document except anything tied to the Linux kernel itself. |
| [Flattened Device Tree](https://elinux.org/Device_Tree_Reference) | FDT binary blobs supplied by the bootloader shall provide the Redox kernel with misc platform \{memory, interrupt, devicemem} maps. Qemu's virt machine platform synthetically creates an FDT blob at a specific address which is very handy. |
| [ARM Trusted Firmware (TF-A)](https://github.com/ARM-software/arm-trusted-firmware) | TF-A is a de-facto standard reference firmware implementation and proven in the field. <br/> TF-A runs post power-on on Armv8-A implementations and eventually hands off to further stages of the boot flow.<br />For qemu's virt machine platform, it is essentially absent but I mean to rely on it heavily for silicon bring up hence mentioning it here. |
| [u-boot](https://www.denx.de/wiki/U-Boot) | u-boot will handle early console access, media access for fetching redox kernel images from non-volatile storage/misc disk subsystems/off the network. <br /> u-boot supports loading EFI applications. If EFI support to AArch64 Redox is added in the future that should essentially work out of the box. <br /> u-boot will load redox and FDT binary blobs into RAM and jump to the redox kernel. |
| Redox early-init stub | For AArch64, the redox kernel will contain an A64 assembly stub that will setup the MMU from scratch. This is akin to the [x86_64 redox bootloader](https://github.com/redox-os/bootloader/blob/master/x86_64/startup-x86_64.asm). <br /> This stub sets up identity maps for MMU initialization, maps the kernel image itself as well as the device memory for the UART console. At present this stub shall be a part of the kernel itself for simplicity. |
| Redox kstart entry | The early init stub hands off here. kstart will then re-init the MMU more comprehensively. |
## Supported devices
The following devices shall be supported. All necessary information specific to these devices will be provided to the redox kernel by the platform specific FDT binary blob.
| [Generic Interrupt Controller v2](https://developer.arm.com/products/architecture/a-profile/docs/ihi0048/b/arm-generic-interrupt-controller-architecture-version-20-architecture-specification) | The GIC is an Arm-v8A architectural element and is supported by all architecturally compliant processor implementations. GICv2 is supported by qemu's virt machine emulation and most subsequent GIC implementations are backward compatible to GICv2. |
| [Generic Timer](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500d/BGBBIJCB.html) | The Generic Timer Architecture is an Arm-v8A architectural element and is implemented by all compliant processor implementations. It is supported by qemu. |
| [PrimeCell UART PL011](http://infocenter.arm.com/help/topic/com.arm.doc.ddi0183f/DDI0183.pdf) | The PL011 UART is supported by qemu and most ARM systems. |
| Redox AArch64 toolchain | Create an usable redox AArch64 toolchain specification | Done | Using this JSON spec in isolated tests produces valid AArch64 soft float code |
| Stubbed kernel image | Stub out AArch64 kernel support using the existing x86_64 arch code as a template <br /> Modify redox kernel build glue and work iteratively to get a linkable (non-functional) image | Not done yet | |
| Boot flow | Create a self hosted u-boot -> redox kernel workflow <br /> Should obtain the stubbed image from a local TFTP server, load it into RAM and jump to it | Not done yet | |
| GDB Debug flow | Create a debug workflow centered around qemu's GDB stub <br /> This should allow connecting to qemu's GDB stub and debug u-boot/redox stub via a GDB client and single stepping through code | Not done yet | |
| Verify Redox entry | Verify that control reaches the redox kernel from u-boot | Not done yet | |
| AArch64 early init stub | Add support for raw asm code for early AArch64 init in the redox kernel <br /> Verify that this code is located appropriately in the link map and that control reaches this code from u-boot | Not done yet | |
| Basic DTB support | Integrate the [device_tree crate](https://mbr.github.io/device_tree-rs/device_tree/) <br /> Use the crate to access the qemu supplied DTB image and extract the memory map | Not done yet | |
| Basic UART support | Use the device_tree crate to get the UART address from the DTB image and set up the initial console <br /> This is a polling mode only setup | Not done yet | |
| Initial MMU support | Implement initial MMU support in the early init stub <br /> This forces the MMU into a clean state overriding any bootloader specific setup <br /> Create an identity map for MMU init <br /> Create a mapping for the kernel image <br /> Create a mapping for any devices needed at this stage (UART) | Not done yet | |
| kmain entry | Verify that kmain entry works post early MMU init | Not done yet | |
| Basic Redox MMU support | Get Redox to create a final set of mappings for everything <br /> Verify that this works as expected | Not done yet | |
| Basic libc support | Flesh out a basic set of libc calls as required for simple user-land apps | Not done yet | |
| userspace_init entry | Verify user-space entry and /sbin/init invocation | Not done yet | |
| Basic Interrupt controller support | Add a GIC driver <br /> Verify functionality | Not done yet | |
| Basic Timer support | Add a Generic Timer driver <br /> Verify functionality | Not done yet | |
| UART interrupt support | Add support for UART interrupts | Not done yet | |
| Task context switch support | Add context switching support <br /> Verify functionality | Not done yet | |
| Login shell | Iteratively add and verify multi-user login shell support | Not done yet | |
| Publish development branch on github | Work with the community to post work done after employer approval | Not done yet | |
| Break out the Bubbly | Drink copious quantities of alcohol to celebrate | Not done yet | |
| Silicon bring-up | Plan silicon bring-up | Not done yet | |
You can see what each component does in the following list:
## Requirements
* [`nasm`](https://nasm.us/) needs to be available on the PATH at build time.
## Building The Documentation
Use this command:
```sh
cargo doc --open --target x86_64-unknown-none
```
## Debugging
### QEMU
Running [QEMU](https://www.qemu.org) with the `-s` flag will set up QEMU to listen on port `1234` for a GDB client to connect to it. To debug the redox kernel run.
```sh
make qemu gdb=yes
```
This will start a virtual machine with and listen on port `1234` for a GDB or LLDB client.
### GDB
If you are going to use [GDB](https://www.gnu.org/software/gdb/), run these commands to load debug symbols and connect to your running kernel:
```
(gdb) symbol-file build/kernel.sym
(gdb) target remote localhost:1234
```
### LLDB
If you are going to use [LLDB](https://lldb.llvm.org/), run these commands to start debugging:
After connecting to your kernel you can set some interesting breakpoints and `continue`
the process. See your debuggers man page for more information on useful commands to run.
## Notes
- Always use `foo.get(n)` instead of `foo[n]` and try to cover for the possibility of `Option::None`. Doing the regular way may work fine for applications, but never in the kernel. No possible panics should ever exist in kernel space, because then the whole OS would just stop working.
- If you receive a kernel panic in QEMU, use `pkill qemu-system` to kill the frozen QEMU process.
- audiod : Daemon used to process the sound drivers audio
- bootstrap : First code that the kernel executes, responsible for spawning the init daemon
- daemon : Redox daemon library
- drivers
- init : Daemon used to start most system components and programs
- initfs : Filesystem with the necessary system components to run RedoxFS
- ipcd : Daemon used for inter-process communication
- logd : Daemon used to log system components and daemons
- netstack : Daemon used for networking
- ptyd : Daemon used for pseudo-terminal
- ramfs : RAM filesystem
- randd : Daemon used for random number generation
- zerod : Daemon used to discard all writes and fill read buffers with zero
## How To Contribute
To learn how to contribute to this system component you need to read the following document:
To learn how to contribute you need to read the following document:
If you want to contribute to drivers read its [README](drivers/README.md)
## Development
To learn how to do development with this system component inside the Redox build system you need to read the [Build System](https://doc.redox-os.org/book/build-system-reference.html) and [Coding and Building](https://doc.redox-os.org/book/coding-and-building.html) pages.
To learn how to do development with these system components inside the Redox build system you need to read the [Build System](https://doc.redox-os.org/book/build-system-reference.html) and [Coding and Building](https://doc.redox-os.org/book/coding-and-building.html) pages.
### How To Build
To build this system component you need to download the Redox build system, you can learn how to do it on the [Building Redox](https://doc.redox-os.org/book/podman-build.html) page.
It is recommended to build this system component via the Redox build system, you can learn how to do it on the [Building Redox](https://doc.redox-os.org/book/podman-build.html) page.
This is necessary because they only work with cross-compilation to a Redox virtual machine, but you can do some testing from Linux.
To build and test outside the build system, [install redoxer](https://doc.redox-os.org/book/ci.html) then use `check.sh` script to build or test:
-`./check.sh` - Check build for x86_64
-`./check.sh --arch=ARCH` - Check build for specific ARCH (`aarch64`, `i586`, `riscv64gc`)
-`./check.sh --all` - Check build for all ARCH
-`./check.sh --test` - Check the base system boots up on x86_64
## Funding - _Unix-style Signals and Process Management_
This project is funded through [NGI Zero Core](https://nlnet.nl/core), a fund established by [NLnet](https://nlnet.nl) with financial support from the European Commission's [Next Generation Internet](https://ngi.eu) program. Learn more at the [NLnet project page](https://nlnet.nl/project/RedoxOS-Signals).
[<img src="https://nlnet.nl/logo/banner.png" alt="NLnet foundation logo" width="20%" />](https://nlnet.nl)
[<img src="https://nlnet.nl/image/logos/NGI0_tag.svg" alt="NGI Zero Logo" width="20%" />](https://nlnet.nl/core)
You can also use `make install` to inspect the content on `./sysroot`, or `make test-gui` to test booting with orbital interactively.
This document tracks the devices from developers or community that need a driver.
This document was created because unfortunately we can't know the most sold device models of the world to measure our device porting priority, thus we will use our community data to measure our device priorities, if you find a "device model users" survey (similar to [Debian Popularity Contest](https://popcon.debian.org/) and [Steam Hardware/Software Survey](https://store.steampowered.com/hwsurvey/Steam-Hardware-Software-Survey-Welcome-to-Steam)), please comment.
If you want to contribute to this table, install [pciutils](https://mj.ucw.cz/sw/pciutils/) on your Linux or Unix-like distribution (it may have a package on your distribution), run the `lspci -v` command to see your hardware devices, their kernel drivers and give the results of these items on each device:
- The first field (each device has an unique name for this item)
- Kernel driver
- Kernel module
If you are unsure of what to do, you can talk with us on the [chat](https://doc.redox-os.org/book/chat.html).
## Template
You will use this template to insert your devices on the table.
```
| | | | No |
```
- Remove the `#` characters in the port numbers to avoid GitLab issues to be wrongly mentioned
Some drivers are work-in-progress and incomplete, read [this](https://gitlab.redox-os.org/redox-os/base/-/issues/56) tracking issue to verify.
## System Interfaces
This section explain the system interfaces used by drivers.
### System Calls
-`iopl` : system call that sets the I/O privilege level. x86 has four privilege rings (0/1/2/3), of which the kernel runs in ring 0 and userspace in ring 3. IOPL can only be changed by the kernel, for obvious security reasons, and therefore the Redox kernel needs root to set it. It is unique for each process. Processes with IOPL=3 can access I/O ports, and the kernel can access them as well.
### Schemes
-`/scheme/memory/physical` : Allows mapping physical memory frames to driver-accessible virtual memory pages, with various available memory types:
-`/scheme/memory/physical` : Default memory type (currently writeback)
-`/scheme/irq` : Allows getting events from interrupts. It is used primarily by listening for its file descriptors using the `/scheme/event` scheme.
## Contribution Details
### Driver Design
A device driver on Redox is an user-space daemon that use system calls and schemes to work, while operating systems with monolithic kernels drivers use internal kernel APIs instead of common program APIs.
If you want to port a driver from a monolithic operating system to Redox you will need to rewrite the driver with reverse enginnering of the code logic, because the logic is adapted to internal kernel APIs (it's a hard task if the device is complex, datasheets are much more easy).
### Write a Driver
Datasheets are preferable (much more easy depending on device complexity), when they are freely available. Be aware that datasheets are often provided under a [Non-Disclosure Agreement](https://en.wikipedia.org/wiki/Non-disclosure_agreement) from hardware vendors, which can affect the ability to create an MIT-licensed driver.
If datasheets aren't available you need to do reverse-engineering of BSD or Linux drivers (if you want use a Linux driver as reference for your Redox driver please ask in the [Chat](https://doc.redox-os.org/book/chat.html) before the implementation to know/satisfy the license requirements and not waste your time, also if you use a BSD driver not licensed as BSD as reference).
### Libraries
You should use the [redox-scheme](https://crates.io/crates/redox-scheme) and [redox_event](https://crates.io/crates/redox_event) libraries to create your drivers, you can also read the [example driver](https://gitlab.redox-os.org/redox-os/exampled) or read the code of other drivers with the same type of your device.
Before testing your changes be aware of [this](https://doc.redox-os.org/book/coding-and-building.html#how-to-update-initfs).
### References
If you want to reverse enginner the existing drivers, you can access the BSD code using these links:
To learn how to do development with this system component inside the Redox build system you need to read the [Build System](https://doc.redox-os.org/book/build-system-reference.html) and [Coding and Building](https://doc.redox-os.org/book/coding-and-building.html) pages.
### How To Build
To build this system component you need to download the Redox build system, you can learn how to do it on the [Building Redox](https://doc.redox-os.org/book/podman-build.html) page.
This is necessary because they only work with cross-compilation to a Redox virtual machine or real hardware, but you can do some testing from Linux.
/// If true, an equivalent to the x86 [WBINVD](https://www.felixcloutier.com/x86/wbinvd) instruction is supported.
/// All caches will be flushed and invalidated upon completion of this instruction,
/// and memory coherency is properly maintained. The cache *SHALL* only contain what OSPM references or allows to be cached.
pubfnsupports_equivalent_to_wbinvd(&self)-> bool{
self.0.get_bit(0)
}
/// If true, [WBINVD](https://www.felixcloutier.com/x86/wbinvd) properly flushes all caches and memory coherency is maintained, but caches may not be invalidated.
pubfnwbinvd_flushes_all_caches(&self)-> bool{
self.0.get_bit(1)
}
/// If true, all processors implement the C1 power state.
/// If true, this system is a hardware-reduced ACPI platform, and software methods are used for fixed-feature functions defined in chapter 4 of the ACPI specification.
pubfnsystem_is_hw_reduced_acpi(&self)-> bool{
self.0.get_bit(20)
}
/// If true, the system can achieve equal or better power savings in an S0 power state, making an S3 transition useless.
pubfnno_benefit_to_s3(&self)-> bool{
self.0.get_bit(21)
}
}
#[derive(Clone, Copy, Debug)]
pubstructIaPcBootArchFlags(u16);
implIaPcBootArchFlags{
/// If true, legacy user-accessible devices are available on the LPC and/or ISA buses.
pubfnlegacy_devices_are_accessible(&self)-> bool{
self.0.get_bit(0)
}
/// If true, the motherboard exposes an IO port 60/64 keyboard controller, typically implemented as an 8042 microcontroller.
pubfnmotherboard_implements_8042(&self)-> bool{
self.0.get_bit(1)
}
/// If true, OSPM *must not* blindly probe VGA hardware.
/// VGA hardware is at MMIO addresses A0000h-BFFFFh and IO ports 3B0h-3BBh and 3C0h-3DFh.
pubfndont_probe_vga(&self)-> bool{
self.0.get_bit(2)
}
/// If true, OSPM *must not* enable message-signaled interrupts.
pubfndont_enable_msi(&self)-> bool{
self.0.get_bit(3)
}
/// If true, OSPM *must not* enable PCIe ASPM control.
pubfndont_enable_pcie_aspm(&self)-> bool{
self.0.get_bit(4)
}
/// If true, OSPM *must not* use the RTC via its IO ports, either because it isn't implemented or is at other addresses;
/// instead, OSPM *MUST* use the time and alarm namespace device control method.
/// The table provides information about the configuration and use of the
/// serial port or non-legacy UART interface. On a system where the BIOS or
/// system firmware uses the serial port for console input/output, this table
/// should be used to convey information about the settings.
///
/// For more information, see [the official documentation](https://learn.microsoft.com/en-us/windows-hardware/drivers/serports/serial-port-console-redirection-table).
#[repr(C, packed)]
#[derive(Debug)]
pubstructSpcr{
pubheader: SdtHeader,
pubinterface_type: u8,
_reserved: [u8;3],
pubbase_address: RawGenericAddress,
pubinterrupt_type: u8,
pubirq: u8,
pubglobal_system_interrupt: u32,
/// The baud rate the BIOS used for redirection.
pubconfigured_baud_rate: u8,
pubparity: u8,
pubstop_bits: u8,
pubflow_control: u8,
pubterminal_type: u8,
/// Language which the BIOS was redirecting. Must be 0.
publanguage: u8,
pubpci_device_id: u16,
pubpci_vendor_id: u16,
pubpci_bus_number: u8,
pubpci_device_number: u8,
pubpci_function_number: u8,
pubpci_flags: u32,
/// PCI segment number. systems with fewer than 255 PCI buses, this number
/// will be 0.
pubpci_segment: u8,
pubuart_clock_freq: u32,
pubprecise_baud_rate: u32,
pubnamespace_string_length: u16,
pubnamespace_string_offset: u16,
}
unsafeimplAcpiTableforSpcr{
constSIGNATURE: Signature=Signature::SPCR;
fnheader(&self)-> &SdtHeader{
&self.header
}
}
implSpcr{
/// Gets the type of the register interface.
pubfninterface_type(&self)-> SpcrInterfaceType{
SpcrInterfaceType::from(self.interface_type)
}
/// The base address of the Serial Port register set, if if console
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
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.