Skip to content

examples: pru_i2c: fix PRU1/dual-core IEP use, read ACK and SDA control (for #137) - #171

Closed
pratheesh wants to merge 15 commits into
TexasInstruments:mainfrom
pratheesh:fix/pr137-pru-i2c-review
Closed

pratheesh wants to merge 15 commits into
TexasInstruments:mainfrom
pratheesh:fix/pr137-pru-i2c-review

Conversation

@pratheesh

@pratheesh pratheesh commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Status (refreshed after #137 was closed)


Fixes for #137, originally targeted at its branch (a0502729_PRU_I2C).

I ran the PRU0 and PRU1 firmware ELFs on pru-simulator against a modelled I2C bus with an EEPROM-style target. The pass/fail judgement comes from a bus monitor that decodes the wire levels, not from the firmware's response codes. The PR head (d3795004) failed every scenario. With these changes all scenarios pass. Each fix was also reverted on its own to confirm the scenario guarding it fails again (details below).

What was wrong, and what changed

Per-core resources. The IEP and the scratchpad banks are shared by PRU0 and PRU1.

# Problem Effect in simulation Fix
1 The makefile build defines neither PRU0 nor PRU1 (DFLAGS :=). icss_constant_defines.inc then treats the core as PRU1, so ICSS_DMEM0_CONST becomes C25. No IEP compare is enabled either. The committed pru0/pru1_load_bin.h are this build: both arrays are identical apart from the array name. PRU0 reads its frequency word from the other DMEM, gets 0 and goes to ERROR_LOOP. SETUP never completes and SCL never toggles. DFLAGS := -DPRU0/-DPRU1 -DSLICEn -DSOC_AM261X, matching the projectspecs. .emsg if neither is defined.
2 I2C_WAIT_FOR_IEP_CMP polls the PRU0 status bit (qodo #5). PRU1 hangs at SETUP. The CMP register, status bit and enable bit are selected once per core (I2C_IEP_CMP_*).
3 I2C_SETUP_IEP_COUNTER programs CMP0 on both cores (qodo #6). Same as #2. Same as #2.
4 The first compare value is a hardcoded 0x9C3 (the DEBUG_CODE guard is commented out) (qodo #7). A second core joining a running counter gets a compare value in the past. First compare = live IEP count + one tick.
5 CMP_CFG is written with only this core's enable bit set. Starting PRU1 disables PRU0's compare, so PRU0 stops. Read-modify-write.
6 I2C_IEP_INTC_CLEAR_EVENT writes the whole CMP_STATUS value back. The register is write-1-to-clear, so this also clears the other core's pending event. When the two cores' ticks coincide, one core loses its event and hangs (2 of 32 start phases). Write only this core's bit.
7 Both cores XOUT/XIN their context to scratchpad bank 10. With both cores running, they overwrite each other's state and both stop. PRU0 uses bank 10, PRU1 uses bank 11.
8 ERROR_LOOP stops the IEP counter. Kills the other core's instance. The counter is left running.

I2C protocol

# Problem Effect in simulation Fix
9 rx_data_ack_begin drives SDA high, so the master NACKs every byte it reads. A 4-byte read returns 5a ff ff ff. Wire trace: A1A 5AN FFN FFN FFN. Drive SDA low.
10 SET_SDA_PIN_INPUT/OUTPUT_DIRECTION write 0x50D00818 with a hardcoded bit 9. That address is ICSSM1_PRU0_GPIO_OUT_CTRL, but these projects run on ICSSM0. SDA is never released. The master reads back its own drive as the ACK, so a write to an absent address reports COMMAND_SUCCESS (START A2A 00A STOP). Use this core's register (ICSSM0_PRU0/1_GPIO_OUT_CTRL at 0x50D00810/814, or ICSSM1 with -DICSSM1), with the bit taken from the configured SDA pin.
11 SDA is released one tick after SCL falls on the 8th bit, and is driven again right after a read's address ACK. The push-pull master drives SDA high while the target drives ACK or read data. That lasts up to a quarter bit (499 cycles at 400 kHz, 4000 at 100 kHz). Release SDA on the 8th falling edge. Keep it released after the address ACK of a read.
12 IEP_CMP_INCREMENT_VAL_400KHZ = 0x270 (624) and _100KHZ = 0x9C3 (2499) are not multiples of the IEP DEFAULT_INC (5). Under an exact-match compare model, 400 kHz and 100 kHz never tick. 0x271 (625) and 0x9C4 (2500). These are exact under either compare model (see "Limits" below).

Commands and bus recovery (added after the first push)

# Problem Effect in simulation Fix
13 The SMBus stub checks only advance to the next check from some stubs, so dispatch stops at ICSS_SMBUS_QUICK_CHECK for every command after TX. READ_SCL, RESET_SLAVE and LOOPBACK are unreachable. Any SMBus or unknown command leaves the firmware stuck in that check until reset. One range check: SMBus commands (not implemented) get INVALID_COMMAND, and every other command continues to READ_SCL / RESET_SLAVE / LOOPBACK, then INVALID_COMMAND.
14 RESET_SLAVE counts falling edges and ends with SCL low. It also keeps driving SDA high. 8 SCL pulses, bus left low, and the master fights the stuck target it is meant to free. Release SDA, give 9 full pulses, end with SCL high.
15 SDA is driven push-pull even while the bus is idle. An idle master fights a target that holds SDA low (1,100+ cycles before recovery even starts). Release SDA when the bus goes idle (after setup, STOP and RESET), and take it back at the start of each transfer.

Housekeeping

Not changed:

Verification

Builds: clpru 2.3.3. make -C examples/pru_i2c pru DEVICE=am261x BUILD_MCUPLUS=y gives 0 warnings. A build with no core define now fails with a clear message. CI was dispatched on the fork (links below).

Simulation: pru-simulator core and memory model, plus an AM261x ICSSM layer:

  • C26 = IEP.
  • IEP DEFAULT_INC = 5 at reset.
  • Writing 0xFFFFFFFF to IEP_COUNT clears it.
  • MSS_CTRL ICSSMx_PRUy_GPIO_OUT_CTRL decides who drives SDA.

The I2C target can only pull low. The bus monitor flags any cycle where the master drives SDA high while the target pulls it low.

scenario PR head this PR
PRU0 400 kHz: write 4 bytes, set pointer, read 4 back read NACKs every byte PASS, exact wire trace
PRU1 400 kHz, same hang at SETUP PASS
write to an absent address reports success ADDRESS_ACKNOWLDEGE_FAILED, START A2N
100 kHz / 1 MHz (781 kHz) read fails PASS, 2000 / 256 PRU cycles per SCL period
PRU0 and PRU1 on one IEP, PRU1 started later PRU1 hangs and stops PRU0 PASS
same, PRU1 started at 32 phases of PRU0's tick fail PASS 32/32
SMBus stubs and an undefined command hang INVALID_COMMAND; the next command still works
READ_SCL / LOOPBACK hang SCL_VALUE_HIGH / RX buffer equals TX buffer, no bus activity
RESET_SLAVE with a target holding SDA low (after a completed and after a NACKed transfer) hang 9 pulses, target released, bus idle, no contention
R5F example config (PRU1, GPIO18/19, IEP 250 MHz / core 225 MHz, increment 785) fail PASS, 398 kHz

Remaining overlap: at most 30 PRU cycles (150 ns) per ACK. The target model drives ACK on the same cycle SCL falls, and the master needs that long to write GPIO_OUT_CTRL. That is the floor for a push-pull master.

Ablation: reverting each fix one at a time re-fails its scenario, 12 of 12. The 9-pulse count is checked by the scenario but not ablated separately.

Limits of this evidence:

  • This is a model, not silicon.
  • SPRUJB6B does not say whether an IEP compare is an exact match or a crossing match. All results hold under both models.
  • The MSS_CTRL access latency is an estimate.
  • There are no pad electricals, rise times or clock stretching.

This needs a run on an AM261x-LP before it is merged.

Questions for @achala-ti

  • Were you testing on ICSSM1 pins? 0x50D00818 would be correct there; build with -DICSSM1. The projectspecs say ICSS_M0, so ICSSM0 is the default here.
  • The SMBus commands (ICSS_SMBUS_*) now get INVALID_COMMAND. The supporting states (CMD_CODE_*, *_BURST) are still there but unreachable: there is no repeated START, the command-code ACK does not release SDA, and the block count is not bounds-checked. Do you want to implement SMBus, or drop those states until it is implemented?

Related: #172 (R5F example, open-drain bus, SMBus; includes this PR). #173 resolved the earlier examples/makefile conflict on #137's branch.

🤖 Generated with Claude Code

achala-ti and others added 5 commits June 10, 2026 14:59
  - Add I2C firmware
  - Create PRU0/PRU1 build projects for ICSS_M0
  - Configure makefiles and projectspec for open-pru structure

Signed-off-by: Achala Ram <a-ram@ti.com>
The am261x "Verify all makefiles were built" CI step failed with
"makefile never built" for the two pru_i2c PRU firmware makefiles,
because nothing in the top-level make recursed into them.

- Add examples/pru_i2c/makefile aggregator (modeled on examples/empty),
  scoped to am261x with an am261x target that builds the pru0/pru1
  ti-pru-cgt firmware. Non-am261x devices hit the SUPPORTED_PROCESSORS
  prebuild check and skip cleanly, so other device builds are unaffected.
- Add pru_i2c to examples/makefile SUBDIRS so the top-level make recurses
  into it.

Verified with GNU Make dry-runs: am261x recurses into both firmware
leaf makefiles (each producing a .out, satisfying the verify step);
am263x prints "does not have a build option" and builds nothing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…control

Found by running the firmware ELFs on TI pru-simulator against an I2C
target model (see the PR description for the harness and results).

Per-core resources (both PRUs share the IEP and the scratchpad banks):
- The makefile build defined neither PRU0 nor PRU1 (DFLAGS was empty),
  so icss_constant_defines.inc treated both cores as PRU1: the firmware
  read its frequency word from the other core's DMEM, got 0 and went to
  ERROR_LOOP. Neither IEP compare was enabled either. The committed
  pru0/pru1_load_bin.h were built this way and are identical apart from
  the array name. Add -DPRU0/-DPRU1 (as the projectspecs already do) and
  fail the build with .emsg if neither is defined.
- I2C_WAIT_FOR_IEP_CMP polled the PRU0 status bit and
  I2C_SETUP_IEP_COUNTER programmed CMP0 on both cores, so PRU1 never saw
  a tick. Select CMP register, status bit and enable bit once per core.
- I2C_SETUP_IEP_COUNTER wrote CMP_CFG with only its own enable bit set,
  disabling the other core's compare. Read-modify-write it instead.
- The first compare value was a hardcoded 0x9C3 (debug guard commented
  out). Use the live IEP count + one tick, so a core can join a counter
  the other core already started.
- I2C_IEP_INTC_CLEAR_EVENT wrote back the whole CMP_STATUS value, which
  (write-1-to-clear) also clears the other core's pending event. Clear
  only this core's bit.
- Both cores saved their context to scratchpad bank 10. Use bank 10 for
  PRU0 and bank 11 for PRU1.
- ERROR_LOOP stopped the shared IEP counter. Leave it running.

I2C protocol:
- Read: the master drove SDA high in the ACK slot after every byte
  (rx_data_ack_begin used SET_SDA_PIN_HIGH), so it NACKed each byte and
  multi-byte reads returned 0xFF after the first byte. Drive it low.
- SET_SDA_PIN_INPUT/OUTPUT_DIRECTION wrote 0x50D00818
  (ICSSM1_PRU0_GPIO_OUT_CTRL) with a hardcoded bit 9. These projects run
  on ICSSM0, so SDA was never released: ACKs were read back from the
  master's own drive (a write to an absent address reported success).
  Use this core's ICSSM0 register (ICSSM1 with -DICSSM1) and the
  configured SDA pin.
- Release SDA on the SCL falling edge after the 8th bit instead of one
  tick later, and keep it released after the address ACK of a read, so
  the push-pull master does not drive SDA high while the target drives
  ACK or read data.

Housekeeping: file header names, register usage map, wait macro docs,
and a missing newline/indent on the final .endif (assembler warning
W0004 "Open block(s) at EOF").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pratheesh Gangadhar <pratheesh.gangadhar@gmail.com>
The IEP counts in steps of DEFAULT_INC = 5. 0x270 (624) and 0x9C3 (2499)
are not multiples of 5, so a compare that fires only when the counter
equals the compare value is never hit at 400 kHz or 100 kHz. Use 0x271
(625, i.e. the 125 cycles the comment already describes) and 0x9C4
(2500). 1 MHz (0x140 = 320) was already a multiple of 5.

SPRUJB6B does not say whether an IEP compare is an equality match or a
crossing match. With these values the tick is exact under either.

Also fix the file header name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pratheesh Gangadhar <pratheesh.gangadhar@gmail.com>
Rebuilt with the makefile flow (make -C examples/pru_i2c pru
DEVICE=am261x BUILD_MCUPLUS=y), which now passes -DPRU0 / -DPRU1. The
previous arrays were built with neither define and were identical for
both cores apart from the array name. These arrays are byte-identical to
the ELFs exercised on pru-simulator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pratheesh Gangadhar <pratheesh.gangadhar@gmail.com>
@qodo-code-review

qodo-code-review Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

examples: pru_i2c: fix PRU1/dual-core IEP use, read ACK and SDA control

🐞 Bug fix ✨ Enhancement ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Fixes PRU0/PRU1 firmware so both cores share the IEP and scratchpad without interfering: per-core
 compare register, status/enable bits, read-modify-write CMP_CFG, write-1-to-clear only own event,
 separate context banks (10 and 11), and the counter left running on error.
• Build now defines PRU0 or PRU1 and SLICEn (DFLAGS and projectspec), so the DMEM constants and
 compare selection resolve for the right core.
• Adds the am261x aggregator makefile and wires pru_i2c into examples/makefile SUBDIRS so the CI
 "makefile never built" check passes.
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 assembly, interface header, per-core build projects, and generated images jointly implement one host-command-to-I2C-transfer behavior.
  • PRU0 and PRU1 are execution components of that same integration rather than independent functional scopes; the shared DMEM command/response layout and interrupt signaling connect them to the same host-visible behavior.
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • Before, the repository had no AM261x PRU I2C firmware behavior.
  • After, two PRU images share IEP timing while independently scheduling a multi-state I2C protocol through DMEM, GPIO direction changes, compare events, acknowledgements, interrupts, and recovery commands.
  • New correctness conditions include ordering PRU startup around non-atomic shared IEP initialization, keeping per-core compare/status/context resources distinct, preserving SDA ownership across ACK and read phases, and maintaining state-machine transitions across 7-bit/10-bit addressing, burst/non-burst transfers, stop/no-stop behavior, and error recovery.
  • These are newly interacting states and coordinated shared-resource invariants, not merely use of an existing helper.
Potential damage 🟡 Medium 🩹 Temporary loss

  • The supported race can leave a PRU scheduler waiting forever or disturb shared timing, preventing I2C transactions.
  • The source supports capability unavailability, not persistent data corruption or a broader system outage.
  • Recovery requires resetting/restarting the affected PRU firmware and may require bus recovery if the stall occurs while driving a transaction; code rollback alone does not repair an already running core.
  • Temporary loss is generally recoverable by resetting/reloading the PRU firmware and, if needed, issuing the implemented slave-reset/bus-recovery command.
  • The external host's ability to perform that recovery is not present in this repository.
Assessed commit e8f3a04
Diagram

graph TD
  A["examples/makefile"] --> B["pru_i2c/makefile"] --> C["PRU0 firmware makefile"]
  B --> D["PRU1 firmware makefile"]
  C --> E["pru_i2c_main.asm"]
  D --> E
  E --> F["IEP compare CMP0 / CMP1"]
  E --> G["Scratchpad bank 10 / 11"]
  E --> H(("I2C bus SCL/SDA"))
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Separate PRU0 and PRU1 source files
  • ➕ Each core's code is simpler to read on its own
  • ➕ Avoids preprocessor-conditional branches in the asm
  • ➖ Two copies of the I2C state machine that will drift apart
  • ➖ Every future protocol fix must be applied twice
2. Give the two cores a shared IEP timer and a single arbitration scheme
  • ➕ Removes the need for per-core compare registers
  • ➕ Avoids the write-1-to-clear race
  • ➖ Larger redesign than this PR's scope
  • ➖ Would need changes to the IEP setup on both cores

Recommendation: Keep the single shared source with per-core defines, which the PR already does. Each PRU core runs the same firmware, so one file with -DPRU0 or -DPRU1 avoids duplicated logic. The per-core fixes are needed under either layout. Before merge, confirm the committed pru0/pru1_load_bin.h are regenerated from this source, since the PR says the committed ones came from the earlier broken build.

Files changed (15) +5057 / -1

Enhancement (2) +270 / -0
pru_i2c_firmware_version.hFirmware version constants header +54/-0

Firmware version constants header

• Defines the firmware version bit fields and I2C_FIRMWARE_VERSION, currently 0.0.0 release. It is included by the main firmware.

examples/pru_i2c/firmware/pru_i2c_firmware_version.h

pru_i2c_interface.hShared I2C memory map and instance layout +216/-0

Shared I2C memory map and instance layout

• Defines the host-to-PRU DMEM layout for I2C instances, including the instance size and Tx and Rx buffer offsets, used by the firmware and the host.

examples/pru_i2c/firmware/pru_i2c_interface.h

Bug fix (4) +2462 / -0
makefilePRU0 firmware makefile with -DPRU0 and -DSLICE0 defines +48/-0

PRU0 firmware makefile with -DPRU0 and -DSLICE0 defines

• Sets DFLAGS to -DPRU0 -DSLICE0 -DSOC_AM261X, so icss_constant_defines.inc selects the PRU0 DMEM constants. Also sets the hex-array output name and destination for pru0_load_bin.h.

examples/pru_i2c/firmware/am261x-lp/icss_m0_pru0_fw/ti-pru-cgt/makefile

makefilePRU1 firmware makefile with PRU1 build defines +48/-0

PRU1 firmware makefile with PRU1 build defines

• Same structure as the PRU0 makefile, with the PRU1 array name and pru1_load_bin.h output. The PRU1 defines are described in the PR as -DPRU1 -DSLICE1 -DSOC_AM261X; I did not open this file to confirm them.

examples/pru_i2c/firmware/am261x-lp/icss_m0_pru1_fw/ti-pru-cgt/makefile

pru_i2c_macro.hI2C state macros for IEP, SCL/SDA, and ACK handling +1006/-0

I2C state macros for IEP, SCL/SDA, and ACK handling

• Adds per-core IEP compare macros (I2C_WAIT_FOR_IEP_CMP, I2C_IEP_INTC_CLEAR_EVENT, I2C_SETUP_IEP_COUNTER) and SDA direction and release helpers. The PR says the ACK fix drives SDA through the GPO out-control register instead of high.

examples/pru_i2c/firmware/pru_i2c_macro.h

pru_i2c_main.asmMain I2C master state machine for PRU0 and PRU1 +1360/-0

Main I2C master state machine for PRU0 and PRU1

• Implements the 100 kHz, 400 kHz, and 1 MHz IEP-driven task loops and the I2C state machine. The PR changes per-core compare and context banks, derives the first compare value from the live counter, and releases SDA for ACK and read. ERROR_LOOP no longer stops the shared IEP counter.

examples/pru_i2c/firmware/pru_i2c_main.asm

Other (9) +2325 / -1
makefileAdd pru_i2c to top-level SUBDIRS +1/-1

Add pru_i2c to top-level SUBDIRS

• Adds pru_i2c to the examples SUBDIRS list so the top-level make recurses into the new project and the CI makefile-built check sees its firmware makefiles.

examples/makefile

makefileNew am261x aggregator makefile for pru_i2c +94/-0

New am261x aggregator makefile for pru_i2c

• Adds a project makefile modeled on examples/empty. It builds the PRU0 and PRU1 firmware for am261x and skips other devices through the SUPPORTED_PROCESSORS prebuild check.

examples/pru_i2c/makefile

example.projectspecCCS projectspec for PRU0 firmware +81/-0

CCS projectspec for PRU0 firmware

• Defines the CCS project for AM261x ICSS_M0_PRU_0 with -DPRU0 -DSLICE0 in compiler options. Links pru_i2c_main.asm and linker.cmd, and runs hexpru to produce pru0_load_bin.h.

examples/pru_i2c/firmware/am261x-lp/icss_m0_pru0_fw/ti-pru-cgt/example.projectspec

example.projectspecCCS projectspec for PRU1 firmware +81/-0

CCS projectspec for PRU1 firmware

• Mirrors the PRU0 projectspec for ICSS_M0_PRU_1 with -DPRU1 -DSLICE1 and the PRU1 hex-array output.

examples/pru_i2c/firmware/am261x-lp/icss_m0_pru1_fw/ti-pru-cgt/example.projectspec

linker.cmdPRU0 linker command file for DMEM0 placement +43/-0

PRU0 linker command file for DMEM0 placement

• Places all data sections in PRU0_DMEM_0 on PAGE 1, with code in PRU_IMEM and shared RAM on PAGE 2.

examples/pru_i2c/firmware/am261x-lp/icss_m0_pru0_fw/ti-pru-cgt/linker.cmd

linker.cmdPRU1 linker command file for DMEM1 placement +43/-0

PRU1 linker command file for DMEM1 placement

• Same memory map as PRU0, with data sections placed in PRU1_DMEM_1.

examples/pru_i2c/firmware/am261x-lp/icss_m0_pru1_fw/ti-pru-cgt/linker.cmd

pru0_load_bin.hGenerated PRU0 firmware hex array +944/-0

Generated PRU0 firmware hex array

• Generated header of the PRU0 firmware image. It is produced by hexpru from the build and is not hand-written. The PR says the committed versions came from the earlier no-define build, so confirm they are regenerated from this fixed source.

examples/pru_i2c/firmware/am261x-lp/pru0_load_bin.h

pru1_load_bin.hGenerated PRU1 firmware hex array +944/-0

Generated PRU1 firmware hex array

• Generated header of the PRU1 firmware image, with the same regeneration question as the PRU0 header.

examples/pru_i2c/firmware/am261x-lp/pru1_load_bin.h

makefileTop-level pru_i2c makefile for am261x +94/-0

Top-level pru_i2c makefile for am261x

• Prebuild checks restrict the build to am261x, and the am261x target recurses into the PRU0 and PRU1 firmware makefiles. Make pru, host, and clean dispatch through the same targets.

examples/pru_i2c/makefile

pratheesh and others added 2 commits October 2, 2026 13:48
…le SDA

Found on pru-simulator while checking the commands beyond TX.

- Dispatcher: the SMBus stub checks (QUICK .. BLOCK_READ) only advanced
  to the next check from some stubs, so dispatch stopped at
  ICSS_SMBUS_QUICK_CHECK for every command after TX. READ_SCL,
  RESET_SLAVE and LOOPBACK were unreachable, and any SMBus or unknown
  command left the firmware spinning there until reset. Replace the stub
  chain with one range check: SMBus commands (not implemented) get
  INVALID_COMMAND, everything else goes on to READ_SCL / RESET_SLAVE /
  LOOPBACK and then INVALID_COMMAND.
- RESET_SLAVE counted falling edges and ended with SCL low: 8 full SCL
  pulses and a bus left low. It also kept driving SDA high, fighting the
  stuck target it is meant to free. Release SDA, give 9 full pulses and
  end with SCL high.
- SDA is now released whenever the bus is idle (after setup, after STOP,
  after RESET) and taken back at the start of each transfer, so an idle
  master never drives SDA high against a target holding it low.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pratheesh Gangadhar <pratheesh.gangadhar@gmail.com>
Byte-identical to the ELFs exercised on pru-simulator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Pratheesh Gangadhar <pratheesh.gangadhar@gmail.com>
pratheesh added a commit to pratheesh/open-pru that referenced this pull request Oct 2, 2026
The example needs the firmware fixes (TexasInstruments#171) and the open-drain/SMBus
firmware it is built for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pratheesh

Copy link
Copy Markdown
Contributor Author

SMBus is now implemented as a follow-up stacked on this PR: pratheesh#2. It is a PR into this PR's branch, so merging it updates #171.

It adds:

  • The 9 SMBus protocols.
  • PEC.
  • An open-drain bus with clock stretching and an SCL-low timeout.
  • STOP after every error.
  • Bus timing that meets UM10204/SMBus minimums. 100 kHz START/STOP phases were too short, and "400 kHz" SCL low was 1.25 µs; it now runs at about 368 kHz.

On pru-simulator, against an SMBus target model written independently from the spec:

  • SMBus checks pass 54/54.
  • The I2C regression passes with timing enforced.
  • 14/14 ablations are caught.

Hardware note: SCL now needs a pull-up and its input path, like SDA. #172 is updated for this.

@achala-ti this answers my earlier question about the SMBus stubs. If you'd rather keep SMBus out of the example, #171 stands on its own without it.

@TexasInstruments TexasInstruments deleted a comment from qodo-code-review Bot Oct 16, 2026
@pratheesh-ti

Copy link
Copy Markdown
Collaborator

/agentic_review

@qodo-code-review

qodo-code-review Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Code Review by Qodo


View medium (6)
Remediation recommended
1. A NACKed address leaves the bus held busy 🐞
Description
NO_ADDRESS_ACK_RECIEVED now explicitly turns the SDA output driver back on
(SET_SDA_PIN_OUTPUT_DIRECTION) and then raises SCL, without first setting SDA high or generating a
STOP. The SDA GPO still holds the last address bit (R/W=0 for a write), so after a write-address
NACK the master actively pulls SDA low with SCL high. The bus stays busy until the next transfer,
which goes against the PR's own rule that SDA is released whenever the bus is idle.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
After an address NACK, NO_ADDRESS_ACK_RECIEVED turns the SDA output back on while the GPO still holds the last address bit (0 for writes), then raises SCL. The master is left pulling SDA low on an idle bus, with no STOP.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_main.asm[984-990]
- examples/pru_i2c/firmware/pru_i2c_macro.h[705-710]

## Recommended Fix
Generate a proper STOP. While SCL is still low: SET_SDA_PIN_LOW, then SET_SDA_PIN_OUTPUT_DIRECTION. Next tick: SET_SCL_PIN_HIGH. Next tick: SET_SDA_PIN_HIGH, then SET_SDA_PIN_INPUT_DIRECTION. Then write ADDRESS_ACKNOWLDEGE_FAILED. At minimum, do SET_SDA_PIN_HIGH before re-enabling the output, or leave SDA released, so the idle bus is not held low. Apply the same handling to `no_tx_data_ack_recieved?`.

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

Dismiss ↗ | View ↗

2. The build change has no matching runbook update 📘
Description
The two PRU makefiles now select different core, slice, and device definitions instead of leaving
DFLAGS empty. Because this changes the CCS-related build inputs and no docs_ai/ file is changed
in the PR, build guidance can continue to describe obsolete targets or flags.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR changes PRU build definitions for core, slice, and device selection without updating the required `docs_ai/` runbooks.

## Fix Focus Areas
- examples/pru_i2c/firmware/am261x-lp/icss_m0_pru0_fw/ti-pru-cgt/makefile[43-43]
- examples/pru_i2c/firmware/am261x-lp/icss_m0_pru1_fw/ti-pru-cgt/makefile[43-43]

## Recommended Fix
Update the relevant `docs_ai/` build and CCS runbooks to document the PRU0/PRU1-specific `DFLAGS`, slice definitions, and AM261X target, or add the corresponding runbook if none exists.

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

Dismiss ↗ | View ↗

3. A late core can reset a running timer 🐞
Description
I2C_SETUP_IEP_COUNTER tests whether the shared timer is enabled before entering an initialization
path that resets its count, clears status, and enables it. If one core passes that test but is
delayed while the other initializes and arms its compare, the delayed core can subsequently reset
the running timer and invalidate the other core's scheduled tick.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A stale observation that the shared timer is disabled permits one core to reset it after the other has started using it.
## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_macro.h[739-768]
## Recommended Fix
Give one core ownership of shared timer initialization or add inter-core startup coordination. Have the other core arm its own compare only after initialization is complete.

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

Dismiss ↗ | View ↗

4. A core can hang if both PRUs start together 🐞
Description
I2C_SETUP_IEP_COUNTER enables each PRU’s distinct compare bit through an unsynchronized
read-modify-write of the shared ICSS_IEP_CMP_CFG_REG. If both cores read the old value before
either writes, the later write can erase the first core’s enable bit, leaving that core in
I2C_WAIT_FOR_IEP_CMP, which checks only its own status bit and has no timeout.
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 read-modify-write operations in `I2C_SETUP_IEP_COUNTER` can erase one PRU’s enable bit in the shared IEP compare configuration register. That PRU then waits indefinitely for its compare event.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_macro.h[770-773]
- examples/pru_i2c/firmware/pru_i2c_main.asm[94-120]
- examples/pru_i2c/firmware/pru_i2c_main.asm[181-184]

## Recommended Fix
Coordinate the cores’ updates to the shared compare configuration register so neither can overwrite the other’s enable bit; for example, protect the read-modify-write with a hardware spinlock or ICSS mutex. Preserve each core’s distinct compare register and status bit.

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

Dismiss ↗ | View ↗

5. Recovery clocks use an avoidable up-counter 📘
Description
RESET_SLAVE_SCL_HIGH increments R15.b0, and the state loop terminates by comparing that counter
against R15.b3 with QBGT. The modified nine-pulse recovery loop could use a down-counter and a
single decrement/zero test, but the new implementation adds separate up-counting state and a bound
comparison.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The modified bus-recovery loop counts pulses upward in `R15.b0` and separately compares it with the configured bound.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_main.asm[1252-1293]

## Recommended Fix
Initialize a remaining-pulse counter, decrement it once per rising edge, and terminate with a zero-based conditional branch; preserve the existing pulse timing and final SCL state.

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

Dismiss ↗ | View ↗

6. SDA timing constraints remain undocumented 📘
Description
The SDA release operation in the transmit path adds GPIO direction-control instructions, but the
nearby four-tick comment gives no PRU clock, numeric cycle budget, or worst-case count for the
complete affected state. Because this state runs inside the bit-banged I2C timing window, the added
register access and state transition have no documented maximum against which to check the
bit-timing deadline.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The modified bit-banged I2C transmit state lacks adjacent numeric timing documentation covering the added SDA direction-control operations and the complete worst-case path.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_macro.h[621-624]

## Recommended Fix
Add a numeric WCET or PEAK-cycle annotation beside the affected protocol block. State the PRU frequency, required SCL/bit period, maximum cycles between edges, and the worst-case cycle count for the complete state, including the SDA direction register read, bit update, write, and state transition. Document the branch-path and GPIO-access timing assumptions and the derivation or measurement method, and keep the count synchronized with future instruction changes.

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

Dismiss ↗ | View ↗


View low (3)
Informational
7. The scheduler can wait forever 📘
Description
I2C_WAIT_FOR_IEP_CMP polls the compare-status bit without a timeout, iteration cap, or
cancellation check, and its comment describes the wait as unbounded. If the compare event is lost or
never armed, the counter stops, or IEP setup fails, the PRU and every caller remain stuck in the
polling loop without an error exit.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The IEP compare-event wait can block indefinitely when the expected hardware event does not arrive, leaving the PRU firmware without a recovery path.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_macro.h[85-91]
- examples/pru_i2c/firmware/pru_i2c_macro.h[105-107]

## Recommended Fix
Add a configured finite wait duration or iteration count to the polling macro. Detect expiry and transition to an explicit error, recovery, or host-notification path while preserving the normal compare-event path.

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

Dismiss ↗ | View ↗

8. The macro header still contains a tab 📘
Description
The modified closing directive in pru_i2c_macro.h contains a literal tab between the directive and
its comment. This violates the repository-wide no-tab requirement for changed header files and can
produce inconsistent formatting in assembler preprocessing and review tools.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The changed header still contains a literal tab character on its closing `.endif` line.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_macro.h[971-971]

## Recommended Fix
Replace the tab between `.endif` and the comment with spaces, then scan all `.asm`, `.inc`, `.c`, and `.h` files changed by the PR for additional tab characters.

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

Dismiss ↗ | View ↗

9. Source comments retain an unexplained abbreviation 📘
Description
The modified setup comment uses e.g. in pru_i2c_main.asm instead of spelling out for example.
The comment is part of the newly changed bus-idle behavior documentation, so the abbreviation
remains in first-party source introduced by this PR.
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A newly added source comment contains the abbreviation `e.g.`, which is disallowed by the checklist.

## Fix Focus Areas
- examples/pru_i2c/firmware/pru_i2c_main.asm[373-375]

## Recommended Fix
Replace `e.g.` with `for example` while preserving the explanation of a stuck bus before slave reset.

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

Dismiss ↗ | View ↗


pratheesh and others added 7 commits October 16, 2026 09:21
Address review findings on the macros changed by the per-core IEP and
scratchpad-bank fixes:
- I2C_IEP_INTC_CLEAR_EVENT: add pseudocode, the arg1 no-event continuation
  label that was documented as 'Parameters: None', and the registers it
  modifies.
- I2C_WAVE_FUNCTION0: add pseudocode and the registers it modifies,
  including the per-core context bank.
- I2C_WAIT_FOR_IEP_CMP: tag the scheduler tick with
  INTENTIONALLY_UNBOUNDED_LOOP; there is no other time base to time it
  out against.

Documentation only, no instruction changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
White space between mnemonic and operand is 5 spaces for 3-letter and 4
for 4-letter operations (best_practices.md); the SET/CLR/LDI32/LBBO/SBBO
lines in SET_SDA_PIN_INPUT/OUTPUT_DIRECTION used one space. Whitespace
only, the assembled output is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
NO_ADDRESS_ACK_RECIEVED took SDA back with the SDA GPO still holding the
last address bit (0 for a write), so after a NACKed write address the
master pulled SDA low on a bus it never STOPped, contradicting the
'SDA is released whenever the bus is idle' rule. Leave SDA released:
SET_SCL_SDA_HIGH takes it back at the start of the next transfer.

The data-byte ACK slot had the same pattern (SET_SDA_PIN_OUTPUT_DIRECTION
before testing the ACK bit). Take SDA back only after an ACK, when the
master transmits next (data or STOP).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…y selector

I2C_SETUP_IEP_COUNTER and I2C_IEP_INTC_CLEAR_EVENT add
I2C_GLOBAL_FREQ_REG.w2 to the compare value, but startup only loaded the
configuration word and nothing set w2 for the selected frequency. A
configuration holding just the selector (w0) gave an increment of 0, so
the compare was re-armed at the current count and the tick had no period.

Set w2 from the selector (IEP_CMP_INCREMENT_VAL_100KHZ / _400KHZ / _1MHZ)
before the IEP is set up. An unsupported selector keeps w2 = 0 and still
ends in ERROR_LOOP. Any w2 the host wrote is now replaced by the
selector's value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
PRU0 and PRU1 share the IEP counter and IEP_CMP_CFG_REG and nothing in
hardware serialises their start-up. State that the two cores must be
released one after the other, and what goes wrong otherwise (lost enable
bit, counter reset under the running core).

The race itself is not closed in firmware: the enable-bit update is
already a read-modify-write rather than the earlier overwrite, and no
cross-core lock is available to these cores in this example.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Rebuilt with the makefile flow (make -C examples/pru_i2c pru DEVICE=am261x
BUILD_MCUPLUS=y) after the review-fix changes. Not hardware tested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Derive w2 from the frequency selector only when the host left it at 0,
so a nonzero increment written by the host stays an override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pratheesh-ti
pratheesh-ti changed the base branch from a0502729_PRU_I2C to main December 1, 2026 07:23
pratheesh added a commit to pratheesh/open-pru that referenced this pull request Dec 1, 2026
…ample branch

TexasInstruments#137 is closed in favour of this PR, so this PR now also carries
TexasInstruments#171's review follow-ups from 2026-10-16, which it did not have:

- 146ccec: pseudocode, arg1 and registers-modified docs for
  I2C_IEP_INTC_CLEAR_EVENT and I2C_WAVE_FUNCTION0. The scheduler wait is
  marked INTENTIONALLY_UNBOUNDED_LOOP. The I2C_WAVE_FUNCTION0 register
  note now also covers this branch's R23/R26 open-drain pin registers.
- 466c7af, 9b8099e: derive the IEP compare increment from the
  frequency selector when the host leaves it at 0, and keep a nonzero
  host value. The R5F example always writes a nonzero increment, so its
  path is unchanged.
- e161b91: document the shared-IEP start-up ordering constraint.

Two commits are not taken. This branch's open-drain bus replaces the
push-pull SDA direction control they patch:
- 6e43662 fixes spacing in SET_SDA_PIN_INPUT/OUTPUT_DIRECTION, which no
  longer exist here.
- a0ca016 leaves SDA released after a NACK. Here SDA is only ever
  released or pulled low, and an address or data NACK ends with a STOP
  through DATA_PROCESSING_COMPLETE.

pru0/pru1_load_bin.h are regenerated with the makefile flow (clpru
2.3.3, no warnings). Each image grows by exactly the 7 instructions of
the selector-to-increment derivation.
TexasInstruments#137 is closed and this PR now targets main. The only conflict is the
SUBDIRS list in examples/makefile, where main added pru_eqep and pru_i2s;
keep all three.
@pratheesh

Copy link
Copy Markdown
Contributor Author

Refreshed for main now that #137 is closed: main is merged in (e8f3a040). The only conflict was the examples/makefile SUBDIRS list, and the PRU build reproduces the committed load_bin.h exactly.

All of this PR is also in #172, which builds on it with the open-drain bus, SMBus and the R5F example, and has run on silicon. If #172 is merged, this PR can be closed without merging. All review threads are answered and resolved.

@pratheesh

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #172, which contains every commit of this PR (merged in 40119da) on top of the open-drain bus, SMBus and the R5F example.

@pratheesh pratheesh closed this Dec 1, 2026
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.

3 participants