Skip to content

sensors: leave a swept bus that only times out, and probe no bus twice - #295

Merged
openipc-ai merged 2 commits into
masterfrom
sweep-leave-dead-bus
Nov 25, 2026
Merged

openipc-ai merged 2 commits into
masterfrom
sweep-leave-dead-bus

Conversation

@openipc-ai

@openipc-ai openipc-ai commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Symptom

On an XM IVG-N8S (NT98566, IMX415), the ipcinfo --short-sensor that runs at boot takes about 27 s when the sensor does not answer, with i2c transfer timed out from f0350000.i2c2 and f03a0000.i2c3 (reported in OpenIPC/firmware#1889).

Cause

When nothing answers on the bus the HAL nominated, the probe sweeps the others, about 13 reads each on Novatek. The kernel driver fails a transfer that never completes with ETIMEDOUT after a fixed 1 s, while a NACK is EREMOTEIO at once. Two such buses are about 26 s, which matches the 27 s. The report also had a 41 s run, timed from syslog. The reporter puts that down to ntpd stepping the clock during detection: a later boot took 42 s by syslog and 27.4 s by uptime.

Change

  1. A swept bus is left after two reads in a row fail with ETIMEDOUT, so such a bus costs about 2 s instead of 13. A NACK or a good read resets the count, so an empty bus is still probed in full. The nominated bus is untouched, and so are the buses in hal_sensor_buses.
  2. A bus already probed is not probed again. Novatek's opener answers number 5 with /dev/i2c-0, and every number with /dev/i2c-1 on some dies. The adapter is compared by the device number of the opened i2c-dev node (major 89); anything else is never treated as the same bus.

The probes call i2c_read_register by that name, so the sweep borrows that global and gives it back, as get_sensor_id_spi() does with its own. Writes are not affected, so a register page is still put back. Other HALs benefit where their reader returns -1 with errno at ETIMEDOUT; elsewhere the count never rises.

getsensorid() takes no lock, so a second probing thread that finds the reader already borrowed does not save it as the HAL's: it would call itself until the stack overflowed. Concurrent sweeps still share the timeout count, so one thread's timeouts can end another's sweep of a bus. Sensor detection already relied on unlocked global state, and this PR does not add a lock.

A bus reporting busy (EBUSY) is not covered.

Tests

sensors_test gains a mock bus set: dead, empty and intermittent buses, a number that opens another's bus, descriptors whose adapter is unknown, and a sensor behind a dead bus. Undoing any of the pieces fails it (one mutation, not giving the reader back, by overflowing the stack). All host tests pass and the sensor fingerprint is unchanged. ipctool and ipcinfo cross-build for arm32 with the NT98566 firmware toolchain.

Tested on a camera

DrSamjames timed this head (6b1e92f) against its base on an XM IVG-N8S (NT98566, IMX415), in full here. I did not run it myself.

base this PR
ipcinfo --short-sensor, sensor not answering, two runs each 27.09 s, 27.03 s 4.15 s, 4.15 s
timeouts on i2c2 / i2c3, per run 13 / 13 2 / 2
NACKs, per run 26 13
detection during a warm boot 27.3 s 4.4 s

The warm boot with this PR detected imx415 and streamed at 25 fps.

Not tested: any other camera. The lab NT98566 cannot run this probe, because it wedges that board's bus. clang-format was not run.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Stop repeated sensor probes on timed-out or duplicate I²C buses

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Leave fallback buses after two consecutive read timeouts to reduce boot delays.
• Skip duplicate i2c-dev adapters while preserving full probes on HAL-nominated and listed buses.
• Add mock sweep coverage; N8S hardware timing remains unverified before merge.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed preferred/fallback probing, adapter selection, and report formatting together determine the end-to-end sensor discovery result consumed by the command/report surfaces.
  • The additional adapter loops are propagation steps within this same bounded integration, not independent capabilities.
  • Concurrent identity/report/monitor discovery calls ultimately consume the same sensor identification behavior and process-global HAL state.
  • They are separate entry points into one bounded sensor-discovery integration, not independent functional scopes.
Sources

src/sensors.c[1491-1503]

static bool get_sensor_id_on_swept_bus(sensor_ctx_t *ctx) {
    sweep_timeouts = 0;
    /* getsensorid() takes no lock. A second thread that finds the reader already
     * borrowed must not save it as the HAL's: it would then call itself. */
    const read_register_t reader = i2c_read_register;
    if (reader != sweep_read_register)
        sweep_bus_read = reader;
    i2c_read_register = sweep_read_register;

    const bool found = get_sensor_id_i2c(ctx);

    i2c_read_register = sweep_bus_read;
    sensor_read_register = i2c_read_register;

src/sensors.c[1340-1351]

static int sweep_read_register(int fd, unsigned char i2c_addr,
                               unsigned int reg_addr, unsigned int reg_width,
                               unsigned int data_width) {
    if (sweep_timeouts >= SWEEP_BUS_TIMEOUTS)
        return -1;

    errno = 0;
    int val = sweep_bus_read(fd, i2c_addr, reg_addr, reg_width, data_width);
    if (val == -1 && errno == ETIMEDOUT)
        sweep_timeouts++;
    else
        sweep_timeouts = 0;
Behavioral complexity 🔴 High 🧩 Concurrent ordering, Coordinated invariants

  • Before: sensor identification used the HAL reader directly without this new temporary global-reader borrowing protocol.
  • After: fallback probing saves the current reader, installs sweep_read_register, calls the existing identification routine, and restores both global reader variables.
  • New correctness condition: overlapping probes must not save another probe's wrapper as the underlying HAL reader, must not restore a stale callback, and must not interleave adapter changes with reads.
  • The source comment explicitly identifies the no-lock condition, while the implementation does not add synchronization around this path.
Sources

src/sensors.c[1491-1503]

static bool get_sensor_id_on_swept_bus(sensor_ctx_t *ctx) {
    sweep_timeouts = 0;
    /* getsensorid() takes no lock. A second thread that finds the reader already
     * borrowed must not save it as the HAL's: it would then call itself. */
    const read_register_t reader = i2c_read_register;
    if (reader != sweep_read_register)
        sweep_bus_read = reader;
    i2c_read_register = sweep_read_register;

    const bool found = get_sensor_id_i2c(ctx);

    i2c_read_register = sweep_bus_read;
    sensor_read_register = i2c_read_register;
Potential damage 🟡 Medium 🩹 Temporary loss

  • If the new consecutive-timeout rule suppresses reads before a sensor answers, or if adapter identity causes a real distinct bus to be treated as already probed, the affected capability is temporarily unavailable or omitted from the report.
  • Recovery is generally a new probe after the bus responds, or code rollback; the source does not show automatic state repair or compensation for a missed report.
  • This is conditional on the transient timeout or incorrect identity premise.
  • Recoverable by a successful later probe, process restart, or reverting the code.
  • No persistent sensor database or external effect requires repair in the inspected path.
Sources

src/sensors.c[1340-1351]

static int sweep_read_register(int fd, unsigned char i2c_addr,
                               unsigned int reg_addr, unsigned int reg_width,
                               unsigned int data_width) {
    if (sweep_timeouts >= SWEEP_BUS_TIMEOUTS)
        return -1;

    errno = 0;
    int val = sweep_bus_read(fd, i2c_addr, reg_addr, reg_width, data_width);
    if (val == -1 && errno == ETIMEDOUT)
        sweep_timeouts++;
    else
        sweep_timeouts = 0;
Assessed commit 6b1e92f
Diagram

graph TD
  P["Sensor detection"] --> H["HAL preferred bus"] --> S["SPI fallback"] --> C["Sweep candidate"] --> D{"Adapter seen?"}
  D -->|No| R["I2C sensor reads"] --> T{"Two consecutive timeouts?"}
  D -->|Yes| C
  T -->|Yes| C
  T -->|No| R
  H -->|Found| O["Sensor found"]
  S -->|Found| O
  R -->|Found| O
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Pass a read callback through sensor probes
  • ➕ Avoids temporarily replacing a process-global function pointer and makes probe state more local.
  • ➖ Requires a broader rewrite across sensor-family probes for this targeted boot-delay fix.

Recommendation: The scoped reader wrapper is the smaller change for the existing probe API, provided its global-state assumptions remain valid. Keep the requested merge hold until timing and sensor detection are verified on an affected N8S.

Files changed (2) +201 / -7

Bug fix (1) +85 / -7
sensors.cBound swept-bus timeouts and deduplicate I²C adapters +85/-7

Bound swept-bus timeouts and deduplicate I²C adapters

• Wraps reads only during fallback I²C probes, stopping further reads on a bus after two consecutive ETIMEDOUT failures and restoring the HAL reader afterward. Records opened i2c-dev device identities to avoid probing the same physical adapter twice; unknown device identities are not deduplicated. The preferred bus and separately listed HAL sensor buses retain their full probes.

src/sensors.c

Tests (1) +116 / -0
sensors_test.cExercise dead, intermittent, duplicate, and unknown sweep buses +116/-0

Exercise dead, intermittent, duplicate, and unknown sweep buses

• Adds mock adapters and read failures to verify timeout cutoffs, full probing after NACKs or intermittent timeouts, duplicate-adapter skipping, and treatment of unknown identities. Also checks reader restoration, unrestricted preferred-bus probing, and discovery of a sensor beyond a dead bus.

src/sensors_test.c

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. New test helper's parameters are misaligned for clang-format ✓ Resolved
Description
The signature of sweep_bus_read_mock wraps onto a continuation line indented 26 spaces, but its
opening parenthesis sits at column 31, so the parameters do not align with the open bracket as the
LLVM-style .clang-format requires. The mismatch is cosmetic and does not affect behaviour, but a
clang-format pass on this file would rewrite the line and produce churn in the test file.

2. Concurrent probes can overflow the stack 🐞 Bug ☼ Reliability
Description
get_sensor_id_on_swept_bus() saves and replaces the process-global reader through sweep_bus_read
without synchronizing concurrent probes. If a second probe enters while the first has installed the
wrapper, it saves that wrapper as its underlying reader, so the next register read calls the wrapper
recursively instead of reaching the hardware.
Code

src/sensors.c[R1493-1494]

+    sweep_bus_read = i2c_read_register;
+    i2c_read_register = sweep_read_register;
Evidence
The new wrapper calls the shared sweep_bus_read pointer. The public getsensorid() path does not
take a lock, while the existing mutex protects only the two identity-formatting entry points;
consequently, overlapping public probes can install the wrapper twice.

src/sensors.c[1337-1348]
src/sensors.c[1491-1500]
src/sensors.c[1656-1659]
src/sensors.c[1780-1812]
src/sensors.h[17-21]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Concurrent swept-bus probes can save the installed wrapper as its own underlying reader and recurse until the stack overflows.
## Fix Focus Areas
- src/sensors.c[1491-1500]
- src/sensors.c[1656-1659]
- src/sensors.c[1713-1725]
- src/sensors.c[1780-1812]
## Recommended Fix
Serialize the full probe across all public sensor-detection entry points, including the complete multi-bus detection path. Use an internal unlocked probe helper where entry points call one another, so the shared reader replacement cannot overlap another probe or deadlock on the same mutex.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@DrSamjames

Copy link
Copy Markdown

Timed on NT98566 + IMX415 (nightly master+8a60044): --short-sensor 27.1 s → 4.15 s, real detection 27.3 s → 4.4 s, i2c2/i2c3 timeouts 13/13 → 2/2. Details: OpenIPC/firmware#1889 (comment)

@openipc-ai

Copy link
Copy Markdown
Contributor Author

On the two Qodo findings, both addressed in 6b1e92f:

  1. Test helper alignment: fixed. I indented it by hand; clang-format was not run.
  2. Concurrent probes overflowing the stack: fixed. The reader is saved only when it is not already the sweep's own, so it can't end up calling itself, and sensors_test has a regression case. I did not add the lock Qodo recommends: it would have to cover every public detection path, which relied on unlocked global state before this PR. What remains is that concurrent sweeps share the timeout count, so one can end another's sweep of a bus early. The description now says so.

Thanks @DrSamjames for the timing. The results are in the description, and the merge hold is lifted.

@openipc-ai
openipc-ai merged commit 083a93f into master Nov 25, 2026
5 checks passed
@openipc-ai
openipc-ai deleted the sweep-leave-dead-bus branch November 25, 2026 12:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants