Skip to content

fix(same53): correct existing inverted-clock software-SPI bulk output before optimization #5044

Closed

Description

@zackees

Context

Native child of #5024, following ESP8266 PR #5021. Discovery baseline: 94dab9c6b. Two investigation rounds completed: (1) inventory and dispatch/consumer tracing; (2) register semantics, variants, interrupt contracts, timing units and focused duplicate search. This is a verified software-path optimization opportunity, not a measured performance result.

Implementation evidence: src/platforms/arm/same53/fastpin_arm_same53.h:27-103.

ClearCore connector stages are active-low. hi uses OUTCLR, lo uses OUTSET, hival clears mask, loval sets it, sport/cport intentionally reversed. Full OUT/fastset remains 32-bit. IO0..3 only map PA00/01/06/07; IO4/5 H-bridge remain excluded.

Existing correctness defect, not merely a future stream risk: at baseline94dab9c6b, the legacy same-port bulk path already constructs clock-high words with data.hival()/loval() | clock.mask() and clock-low words with data.hival()/loval() & ~clock.mask() in generic_software_spi.h:379-382 (writeBytesValueRaw), 425-428 (writeBytes), and 504-507 (writePixels). The three-store writer at 306-320 sends the supposed low/high/low words. At a ClearCore connector these raw clock bits are instead logical HIGH/LOW/HIGH. The final bulk clock is therefore logically HIGH, and the first supposed setup/low write may create a logical rising edge while updating data. When data changes across adjacent bits, the claimed logical high phase can contain the next data transition. Data hival/loval themselves respect inversion; the raw clock OR/AND combination does not. This is a source-level register-to-connector polarity deduction, not a hardware waveform measurement.

With default kTwoWriteStream=false, writeByteStreaming dispatches to that existing three-store writer, and finishByteStream does nothing. Thus leaving the new stream flag false does not establish a correct fallback for SAME53 bulk output. The single-bit/direct writeByte path that calls FastPin hi/lo respects the declared inversion. FAST_SPI_INTERRUPTS_WRITE_PINS can select that atomic/direct path, but ordinary exclusive same-port selection still needs explicit polarity-safe dispatch or word construction. The new two-store stream's low | clock.mask() repeats the same assumption and must also remain disabled until adapted.

Production/API reachability: SAME53 reaches shared fallback SPIOutput -> GenericSoftwareSPIOutput, used by APA102Controller. ClearCoreFastPin pin setup delegates to Teknic core for mode/mux/protection.

The existing shared implementation is src/platforms/shared/spi_bitbang/generic_software_spi.h: kCanStreamSamePort (53-55) requires explicit pin opt-in; useAtomicWrites (60-69) chooses atomic writes for independent ports or FAST_SPI_INTERRUPTS_WRITE_PINS; writeStreamingBit (234-242) combines the previous falling edge with the next data write; finishByteStream (264-268) restores final clock-low. Existing same-port fallback (305-324) emits three stores per bit. Stream callers are writeBytesValueRaw (354-397), writeBytes (403-456), and writePixels (472-557). Absence of opt-in alone was not used as evidence.

Proposal

Fix existing bulk logical-clock correctness before optimizing: use polarity-correct precomputed clock words or explicitly route inverted pins through the correct direct atomic path. Merely adding an atomic trait is insufficient because current useAtomicWrites selects that trait automatically only for different ports; all ClearCore pins here share Group0 OUT. Then implement polarity-aware atomic data selection (logical set->OUTCLR), and only a polarity-aware stream if clock high/low values are derived from pin semantics. Preserve connector setup/protection.

Use the existing ESP8266 policy pattern where semantics match; no global default-true trait. Atomic writes and exclusive full-port streaming have different ownership contracts. Whole-port snapshots must never be selected for interrupt/shared-port mode, and a two-core platform must treat the second core as a concurrent writer.

Acceptance criteria

  • First establish an independent correctness RED using the actual ClearCoreFastPin implementation and production writeBytesValueRaw/writeBytes/writePixels paths with kTwoWriteStream still false: check logical connector low/setup, rising sample, falling edge and final clock-low against inverted register semantics. Include transitions0x55/0xaa across bytes/pixels and FLAG_START_BIT. The old baseline bulk path must fail this correctness test; never use its waveform as the reference oracle. The direct hi/lo path is a polarity control. GREEN must fix this regardless of whether a two-store optimization is enabled.
  • Establish RED before implementation with a focused fixture compiling the actual production pin implementation and selected SPI entrypoint, instrumenting vendor-register writes or tracing actual generated stores. Capture byte/pixel/start-bit waveforms and count GPIO writes. A fake unrelated pin class or a test checking only trait constants does not establish coverage.
  • GREEN must show the targeted improvement: eligible exclusive same-port generic stream emits two stores per payload bit plus one final clock-low per nonempty block; atomic data emits one correct-width data store without a data-dependent GPIO branch or stale whole-port snapshots. If only an independent GPIO bit path applies, assert its direct production register/address/value sequence and absence of OUT RMW. Preserve bit order, exact edge count, final clock-low, modifiers, RGB order, brightness/dithering, start bits, empty blocks and transaction ordering.
  • Mutation-sensitive gate: restore the old production writer/policy (or disable the new platform opt-in while leaving the test intact) and demonstrate the same focused gate fails. A waveform-only test that passes both old and new paths is insufficient for the optimization claim. Keep correctness and optimization assertions separate.
  • Cover 0x00, 0xff, 0x55, 0xaa, every one-hot byte and transitions across adjacent bytes, pixels and frame boundaries. Inject unrelated-pin updates between writes; atomic/shared mode must preserve them and must never enter full-port streaming. Exercise same-port/different-port cases only where hardware exposes them.
  • Audit units before reusing delay code: for these ARM families fastspi.h:85-90 encodes DATA_RATE_MHZ/KHZ as CPU-cycles-per-bit, not Hz. Cover slow rates, divider <=10, odd dividers and the 35ns minimum (bitbangPhaseDelay); prove no unsigned underflow and preserve requested high/low timing. Do not transplant ESP8266 minimum-write-cycle assumptions to another bus/CPU.
  • Compile the real board/configuration matrix below using repository wrappers and supported fbuild toolchains; preserve native peripheral, forced-software-pin and interrupt-safe configurations. A host fixture does not establish vendor-header or real-core compilation.
  • Removing redundant GPIO stores while preserving all existing conservative padding requires production-connected traces, real target compilation and generated-code/store-count evidence. Changing target timing assumptions (crediting GPIO latency or skipping existing padding) additionally requires physical logic-analyzer/loopback evidence at the connector/LED input for requested rates, high/low widths and setup/hold under declared interrupt/core conditions. Any claim of physical speed or phase accuracy requires measurements with board/core/compiler/rate/payload recorded. Missing hardware is explicitly unmeasured and cannot establish electrical validation; hardware-dependent timing changes remain open until measured.

Board/configuration matrix

Teknic ClearCore SAME53 with Teknic core1.7.4 or pinned current supported core. Test connector IO0/IO1 and IO2/IO3 with safe LED-compatible electrical interface and actual connector waveform; MCU pad trace alone does not prove connector polarity/timing.

Decisions

  • Scope is the implementation above; shared variants belong to this one child with the explicit matrix rather than duplicate issues per board.
  • Priority P2: reduce unnecessary GPIO work without weakening electrical or concurrency correctness.
  • Hardware peripheral transfers, DMA/PIO engines and clockless protocol encoding are excluded even when filenames mention SPI.
  • Existing inverted same-port bulk fallback is not a known-correct path. Correctness takes precedence; route to proven direct operations or derive polarity-aware words while leaving any unverified timing optimization disabled.
  • No source changes, builds, hardware measurements or claimed speedup were made during discovery.

Next steps

Shared prerequisite gates: #5031 owns the production-connected tracing/inventory/mutation infrastructure; #5032 owns shared default-delay call overhead. This child owns the distinct platform register/polarity/width/dispatch contract and should reuse those gates.

  1. Confirm real vendor headers/register contracts and annotate eligible variants/pins.
  2. Add the production-connected RED gate and record its failure.
  3. Implement the smallest platform policy/writer change; run GREEN and old-path mutation.
  4. Run board matrix and hardware timing checks, then review before opt-in.

Open questions

The board/device availability, exact GPIO bus write latency and supported compiler code generation require implementation-time evidence. Any implementation-specific blockers called out above remain required work. This discovery does not certify hardware timing.

Duplicate search used issue metadata for all-state "software SPI", "bitbang", and "two-write"; no existing platform-specific optimization child was found. Broader platform bring-up and hardware-SPI issues do not replace this focused work.

Activity

  1. added
    sanitized
    on Nov 5, 2026
  2. added
    sanitized
    and removed
    sanitized
    on Nov 5, 2026
  3. changed the title [-]perf(same53): add polarity-aware ClearCore software-SPI writes[/-] [+]fix(same53): correct existing inverted-clock software-SPI bulk output before optimization[/+] on Nov 5, 2026
  4. added
    sanitized
    and removed
    sanitized
    on Nov 5, 2026
  5. moved this from Triage to Done in FastLED Trackeron Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    sanitized

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions