This is an automated email from the ASF dual-hosted git repository.

acassis pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit e26d467fab748d329000351728e00aa5e98b721e
Author: Daniel P. Carvalho <[email protected]>
AuthorDate: Sat Oct 3 17:01:00 2026 -0300

    arch/mips/pic32mz: do not exceed the requested SPI frequency.
    
    spi_setfrequency() in pic32mz_spi.c rounded the baud rate divisor down,
    so the SCK frequency could be higher than the one requested by the
    device driver (e.g. 20 MHz requested with a 100 MHz PBCLK2 gave 25 MHz).
    A request above PBCLK/2 gave a zero divisor and a division by zero when
    computing the actual frequency; the SST26 driver's default of 64 MHz
    does that with any peripheral bus clock below 128 MHz.
    
    Round the divisor up instead, so the actual frequency never exceeds the
    requested one and the divisor is never zero.  Boards whose requested
    frequency is not an exact divisor of PBCLK/2 now run SPI at a lower
    clock than before.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Daniel P. Carvalho <[email protected]>
---
 arch/mips/src/pic32mz/pic32mz_spi.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/arch/mips/src/pic32mz/pic32mz_spi.c 
b/arch/mips/src/pic32mz/pic32mz_spi.c
index 5f251e69d9d..2c3deea91d5 100644
--- a/arch/mips/src/pic32mz/pic32mz_spi.c
+++ b/arch/mips/src/pic32mz/pic32mz_spi.c
@@ -1252,9 +1252,13 @@ static uint32_t spi_setfrequency(struct spi_dev_s *dev,
    *
    * frequency = BOARD_PBCLOCK / (2 * divisor), or
    * divisor  = (BOARD_PBCLOCK / 2) / frequency
+   *
+   * Round up so that the actual frequency never exceeds the requested one.
+   * This also keeps the divisor >= 1 when the request is above
+   * BOARD_PBCLOCK / 2.
    */
 
-  divisor = (BOARD_PBCLOCK / 2) / frequency;
+  divisor = (BOARD_PBCLOCK / 2 + frequency - 1) / frequency;
 
   /* The a BRG register value is that divisor minus one
    *
@@ -1262,11 +1266,7 @@ static uint32_t spi_setfrequency(struct spi_dev_s *dev,
    * BRG       = (BOARD_PBCLOCK / 2) / frequency - 1
    */
 
-  regval = divisor;
-  if (regval > 0)
-    {
-      regval--;
-    }
+  regval = divisor - 1;
 
   /* Save the new BRG value */
 

Reply via email to