nut icon indicating copy to clipboard operation
nut copied to clipboard

apc_modbus over USB on Smart-UPS X1500: measured device behavior (reply conveyor, offset classes, timing phases) and what a driver needs to survive it

Open d01 opened this issue 3 months ago • 2 comments

This is a measurement write-up, not a single bug report. Over a week of instrumented testing (usbmon captures from verified-clean device states, day-long soaks, an instrumented driver) getting apc_modbus reliable on an APC Smart-UPS X1500 (051d:0003, firmware "UPS 16.0") over USB, the device turned out to have behavior that quietly breaks most obvious driver designs — including several I tried first. Filing it in one place so the next person doesn't have to rediscover it, and because a few of the findings bear on driver defaults. Related threads: networkupstools/libmodbus#12 (transport fixes), #3571 (retry-loop fixes), #2609 (the desync discussion; my measurements there were corrected in a follow-up comment).

Everything below is one unit of one model; APC application notes AN176 and AN178 are cited where the behavior matches or contradicts them.

1. The reply stream is a conveyor; one missed timeout is permanent

A Modbus RTU reply carries no echo of its request, and the USB transport has no meaningful CRC, so nothing ties a reply to its request except arrival order. On this device a reply that misses the response timeout does not age off: it stays queued, and every request that consumes a stale reply queues its own reply behind it. The stream is then permanently offset by one — the client cannot drain it, ever; only the device's occasional spontaneous double-push (rare) or a lucky USB reset (see §4) removes one.

The failure is silent when reads share a shape: a stale reply of the right length is accepted as current data. Measured corruption from one such state: the firmware revision string served as ups.model, ups.serial and ups.firmware, 14.5 kW as ups.realpower on a 1500 VA unit, input.voltage 63 V — all while ups.status read a healthy OL.

Offsets also stack. With a standing offset and a timeout the device's current mode cannot meet, each further miss adds a layer; I have run at a stable depth of 4 (every read consumes four stales before its own reply). At depth ≥ the retry budget, reads fail outright. And there is a resonance worth knowing: at depth N, a read's Nth+1 attempt consumes the reply to its own first attempt — same registers, same shape — so shape-based validation structurally cannot reject it. Benign here (the data is ~100 ms old and correct) but it means "validate by size/shape" has a blind spot no driver can close.

2. The device has timing modes, and they persist

Three phases after a USB link reset (host reboot; the UPS itself never restarts):

  • deaf — requests accepted and queued, nothing delivered. 8–24 s after a link reset at boot; up to ~2.5 min after a software (libusb_reset_device) reset — and sometimes absent entirely.
  • slow — every request answered, in order, quantized to a ~1 Hz internal tick. Usually 1–3 s replies, with withholding stalls of 10–14 s. I have also observed a deep mode with a metronomic 6.93 s (7-tick) base and excursions to 53 s — after the host had been off for 8.75 h, i.e. modes persist across long unpolled idle.
  • fast — normal operation, ~12 ms replies, but with a real tail: ~10 % of healthy replies run 0.5–2 s (measured p90 919 ms over steady state).

Consequences for defaults: a response timeout that is safe in fast mode (2 s) is unmeetable in slow mode, and every miss mints a permanent offset (§1). A timeout of 500 ms or less — tempting from AN176's 250 ms figure — would turn the healthy tail alone into thousands of retry storms per day. On this hardware, 2 s + retries is the working floor, and slow phases need a separate long-timeout connect grace rather than a bigger steady-state timeout (waiting cannot help a withholding device; it just delays detection).

3. Notifications: the healthy baseline is not silence, and it breaks naive receive timeouts

The device broadcasts unsolicited HID input reports (IDs 0x07, 0x0c, 0x0d, 0x12, 0x13). Healthy baseline, measured on a verified-clean unit: each ID every ~6–8 s on a staggered lattice — note AN178 §3.2.2 says change-driven and ≥15 s apart, so even healthy this firmware is ~2× out of spec. Degraded states run a sustained 1 Hz per-ID storm (15× out of spec), which is a useful passive health signature.

The dangerous interaction: a receive loop that restarts its timeout on every non-Modbus report never times out at all against a 1 Hz notification stream — the configured timeout only fires on total device muteness, and every stall measurement is conflated. libmodbus's rtu_usb had exactly this; fixed in networkupstools/libmodbus#12 (a832970, one deadline across skipped reports).

4. The USB reset: not fatal, not very useful either

Corrections and measurements (details in the #2609 follow-up):

  • A single reset is survivable: typically up to 2.5 min deaf, sometimes no deaf window at all. The unit absorbed dozens of well-spaced resets across the week.
  • Resets in close succession wedge it — three within four minutes, two of them 26 s apart, left both interrupt endpoints dead until the cable was physically reseated. SIGKILLing the driver mid-exchange does the same. (My original "the reset is fatal" report was a restart loop clustering resets in disguise.)
  • As desync recovery, the reset mostly does not work here: across 14 resets issued against a known standing offset, 2 shed it. The pattern fits the reset discarding only a reply already staged in the endpoint buffer, while replies the firmware still holds internally — the common case — survive. My driver build grades every reset by sampling the 20 reads after it, and retires the mechanism after 4 consecutive failures; on this unit it always retires. Other hardware may behave differently (the #11 rationale presumably came from somewhere), but "reset to resync" should not be assumed universal.

5. What actually survives this device

For the record, the layered design that has run clean here — each layer added after the previous alone failed:

  1. Reads only at firmware-accepted register block boundaries (AN176 §3.1.1: the firmware matches (start,count) against its own table and refuses sub-ranges).
  2. Retries that also retry wrong-reply errors (EMBBADSLAVE/EMBBADCRC/EMBBADDATA), with a transport flush between attempts, and a retry budget above the plausible offset depth (#3414 + #3571 + a flush-before-retry patch).
  3. Distinct reply shapes for adjacent reads wherever possible, so a stale reply is shape-rejected instead of silently accepted — this is the load-bearing layer; §1's resonance is its one blind spot.
  4. A pre-send drain until a full interframe interval of silence (AN176 §4.2.2 gives 35 ms; I use 45 ms), apcupsd's discipline — it destroys stragglers before they can become queued stales (networkupstools/libmodbus#12, 63583ff).
  5. A connect-time grace (long first-read timeout riding out the deaf window, long grace timeout through the slow phase, released only after a run of prompt completions) instead of any fixed margin — fixed margins lost this race twice.
  6. Offset detection by behind-ratio over a sliding window of completed reads, with the winning-attempt mode as a depth gauge, reported at NOTICE on change — cheap, and it keeps the journal honest with per-attempt debug logging off.

All of it is running as a patch series on 2.8.4 here; happy to share any of it, split PRs, or provide usbmon captures if there's interest.

Suggestions distilled

  • Never let a driver be SIGKILLed mid-exchange on this hardware, and never issue USB resets in close succession (#3571 handles the first).
  • apc_modbus defaults for this family: response timeout not below 2 s; retries ≥ 3 with flush between attempts.
  • Treat "reset recovers a desynced device" as per-device, not a given; if used automatically, grade the result and stop when it never works.
  • The AN176 register-block rule and the notification-vs-timeout interaction (§3) are worth a note in the apc_modbus docs — both produce failures that look nothing like their cause.

Developed with assistance from Claude (Anthropic); all findings verified on real hardware.

d01 avatar Aug 16 '26 19:08 d01

Following up on the report above with a correction and a substantial new finding, from another week of instrumented operation on the same SMX1500 (FW "UPS 16.0").

Correction: "offset past retries" is really a firmware task hang

The issue text describes a state where, after a host reboot against an un-shed offset, every inventory read fails all modbus_retries attempts and the driver cannot start — which I attributed to queue depth exceeding the retry count. usbmon now shows that diagnosis was wrong. In that state the device's Modbus engine is not deep — it is mute: zero Modbus replies and zero interrupt notifications over minutes of capture, while USB enumeration stays perfectly normal. lsusb, descriptors, and string reads all look healthy; nothing at the USB level distinguishes it. I've taken to calling it the wedge-mute state.

The journal signature is distinctive and worth documenting for other apc_modbus USB users, because it masquerades as a data problem while being invisible to USB-level checks:

_apc_modbus_read_registers_chunk: Read of 516:532 failed after 8 attempt(s): Connection timed out
Can't read inventory information from the UPS

repeated by systemd's restart loop indefinitely — each start burning modbus_retries × <first-read timeout> in pure silence. One boot here accumulated 43 consecutive failed starts before anyone noticed, because the failure produces no distinctive message.

Three further characterizations, all bus-verified against the wedged unit:

  • The HID front-end stays alive: SET_REPORT to the Modbus report IDs is accepted, GET_REPORT returns empty reports. The hang is behind the HID layer, in whatever firmware task services the vendor-page tunnel.
  • The standard Power Device / Battery System HID stack keeps answering perfectly — GET_REPORT(Feature) returned live, correct battery data (charge, runtime, battery voltage, AC flags) the whole time the Modbus side was mute. The two interfaces are evidently separate firmware tasks, and only the Modbus one wedges.
  • No software path recovers it. Tried and measured: USB device resets (single and clustered), a 50 s host-side port disable with full fresh re-enumeration, endpoint-halt clears, slave-address scan 1–223, passive and broadcast drains, and multi-day power-off of the host (the state survives it — the UPS keeps its firmware running). The only recovery, in every occurrence, is physically reseating the USB cable.

Trigger: no crash required

The earlier report guessed driver crashes / SIGKILL. The journals of the latest occurrence rule that out: the driver exited cleanly on SIGTERM ("Deactivated successfully", no kill escalation) during a normal host shutdown, while carrying a long-standing pinned reply-stream offset (depth 4–5 for several days, the "own-reply re-acceptance" mode described above). At the next boot the device was already mute. So the trigger is some combination of link death and standing dirty queue state — a clean driver stop is enough.

Notably, I could not reproduce the wedge on demand from fresh dirt: a deliberate campaign (abandoned in-flight replies at depths 1–5, SIGKILL mid-session ×4, 50 s link deaths, and a 3-reset cluster — all against freshly-created queue states) produced zero wedges. Both real occurrences sat on a days-old pinned offset, which I now suspect is a precondition. Fresh dirt appears robust; aged state is another animal.

What the manufacturer's software does (and why it never sees this)

To understand how APC's own tooling survives, I ran PowerChute Serial Shutdown (the current PCBE replacement, which supports this model over USB) in a VM with the UPS passed through, capturing usbmon on the host — first against the wedged unit, then against a healthy one.

Two findings that seem directly relevant to this issue:

  1. PCSS never speaks Modbus RTU over USB to this device. It uses the same vendor HID reports (the usages AN176 labels ModbusRTURx/Tx — which APC's own HID tooling names APCMicroLinkMasterRx/Tx), but the framing is MicroLink: single-byte polls from the host, then the device streaming its data table in sequence-numbered, CRC-terminated frames, each acknowledged by a single-byte ACK, continuously. No addressed request/response at all in steady state — nothing to misattribute, no reply queue to go stale, nothing left dangling at link death. The Modbus-over-USB tunnel that apc_modbus (and apcupsd's modbus-usb driver) relies on appears to be exercised by nothing in APC's own USB stack — consistent with the rough edges catalogued in this issue.

  2. PCSS cannot recover the wedge either. Against the wedged unit it polled at 400 ms for 25 minutes (with Windows applying USB resets along the way) and got total silence, forever, "UPS Communication Lost". Recovery required the same physical reseat. So this is not a client-discipline problem — once wedged, the tunnel is gone for everyone, manufacturer included.

One more observation: link deaths can shed queued replies

During the reproduction campaign, host-side port-disable cycles and a clustered device reset repeatedly cleared freshly-queued stale replies — in the best case taking a deliberately dirtied stream back to fully in-step, with prompt replies and no deaf window, within ~20 s. Single resets against the aged pinned offset were 0-for-17 in earlier weeks, so this may not transfer — but a reset cluster / port-power approach was never tried against the aged state, and I'll test it at the next natural occurrence. If it holds, the pinned-offset class may have a software heal after all.

Mitigation deployed here (offering upstream if there's interest)

Since the wedge presents as an endless, silent crash-loop, I've wired a systemd OnFailure= diagnosis onto the driver unit: on a start failure matching the all-attempts-timed-out signature it stops the unit, probes the tunnel (one addressed read + a passive listen for the notification lattice), probes the legacy HID path via GET_REPORT, and then either (a) declares the wedge loudly — "no software recovery exists, reseat the cable" — and leaves the unit stopped rather than grinding the device, or (b) resumes the restart policy for the recoverable classes. The legacy-HID probe is what makes the diagnosis trustworthy: it cleanly separates "tunnel wedged" from "UPS dead/unplugged" on a device where lsusb can't tell you anything.

Happy to contribute any of this in whatever form is useful.

d01 avatar Aug 24 '26 02:08 d01

A closing data point from this SMX1500 (FW "UPS 16.0", 051d:0003), three more weeks on from the wedge-mute write-up above. Short version: I'm parking apc_modbus over USB on this unit and moving my testing to apcmicrolink (#3579/#3591). The details, in case they help whoever triages this for 2.8.5:

The wedge does not need a trigger. Earlier I believed wedge-mute needed a long-lived misaligned reply stream plus a link death (driver stop, host power-off, USB reset). On 09-13 it happened with neither: a clean 2-second start on a freshly shed stream, replies slipped to "one behind"-class misalignment about ten minutes in, and the tunnel went fully mute within the hour — host up, no USB reset anywhere in the kernel log, no suspend, no writes. Six wedges total now; each needed a physical reseat of the USB cable, and nothing else (single or clustered USBDEVFS_RESET, port power-cycle, days of host-off) has ever cleared one.

Nothing done at driver stop predicts the next start. My local build grades the reply stream at clean stop and, if it is misaligned, sheds the offset with a short cluster of USB resets and verifies the stream is back in step before closing. Over eleven such stops followed by a host power-off: 8 verified "in step" → 6 normal starts, 2 wedges; 3 that failed to shed → 3 normal starts. The shed works, and it is irrelevant to the wedge.

The misalignment comes back on its own, quickly. After a reseat the stream ran clean for roughly a day (two driver stops graded 0 of the last 100 reads misaligned). From then on every boot fell back to replies arriving 3–5 requests late within 10–20 minutes of the driver going live, with a 2 s poll interval, nothing else talking to the device, and the driver never abandoning a request it could wait out. The driver stays correct under this (a stale reply is rejected on shape and retried) but the poll cycle stretches past upsd's default MAXAGE, and I could find no software-side variable — retries, timeouts, poll rate, resets on or off — that prevents it or the wedge that follows it around.

Practical note for anyone hitting this: usbhid-ups still works on a wedged unit. The vendor-page tunnel and the standard Power Device HID stack are separate inside the firmware. With the tunnel completely mute, usbhid-ups -s test -x port=auto -x vendorid=051d -d 1 attached in 0.13 s and returned a full, correct variable set (status, charge, runtime, battery voltage, firmware string). So a wedged apc_modbus setup can be given shutdown protection again without touching the cable, by switching driver — at the cost of the richer Modbus data.

A possible cause, from the MicroLink side. In #3587 @nmbro reports that on their unit the same unplug-only lock-up is what happens "if you query the tunnel too many times unauthenticated" — MicroLink sessions authenticate with a small handshake, and PowerChute does so on every connect. Modbus RTU has no such step, so over this tunnel apc_modbus is permanently an unauthenticated client. That is speculation about firmware nobody here can read, but it fits every property of the wedge I measured (no host-side trigger, standard HID reports unaffected, survives days of host power-off, USB resets useless, cleared only by pulling the cable), and if it is right then no amount of care in the Modbus driver can avoid it.

Why MicroLink next. On this port APC's own PowerChute Serial Shutdown speaks MicroLink, never Modbus RTU (usbmon captures, described above), and it runs against this same unit without wedging it. Both protocols ride the same two HID reports, but MicroLink frames are sequence-numbered and individually ACKed, so there is no reply queue to fall out of step with. If the wedge grows out of misaligned or abandoned Modbus exchanges, that path may simply never reach it; if it doesn't, that is worth knowing too. I'll report what apcmicrolink from master does on FW UPS 16.0 over on #3587.

I'm happy to keep answering questions here, re-run anything on this unit on request, or test a patch. The instrumented driver changes (stream-state reporting at NOTICE, the stop-time grading) are available if any of it is useful upstream, but I would not propose the reset-cluster shed for merging on this evidence.

d01 avatar Sep 17 '26 23:09 d01