Teensy 4.1: exact 2^30-cycle CPU stall (1491 ms @720 MHz), depends on the build

Marmes

Member
Summary

I see a periodic stall of the whole CPU of exactly 2^30 CPU cycles (1491 ms at 720 MHz, 1790 ms at 600 MHz). It looks the same as the freeze in the 2021 thread "Teensy 4.1 Freeze (~1786ms)" by UdoZ (Paul: 2^28 IPG cycles), but I am on core 1.62.0 where the overlapping FlexSPI2 MPU regions are long fixed. The stall is deterministic for a given binary, but different builds of nearly identical source behave completely differently: some run for hours without a single stall, some stall reproducibly at the same uptime. I can mitigate it but I have not found the cause. I would be grateful for any idea what can block a Cortex-M7 for exactly 2^30 cycles.

Hardware / software

  • Teensy 4.1, 720 MHz (also seen at 600 MHz), -O2, USB Type "Serial", Arduino IDE 2, "Teensy (for Arduino IDE 2.0.4 or later)" package 1.62.0
  • PSRAM: 2x APS6404L (8 MB each), hand-soldered, 16 MB in total. The core detects psram=16MB and a memory test over the full 16 MB gives 0 errors
  • u-blox ZED-F9P on Serial1 (LPUART6) at 921600 baud. At 5 Hz: RAWX + SFRBX + NAV-PVT + NAV-SAT + NMEA, about 30 KB/s. At 1 Hz about 6 KB/s
  • Built-in microSD (SD library bundled with Teensyduino), HX8357D TFT on SPI, resistive touch. The sketch is about 6000 lines
  • GPS RX: 32 KB hardware serial buffer, an IntervalTimer (5 ms, priority 144) drains it into a 1 MB ring buffer in PSRAM (EXTMEM). The main loop parses from the ring and writes to SD. A second small buffer lives in DMAMEM (RAM2)

Symptom

  • All CPU activity stops for exactly 2^30 cycles: main loop, IntervalTimer, GPS parsing. The serial buffer overflows and the log contains garbage frames. millis()/micros() keep correct time afterwards. I measure it with DWT_CYCCNT in an ISR (isr=1491 ms)
  • In affected builds it starts at about 1886 s uptime, as a series of several events a few seconds apart, and again at about 6183 s and 10476 s. The 4295 s spacing is suspiciously close to 2^32 microseconds
  • Also happens with no SD card inserted, so SD and SdFat are not the cause (I tried the Adafruit SdFat fork, SdFat 2.3.0 and the bundled one)
  • UART error counters (framing/noise) stay at 0 for the whole run; the overrun flag only shows up after the stall

What the hardware does during the stall

I attached a high priority GPT2 interrupt (priority 0) as a probe. During a stall, the interrupt that is executing is the LPUART6 interrupt (IPSR = 41), and the PC sits in HardwareSerialIMXRT::IRQHandler on a strb into the receive buffer in DMAMEM (RAM2). The UART interrupt rate drops from about 46000/s to 2000-8000/s, i.e. each byte store into the RAM2 buffer takes roughly 100-300 microseconds. It looks like memory accesses through the cache/AXI path become extremely slow, rather than the CPU sitting in a loop.

It depends on the binary

  • Version 10.133 built on Oct 24 22:21: ran 8314 s and 1920 s with no stall at all (isr max 5 ms). It passed the 1886 s and 6181 s marks
  • The same version number, rebuilt on Oct 25 11:11: stalls at 1885 s every time (isr = 1491 ms, 18-30 bad frames per run)
  • An older build (10.89, 600 MHz): 12510 s with no stall
  • The current build (10.153) has now run 6329 s at 5 Hz with the full load and touch input with no stall, passing both the 1886 s and 6181 s marks (isr max 5 ms, GPT2 probe gap constant 62 ms)
  • Adding unrelated diagnostics changes the behaviour. This matches the old thread, where one extra character in a Serial.println made the freeze vanish

What I tried

  • Without SD card, with different SD libraries, re-formatted card: no change
  • Without PSRAM (ring buffers in the heap): worse, a stall every 6.3 s and finally a complete hang. So PSRAM is not simply the culprit
  • USB Type "Serial" vs "Serial + MTP": MTP with a PC cable gives separate 1.8 s stalls (a different problem, avoided). The stall described here also happens with USB Type "Serial"
  • Wiring: UART error counters stay 0; re-wired and soldered, no difference
  • The probe (GPT2 priority 0, 62.5 ms tick, an arm_dcache_flush_delete of one RAM2 line on each tick, CCM_CCGR0 bits set, GPT2 reset) mitigates it (0-7 bad frames in a 6389 s run) but does not remove it: at one event (6185 s) the probe saw a 1428 ms hole in its own ticks while a lower priority timer slipped only 27 ms
  • Module output rate: with the receiver set to 1 Hz the first mark passed. With the build dependency above I do not trust this as proof

MPU

I read the MPU regions back from the running sketch (region, base address, SIZE field):

Code:
r0=0/31  r1=0/18  r2=0/4  r3=200000/16  r4=20000000/18  r5=2002F8A0/4
r6=20200000/19  r7=40000000/25  r8=60000000/23  r9=70000000/24  r10=80000000/29

There is only one FlexSPI2 region, so the old overlapping 256M READONLY region is gone. The stock 1.62.0 startup.c uses SIZE_32M for 0x70000000 (r9, SIZE field 24); I assume it was raised from 16M to cover two 16 MB PSRAM chips. In the old thread Frank B reported (post #137) that a single FlexSPI2 region larger than 16M still froze. With my 16 MB of PSRAM that leaves 16 MB of cacheable read/write address space with nothing behind it.

I tested both: with SIZE_16M (r9 = 70000000/23) the build ran 6329 s without a stall. With SIZE_32M (the stock value) the same sketch object (only the core was recompiled) has passed the 1886 s mark so far without a stall; that run is still going. So I cannot show that the region size is the cause. I will update this post when the 103 minute mark has passed.

Questions

  1. Is there any known mechanism, other than the old FlexSPI2 MPU issue, that can block the M7 for exactly 2^30 CPU cycles (2^28 IPG cycles)? Is there a hardware timeout of that length (FlexSPI AHB, AIPS, OCRAM, SEMC, PXP)?
  2. Why does the stall depend on code layout? Could it be code or data alignment against cache lines, flash/ITCM placement, or something in the FlexSPI1 (QSPI flash) read path while the CPU executes from flash?
  3. Which registers would be worth dumping right after a stall to identify the blocked bus? I can add that to the logger; it is reproducible within about 30 minutes in an affected build
  4. Is there a recommended way to move the receive buffer out of DMAMEM/RAM2 (for example into TCM) just for testing, to see whether the stall follows the RAM2 accesses?

I can supply the full diagnostic log files (one row every 5 s, with the raw bad frames) and the sketch. It is large, so I have no minimal sketch yet, but the behaviour is reproducible per binary at the same uptime.

Thanks!
 
Update: the MPU region size is not the cause.

I ran the same sketch object (the sketch was not recompiled, only the core) with the stock SIZE_32M and with SIZE_16M for the FlexSPI2 region. I confirmed the active setting by reading the MPU back at boot (region 9: 70000000/24 = 32M, 70000000/23 = 16M). Both runs were at 5 Hz with the full GPS load and touch input:

  • SIZE_16M: 6329 s without a stall
  • SIZE_32M (stock core 1.62.0): 6307 s without a stall

In both runs the 1886 s and 6181 s marks passed cleanly: ISR time max 5 ms, GPT2 probe gap constant at 62 ms, 0 bad frames, 0 lost bytes. So the FlexSPI2 region size does not decide it in my case.

What remains is that the same source behaves differently per build: 10.133 built on Oct 24 ran 8314 s clean, the rebuild of the same version on Oct 25 stalls at 1885 s every time, and the current build (10.153) is clean. The differences between a stalling build (10.147) and the clean one (10.153) are the code layout and that the new build sets the receiver's measurement rate at boot over UBX-CFG-VALSET. I will rebuild the old one on the current core to see whether the receiver command matters.

Earlier thread this resembles (UdoZ, 2021, overlapping FlexSPI2 MPU regions): https://forum.pjrc.com/index.php?threads/teensy-4-1-freeze-1786ms.66525/

My questions above still stand, in particular which registers would be worth dumping right after a stall to find out which bus is blocked.
 
It most likely is the PSRAM MPU region size. The trick is that it's being caused by speculative execution (rather than any actual memory read in your code), which can behave very unpredictably even between the same program runs.

Not quite sure how you managed to miss this thread with an almost identical title to this one: https://forum.pjrc.com/index.php?th...very-2-32-cycles-systick-keeps-running.78098/
And also this one: https://forum.pjrc.com/index.php?th...lexspi2-mpu-region-when-less-is-fitted.78164/

One thing I'm noticing, this only seems to be an issue on boards with 2x8MB PSRAM chips; even before the MPU region was increased from 16MB to 32MB, boards with only 1x8MB PSRAM didn't seem to ever suffer from this issue (and still don't now). Possibly something to do with the speculative execution mistaking opcodes that begin with 0x71 for memory addresses?
the PC sits in HardwareSerialIMXRT::IRQHandler on a strb into the receive buffer in DMAMEM (RAM2).
Would you be able to tell me the exact opcode encoding (and the one immediately after it) for that strb instruction? I'm guessing it starts with a 7...
 
Last edited:
Another test, and I have to take back my last conclusion

I repeated the test with the same build as in my previous post (10.153, stock SIZE_32M, MPU read-back at boot shows region 9 = 70000000/24, same compiled sketch, only a normal restart in between, 5 Hz GPS load, touch input as before).

This time it stalled:

  • at about 1898 s uptime (the familiar 1890-1900 s)
  • the GPT2 probe saw holes of 1456 ms and 1487 ms in two consecutive 5 s log windows (probe gap is 62 ms otherwise)
  • ISR max 36 ms, 2 bad NMEA frames (cut off in the middle of a $GNGRS sentence), no lost bytes
  • after that it ran on to 2611 s with no further events

The run before it, with exactly the same binary and the same core, ran 6307 s with no stall at all.

So the same binary is clean in one boot and stalls in the next. My statement in the previous post that the region size is not the cause is not supported by this: I only have a single clean run with SIZE_16M (6329 s), and a single clean run and a single stalled run with SIZE_32M. With that spread I can not say anything about either value, so please read my previous post as "not demonstrated", not as "excluded".

At the moment I can not find any systematic pattern to build on:

  • Same binary, same core, same hardware: sometimes clean for hours, sometimes it stalls at the usual uptime
  • Different builds of the same source also differ (clean on Oct 24, stalling on Oct 25), so it is not only the binary and not only the boot
  • Temperature at start was 56-57 C in all runs. The restart type (power-up vs software restart) does not separate the cases either, both kinds were clean and both kinds stalled
  • Changing the receiver rate to 1 Hz was clean in the one run I did, but with this spread that proves nothing

I will keep repeating the same configuration many times to get a stall rate per boot, instead of trusting single runs. If anyone has an idea about what could differ from boot to boot (FlexSPI2 sample clock / DLL calibration with my two hand-soldered PSRAM chips at 105.6 MHz, PLL or clock phase, anything else), or which registers are worth logging right after an event to see which bus is blocked, I would be very happy to try it.
 
It most likely is the PSRAM MPU region size. The trick is that it's being caused by speculative execution (rather than any actual memory read in your code), which can behave very unpredictably even between the same program runs.

Not quite sure how you managed to miss this thread with an almost identical title to this one: https://forum.pjrc.com/index.php?th...very-2-32-cycles-systick-keeps-running.78098/
And also this one: https://forum.pjrc.com/index.php?th...lexspi2-mpu-region-when-less-is-fitted.78164/

One thing I'm noticing, this only seems to be an issue on boards with 2x8MB PSRAM chips; even before the MPU region was increased from 16MB to 32MB, boards with only 1x8MB PSRAM didn't seem to ever suffer from this issue (and still don't now). Possibly something to do with the speculative execution mistaking opcodes that begin with 0x71 for memory addresses?

Would you be able to tell me the exact opcode encoding (and the one immediately after it) for that strb instruction? I'm guessing it starts with a 7...
Thanks, and thanks for the pointers to the other two threads. I will test the same fix (resizing the region at startup, in my case from startup_middle_hook so I do not have to touch the core).

The instruction at the stalled PC (HardwareSerialIMXRT::IRQHandler+0x11a, I took it from the compiler listing of the current build, the function itself did not change since I measured the PC):

2f4b8: 6a44 ldr r4, [r0, #36]
2f4ba: f804 c001 strb.w ip, [r4, r1]
2f4be: e797 b.n 2f3f0 <HardwareSerialIMXRT::IRQHandler()+0x50>

It is a 32-bit Thumb-2 strb.w (halfwords 0xF804, 0xC001), not a 16-bit 0x7xxx one. The source line is rx_buffer_storage_[head-rx_buffer_size_] = n; i.e. the store into the extra receive buffer I added with addMemoryForRead (in DMAMEM / RAM2). Bytes in memory: 44 6a 04 f8 01 c0 97 e7. The code is in ITCM.

So the interrupted instruction is not related to the 0x71 pattern as far as I can see. It is just where the stall catches the CPU (as _jacek_ also found), the store goes to RAM2 and only the bus is blocked.
 
Found it: it is the same speculative-read problem, and in my case the trigger is micros()

Thanks to everyone, in particular to the thread by SamiH (the AHBBUSWAIT explanation: 0xFFFF x 1024 cycles x 16 = 2^30 cycles) which made me look at the value in the register rather than at the code.

My log has a line every 5 s with micros(). The stall windows in my logs always lie where micros() is in the range 0x71000000..0x71FFFFFF:

Code:
0x71000000 us = 1895.825 s     0x72000000 us = 1912.603 s
log row up=1888 s  micros 0x714C47D2  in range
log row up=1893 s  micros 0x7198919B  in range
log row up=1898 s  micros 0x71E4DAC2  in range, probe gap 1456 ms
log row up=1903 s  micros 0x7231252A  probe gap 1487 ms (the stall ended in this window)

micros() has a period of 2^32 us = 4295 s, which is exactly the period I measured for the stalls (1886 s + n x 4295 s, i.e. about 1886 s, 6181 s, 10476 s after boot). That is the reason why the time looked deterministic, why it needed 5 Hz load (more micros() values live in registers while the GPS parser runs), and why it depends so much on the build: whether the compiler keeps the micros() value in a register that the core then uses to speculate a load depends on code layout and register allocation. The ADC/yield() link jacek found probably belongs to the same effect.

Also see: my board has the same hand-soldered 2 x 8 MB PSRAM (16 MB) with the stock 32 MB region, so 0x71000000 and up is cacheable normal memory with nothing behind it.

The fix: I resize the FlexSPI2 MPU region at startup to the detected PSRAM size, from startup_middle_hook() in the sketch (so I do not have to touch the core), and the region is 16 MB on my board. I am running a long log now; the first checks are the windows around micros() = 0x71000000 (about 1883-1900 s after boot, then 6178-6195 s). I will report back whether it stays clean. I agree with SamiH that the core could size the region in configure_external_ram() after the PSRAM size is known.
 
Ah, so the bad address is coming from a register. I was thinking another possibility might be a text string starting with 'q' being stored near a FLASHMEM function.
 
Ah, so the bad address is coming from a register. I was thinking another possibility might be a text string starting with 'q' being stored near a FLASHMEM function.
Thanks. A string starting with 'q' (0x71) near a FLASHMEM function is a good thought, but in my case the stall windows line up with micros() being in 0x71000000..0x71FFFFFF (period 2^32 us = 4295 s), so I think the register is what triggers it. A literal pool string would not give that period. Either way, anything that reads speculatively from 0x71xxxxxx while the region is 32 MB and only 16 MB is fitted can trigger it, so shrinking the region to the fitted size covers both cases.
 
boards with only 1x8MB PSRAM didn't seem to ever suffer from this issue
Looking at the startup code I see the reason for this - when only one chip is present, the FLEXSPI2_FLSHA2CR0 register is never touched and keeps its default value (64MB). So in that case FlexSPI doesn't think the memory is "unbacked" and never stalls the AHB bus.

This also explains why boards with no PSRAM don't have any issues - in that case both FLEXSPI2_FLSHA1CR0 and FlexSPI2_FLSHA2CR0 keep their 64MB default values.
 
When the problem happens, any chance you could read the FLEXSPI2_STS1 register?

Main question is whether these fields indicate the hardware detected any sort of error.

1792967390566.png
 
Also another blind guess, if this is some sort of timeout error, maybe configuring different the AWRWAIT and AWRWAITUNIT fields in FLEXSPI2_FLSHA1CR2 and FLEXSPI2_FLSHA2CR2 might have some effect?
 
Is micros() time value just when the problem happens? The testing time could be cut with:
extern "C" volatile uint32_t systick_millis_count;
Setting that to 70 minutes of millis when seen less than 1 minute of millis?
// 1 min = 1*60*1000
// 70 min = 70*60*1000
if ( (1*60*1000) > systick_millis_count ) systick_millis_count = 70*60*1000;
Could also force repro?: if ( (73*60*1000) > systick_millis_count ) systick_millis_count = 70*60*1000;

Code:
// Returns the number of microseconds since your program started running.
// This 32 bit number will roll back to zero after about 71 minutes and
// 35 seconds.  For a simpler way to build delays or timeouts, consider
// using elapsedMicros.
uint32_t micros(void)
{
    uint32_t smc, scc;
    do {
        __LDREXW(&systick_safe_read);
        smc = systick_millis_count;
        scc = systick_cycle_count;
    } while ( __STREXW(1, &systick_safe_read));
    uint32_t cyccnt = ARM_DWT_CYCCNT;
    asm volatile("" : : : "memory");
    uint32_t ccdelta = cyccnt - scc;
    uint32_t frac = ((uint64_t)ccdelta * scale_cpu_cycles_to_microseconds) >> 32;
    if (frac > 1000) frac = 1000;
    uint32_t usec = 1000*smc + frac;
    return usec;
}
 
Also another blind guess, if this is some sort of timeout error, maybe configuring different the AWRWAIT and AWRWAITUNIT fields in FLEXSPI2_FLSHA1CR2 and FLEXSPI2_FLSHA2CR2 might have some effect?
I doubt that would have any effect. The speculative accesses are causing FlexSPI to access the non-present B1 device (because the memory address is beyond the combined sizes of A1 and A2 as set in their CR0 registers). The B1 and B2 control registers are never initialized in the startup code and hold their default power-on values:
- size of 64MB
- LUT read and write sequence indexes both set to 0 in the CR2 register, which is the "exit QPI mode" sequence and doesn't return any data.

So when a speculative access occurs to read memory that doesn't exist, FlexSPI activates SS0_B (which isn't externally muxed), sends the exit QPI mode sequence, then waits for its AHB RX buffer to fill up (which never happens because the sequence has no read stage) and times out after AHBBUSWAIT cycles.

Setting the correct size for the MPU region stops the speculative access from attempting to access the invalid memory.
Setting CR0 for all unused devices (A1/A2/B1/B2) to zero would also be advisable, but that's not a complete fix on its own because there may be flash chips present - they will be accessible via AHB if the PSRAM MPU region is oversized.
 
Last edited:
Thanks Paul, and thanks jmarsh who explained the B1 behaviour. I ran a minimal reproduction on the stock core 1.62.0 (Teensy 4.1, 720 MHz, 2x APS6404L = 16 MB, psram=16MB detected). It reads the first address behind the PSRAM (0x70000000 + 16 MB) from loop(), and a BusFault handler stores the FlexSPI2 registers in DMAMEM and resets, so I can print them after the reboot.

Result on the stock core (MPU region 0x70000000 = 32 MB)

Code:
BFAR   0x71000000  CFSR 0x00008200 (BFARVALID, PRECISERR)  HFSR 0
stall  268431504 CPU cycles = 0.373 s @720 MHz

FLEXSPI2_MCR0      0xFFFF8010
FLEXSPI2_MCR1      0xFFFFFFFF   (AHBBUSWAIT = 0xFFFF, SEQWAIT = 0xFFFF)
FLEXSPI2_AHBCR     0x00000000
FLEXSPI2_INTR      0x00000440   (bit 6 IPTXWE, bit 10 SEQTIMEOUT; bit 9 not set)
FLEXSPI2_STS0      0x00000003
FLEXSPI2_STS1      0x00000000   (AHBCMDERRID/CODE = 0, IPCMDERRID/CODE = 0)
FLEXSPI2_STS2      0x00000000
FLEXSPI2_FLSHA1CR0 0x00002000   (8 MB)
FLEXSPI2_FLSHA2CR0 0x00002000   (8 MB)
FLEXSPI2_FLSHA1CR2 0x00000605   (ARDSEQID 5, AWRSEQID 6, AWRWAIT 0)
FLEXSPI2_FLSHA2CR2 0x00000605
FLEXSPI2_FLSHB1CR0 0x00010000   (64 MB, power-on default)
FLEXSPI2_FLSHB2CR0 0x00010000
FLEXSPI2_FLSHB1CR2 0x00000000   (read and write sequence index 0)
FLEXSPI2_FLSHB2CR2 0x00000000

So this matches the explanation: the address is beyond A1+A2 (8+8 MB), B1/B2 are untouched power-on defaults (64 MB, sequence index 0), and the access ends with a timeout instead of an AHB command error (STS1 = 0). AWRWAIT/AWRWAITUNIT are 0 in A1/A2 and are not involved, so Paul's guess does not apply here. One detail: the timeout shows up as SEQTIMEOUT (bit 10), not as bit 9.

One thing I cannot explain: this single load stalls 2^28 CPU cycles (0.373 s), while in my logger the stall is 2^30 cycles (1.49 s), exactly 4 times longer. Maybe the speculative cache line fill is retried several times before it gives up, but this test does not show that.

Result of my application

With the MPU region for 0x70000000 resized to the detected PSRAM size (done from startup_middle_hook() in the sketch, core files untouched) the logger ran 12 h 9 min at 5 Hz with 0 bad frames and the CPU/ISR gap constant (62 ms), including nine passes through the micros() = 0x71xxxxxx windows (uptime 1884, 6178, 10473, 14768, 19063, 23358, 27653, 31948, 36243 s) where the same code before stalled at the first one. I will repeat the run once more.

The whole fix (mpu_fix.h, #include it in the sketch; it finds the MPU region with base 0x70000000 and sets its SIZE field to the detected PSRAM size, so it also keeps working if a future core already does this):

Code:
// mpu_fix.h: resize the FlexSPI2 MPU region to the PSRAM that is really fitted.
// The stock startup.c always uses 32 MB; with 16 MB fitted the upper 16 MB is cacheable
// "normal memory" with nothing behind it. Runs from startup_middle_hook(), i.e. after the
// PSRAM has been detected and before USB and setup().
#include <Arduino.h>
extern "C" uint8_t external_psram_size;
extern "C" FLASHMEM void startup_middle_hook(void) {
  const uint32_t RNR = 0xE000ED98UL, RBAR = 0xE000ED9CUL, RASR = 0xE000EDA0UL;
  int reg = -1;
  uint32_t ra = 0;
  for (int r = 0; r < 16; r++) {                       // find the region based at 0x70000000
    *(volatile uint32_t *)RNR = (uint32_t)r;
    __asm__ volatile ("dsb" ::: "memory");
    uint32_t b = *(volatile uint32_t *)RBAR & 0xFFFFFFE0UL;
    uint32_t a = *(volatile uint32_t *)RASR;
    if (b == 0x70000000UL && (a & 1u)) { reg = r; ra = a; break; }
  }
  if (reg < 0) return;                                 // not found: leave the core setup alone
  uint32_t mb = external_psram_size;
  uint32_t sz = (mb == 0) ? 4u : (mb <= 8 ? 22u : (mb <= 16 ? 23u : 24u));  // SIZE: 4 = 32 B, 22 = 8 MB, 23 = 16 MB, 24 = 32 MB
  uint32_t na = (ra & ~(0x1Fu << 1)) | (sz << 1);
  if (na == ra) return;                                // already correct
  uint32_t pm;
  __asm__ volatile ("mrs %0, primask" : "=r" (pm));
  __disable_irq();
  uint32_t ctrl = SCB_MPU_CTRL;
  __asm__ volatile ("dmb" ::: "memory");
  SCB_MPU_CTRL = 0;
  *(volatile uint32_t *)RNR = (uint32_t)reg;
  *(volatile uint32_t *)RASR = na;
  SCB_MPU_CTRL = ctrl;
  __asm__ volatile ("dsb" ::: "memory");
  __asm__ volatile ("isb" ::: "memory");
  if (!(pm & 1u)) __enable_irq();
}

The same minimal test with the fix

Same sketch, same read of 0x71000000, only the MPU region for 0x70000000 resized to the detected PSRAM size (16 MB) from startup_middle_hook():

Code:
vector 4 (MemManage)  CFSR 0x00000082 (MMARVALID, DACCVIOL)  MMFAR 0x71000000
stall  116 CPU cycles (instead of 268431504)
FLEXSPI2_INTR 0x00000040 (only IPTXWE, SEQTIMEOUT not set)
FLEXSPI2_STS1 0x00000000

So the access is stopped by the MPU immediately and never reaches FlexSPI, as Paul and the others described. The registers of FlexSPI2 are identical to the stock run, only the MPU region differs. In the real application the speculative accesses have no fault to report (they are never architecturally executed), they simply no longer reach the FlexSPI.
 
FLEXSPI2_INTR 0x00000440 (bit 6 IPTXWE, bit 10 SEQTIMEOUT; bit 9 not set)
SEQTIMEOUT is bit 11 (not set), AHBBUSTIMEOUT is bit 10 (is set).

One thing I cannot explain: this single load stalls 2^28 CPU cycles (0.373 s), while in my logger the stall is 2^30 cycles (1.49 s), exactly 4 times longer. Maybe the speculative cache line fill is retried several times before it gives up, but this test does not show that.
The max AHB burst size is 64 bits and the memory is marked cached so any speculative access should trigger 4x AHB bursts to fill a 256 bit cacheline. I can't explain why a non-speculative access does not act the same.
 
SEQTIMEOUT is bit 11 (not set), AHBBUSTIMEOUT is bit 10 (is set).


The max AHB burst size is 64 bits and the memory is marked cached so any speculative access should trigger 4x AHB bursts to fill a 256 bit cacheline. I can't explain why a non-speculative access does not act the same.
Follow-up: corrections, the complete fix and the full reproduction

Thanks jmarsh, you are right about the INTR bits (AHBBUSTIMEOUT is bit 10 and it is the one that is set, SEQTIMEOUT is bit 11 and not set; I took the bit order from a generated register list and was wrong), and your cache line explanation answers my open question: the 2^30 stall is 4 x 2^28, one timeout per 64-bit AHB burst of a 256-bit line fill. My previous post had only a stub of the fix code, so here is the complete chain again with the full code: root cause, evidence, the minimal reproduction with registers, the fix (sketch only, core untouched), and the result in my real application.

Short version: the stall is caused by the stock MPU setup for 0x70000000 being larger than the PSRAM that is really fitted.

1. Setup

  • Teensy 4.1, 720 MHz, USB Type "Serial", Arduino IDE 2, Teensy package 1.62.0
  • 2x APS6404L (8 MB each) soldered on, psram=16MB detected by the core, memory test over the full 16 MB is clean
  • Application: GPS logger, ZED-F9P on Serial1 at 921600 baud, SD logging, TFT, about 6000 lines

2. Why it looked random

The stock startup.c (1.62.0) sets one MPU region for 0x70000000 with SIZE_32M (SIZE field 24, I read it back at run time). With two 8 MB chips only the first 16 MB (0x70000000-0x70FFFFFF) exist. 0x71000000-0x71FFFFFF is cacheable normal memory with nothing behind it. The Cortex-M7 may issue speculative reads to any address that is in a register and falls into such a region, even if the program never dereferences it. In my sketch the trigger is a value derived from micros(): whenever micros() is in 0x71000000..0x71FFFFFF (= 1895.825 s ... 1912.603 s after boot, repeating every 2^32 us = 4294.967 s), a register holds a "valid" address in the hole at some point. Whether that happens depends on what the compiler keeps in registers, so it depends on the exact binary: one-character changes, different library versions, a rebuild on another day, diagnostics that I added to find the problem, all changed the behaviour. This is exactly the "depends on the build" lottery I described in the first post.

Evidence from my logs (5 s rows, micros() logged next to the stall measurement):

  • Stalls always in the windows 1886 s + n * 4295 s of uptime, and in the rows where they happened micros() was 0x71xxxxxx (for example up=1898 s, micros = 0x71E4DAC2, longest gap 1456 ms; up=1903 s, 1487 ms)
  • No stall outside these windows in any of my logs, over many builds
  • Builds that did not keep the value in a register at the wrong time ran for hours with the same stock 32 MB region (e.g. 12510 s, 8314 s), so a long clean run proves nothing for a given build

3. Minimal reproduction with the FlexSPI2 registers

The sketch reads the first address behind the PSRAM (0x70000000 + external_psram_size MB) from loop(). A BusFault/MemManage handler saves the registers into DMAMEM and resets; after the reboot setup() prints them. USE_FIX 0 is the stock core, USE_FIX 1 includes the fix from section 5.

Code:
#include <Arduino.h>
#define USE_FIX 0                 // 0 = stock core, 1 = with mpu_fix.h
#if USE_FIX
#include "mpu_fix.h"
#endif
extern "C" uint8_t external_psram_size;
extern "C" { extern void (* volatile _VectorsRam[])(void); }

#define FSPI2 0x402A4000UL
#define R(off) (*(volatile uint32_t *)(FSPI2 + (off)))
struct Cap {
  uint32_t magic, t0, cyc, cfsr, bfar, hfsr, mmfar, vec;
  uint32_t mcr0, mcr1, intr, sts0, sts1, sts2, a1cr0, a2cr0, a1cr2, a2cr2, ahbcr, b1cr0, b2cr0, b1cr2, b2cr2;
};
static const uint32_t CAPMAGIC = 0xB05FA5A5UL;
DMAMEM volatile Cap cap;

static void capRegs(uint32_t vec) {
  cap.vec = vec; cap.cyc = ARM_DWT_CYCCNT - cap.t0;
  cap.cfsr = SCB_CFSR; cap.bfar = SCB_BFAR; cap.hfsr = SCB_HFSR; cap.mmfar = SCB_MMFAR;
  cap.mcr0 = R(0x00); cap.mcr1 = R(0x04); cap.intr = R(0x14);
  cap.sts0 = R(0xE0); cap.sts1 = R(0xE4); cap.sts2 = R(0xE8);
  cap.a1cr0 = R(0x60); cap.a2cr0 = R(0x64); cap.a1cr2 = R(0x80); cap.a2cr2 = R(0x84); cap.ahbcr = R(0x0C);
  cap.b1cr0 = R(0x68); cap.b2cr0 = R(0x6C); cap.b1cr2 = R(0x88); cap.b2cr2 = R(0x8C);
  cap.magic = CAPMAGIC;
  arm_dcache_flush_delete((void *)&cap, sizeof(cap));
  SCB_AIRCR = 0x05FA0004;         // reset
  while (1) ;
}
extern "C" void myBusFault(void)  { capRegs(5); }
extern "C" void myMemFault(void)  { capRegs(4); }
extern "C" void myHardFault(void) { capRegs(3); }

static void pr(const char *n, uint32_t v) { Serial.printf("  %-18s 0x%08lX\n", n, (unsigned long)v); }

void setup() {
  Serial.begin(115200);
  uint32_t t = millis();
  while (!Serial && millis() - t < 8000) ;
  delay(300);
  if (cap.magic == CAPMAGIC) {
    Serial.printf("stall: %lu cycles = %.3f s, vector %lu (3 HardFault, 4 MemManage, 5 BusFault)\n",
                  (unsigned long)cap.cyc, (double)cap.cyc / F_CPU_ACTUAL, (unsigned long)cap.vec);
    pr("CFSR", cap.cfsr); pr("BFAR", cap.bfar); pr("MMFAR", cap.mmfar); pr("HFSR", cap.hfsr);
    pr("MCR0", cap.mcr0); pr("MCR1", cap.mcr1); pr("AHBCR", cap.ahbcr); pr("INTR", cap.intr);
    pr("STS0", cap.sts0); pr("STS1", cap.sts1); pr("STS2", cap.sts2);
    pr("FLSHA1CR0", cap.a1cr0); pr("FLSHA2CR0", cap.a2cr0); pr("FLSHA1CR2", cap.a1cr2); pr("FLSHA2CR2", cap.a2cr2);
    pr("FLSHB1CR0", cap.b1cr0); pr("FLSHB2CR0", cap.b2cr0); pr("FLSHB1CR2", cap.b1cr2); pr("FLSHB2CR2", cap.b2cr2);
    cap.magic = 0; arm_dcache_flush_delete((void *)&cap, sizeof(cap));
    return;
  }
  Serial.printf("PSRAM: %u MB. Send any character to read the first address behind it.\n", (unsigned)external_psram_size);
}

static bool started = false;
void loop() {
  if (cap.magic == CAPMAGIC || started) return;
  if (Serial.available()) {
    while (Serial.available()) Serial.read();
    started = true;
    Serial.println("reading..."); Serial.flush();
    _VectorsRam[5] = myBusFault; _VectorsRam[4] = myMemFault; _VectorsRam[3] = myHardFault;
    SCB_SHCSR |= (1UL << 16) | (1UL << 17);   // MEMFAULTENA, BUSFAULTENA
    cap.magic = 0; cap.t0 = ARM_DWT_CYCCNT;
    arm_dcache_flush_delete((void *)&cap, sizeof(cap));
    volatile uint32_t *hole = (volatile uint32_t *)(0x70000000UL + (uint32_t)external_psram_size * 0x100000UL);
    uint32_t v = *hole;
    Serial.printf("read returned 0x%08lX (no fault?)\n", (unsigned long)v);
  }
}

4. Results

Code:
                       stock core (USE_FIX 0)         with fix (USE_FIX 1)
stall                  268431504 cycles = 0.373 s     116 cycles
vector                 5 (BusFault)                   4 (MemManage)
CFSR                   0x00008200 (BFARVALID,PRECISERR)  0x00000082 (MMARVALID,DACCVIOL)
BFAR / MMFAR           0x71000000                     0x71000000
FLEXSPI2_INTR          0x00000440                     0x00000040
                       (bit 6 IPTXWE, bit 10 AHBBUSTIMEOUT) (only IPTXWE)
FLEXSPI2_STS0          0x00000003                     0x00000003
FLEXSPI2_STS1          0x00000000                     0x00000000
FLEXSPI2_STS2          0x00000000                     0x00000000
FLEXSPI2_MCR0          0xFFFF8010                     0xFFFF8010
FLEXSPI2_MCR1          0xFFFFFFFF                     0xFFFFFFFF
                       (AHBBUSWAIT = SEQWAIT = 0xFFFF)
FLEXSPI2_AHBCR         0x00000000                     0x00000000
FLEXSPI2_FLSHA1CR0     0x00002000 (8 MB)              same
FLEXSPI2_FLSHA2CR0     0x00002000 (8 MB)              same
FLEXSPI2_FLSHA1CR2     0x00000605                     same
FLEXSPI2_FLSHA2CR2     0x00000605                     same
                       (ARDSEQID 5, AWRSEQID 6, AWRWAIT 0)
FLEXSPI2_FLSHB1CR0     0x00010000 (64 MB, default)    same
FLEXSPI2_FLSHB2CR0     0x00010000                     same
FLEXSPI2_FLSHB1CR2     0x00000000 (seq index 0)       same
FLEXSPI2_FLSHB2CR2     0x00000000                     same

This matches the explanation given earlier in the thread. The address is behind A1+A2 (8+8 MB), so the access goes to B1/B2, which still hold their power-on defaults (64 MB, read/write sequence index 0). It ends in an AHB bus timeout (INTR bit 10, AHBBUSTIMEOUT; MCR1 AHBBUSWAIT = 0xFFFF), not in an AHB command error (STS1 = 0, INTR bits 3/4 clear). AWRWAIT/AWRWAITUNIT are 0 in A1/A2, so Paul's idea about them does not apply here.

With the region resized, the same read is stopped by the MPU after 116 cycles (MemManage, DACCVIOL, MMFAR = 0x71000000) and never reaches FlexSPI. The FlexSPI2 registers are identical in both runs, only the MPU region differs. So the fault is immediate and deterministic instead of a multi-hundred-millisecond bus hang.

5. The fix (sketch only, core untouched)

This is startup_middle_hook(), which the core calls after the PSRAM is detected and before USB and setup(). It finds the MPU region based at 0x70000000 and sets its SIZE field from external_psram_size. If the core is ever fixed so the size already matches, it does nothing.

Code:
// mpu_fix.h
#include <Arduino.h>
extern "C" uint8_t external_psram_size;
extern "C" FLASHMEM void startup_middle_hook(void) {
  const uint32_t RNR = 0xE000ED98UL, RBAR = 0xE000ED9CUL, RASR = 0xE000EDA0UL;
  int reg = -1;
  uint32_t ra = 0;
  for (int r = 0; r < 16; r++) {                       // find the region based at 0x70000000
    *(volatile uint32_t *)RNR = (uint32_t)r;
    __asm__ volatile ("dsb" ::: "memory");
    uint32_t b = *(volatile uint32_t *)RBAR & 0xFFFFFFE0UL;
    uint32_t a = *(volatile uint32_t *)RASR;
    if (b == 0x70000000UL && (a & 1u)) { reg = r; ra = a; break; }
  }
  if (reg < 0) return;                                 // not found: leave the core setup alone
  uint32_t mb = external_psram_size;
  uint32_t sz = (mb == 0) ? 4u : (mb <= 8 ? 22u : (mb <= 16 ? 23u : 24u));  // 4 = 32 B, 22 = 8 MB, 23 = 16 MB, 24 = 32 MB
  uint32_t na = (ra & ~(0x1Fu << 1)) | (sz << 1);
  if (na == ra) return;                                // already correct
  uint32_t pm;
  __asm__ volatile ("mrs %0, primask" : "=r" (pm));
  __disable_irq();
  uint32_t ctrl = SCB_MPU_CTRL;
  __asm__ volatile ("dmb" ::: "memory");
  SCB_MPU_CTRL = 0;
  *(volatile uint32_t *)RNR = (uint32_t)reg;
  *(volatile uint32_t *)RASR = na;
  SCB_MPU_CTRL = ctrl;
  __asm__ volatile ("dsb" ::: "memory");
  __asm__ volatile ("isb" ::: "memory");
  if (!(pm & 1u)) __enable_irq();
}

To verify at run time, read back the region (RNR/RBAR/RASR): with 16 MB fitted, the region at 0x70000000 should show SIZE field 23 and not 24.

6. Result in the real application

The application with the fix ran 12 h 9 min at 5 Hz (about 30 KB/s from the receiver, SD logging, display) with zero bad frames, receiver buffer drops 0, and the interrupt latency probe constant (62 ms, ISR max 5 ms). The run included nine passes through the micros() = 0x71xxxxxx windows (uptime 1884, 6178, 10473, 14768, 19063, 23358, 27653, 31948, 36243 s), where builds with the stock region regularly stalled in the first window (not every stock build does, see section 2). I will repeat the run once more. There were also six SD write delays of 1.2-2.3 s during the night (a normal consumer card, buffered by the 1 MB ring buffer in PSRAM, no data lost, ISR and probe unaffected). That is a separate, unrelated effect.

7. Suggestions for the core

  • startup.c could derive the MPU region size from external_psram_size (8 MB, 16 MB, or 32 MB only when two 16 MB chips are present) instead of always using 32 MB. That is exactly the "region larger than the memory" situation that is dangerous with speculative accesses.
  • As mentioned earlier in the thread, zeroing CR0 of unused FlexSPI2 devices (A1/A2/B1/B2) would also be advisable, but it is not a complete fix on its own because a flash chip may be fitted on that port.

8. Why 2^28 in the test and 2^30 in the logger

jmarsh's explanation: the memory is marked cacheable, so a speculative access fills a whole 256-bit cache line. The maximum AHB burst is 64 bits, so that is 4 bursts, and each of them runs into the AHB timeout: 4 x 2^28 = 2^30 CPU cycles (1.49 s at 720 MHz, 1.79 s at 600 MHz). That matches my numbers exactly. My reproduction is a single non-speculative word load, which faults after the first timeout (2^28 cycles, 0.373 s). Why the non-speculative access does not behave the same way (cache line fill) is still open, as he says.

Thanks again, this thread solved a problem that had cost me a lot of time.
 
Presumably 24MB is a possibility - one each of 16MB and 8MB PSRAM parts.
Good point about 24 MB (16 MB + 8 MB chips). An MPU region must be a power of two, so 24 MB can not be described exactly by one region. Two ways: a 32 MB region with the subregion-disable bits (SRD) set for the top 8 MB (32 MB / 8 = 4 MB per subregion, six enabled, two disabled), or two regions (16 MB at 0x70000000 plus 8 MB at 0x71000000, both naturally aligned). The SRD variant needs only the existing region, so my sketch-side fix can handle it in the same place. My earlier code would have left the hole between 24 and 32 MB open in that case, so here is the updated version. I can only test the 16 MB case (that is what is on my board), so 8/24/32 MB are untested:

Code:
// mpu_fix.h: resize the FlexSPI2 MPU region (0x70000000) to the PSRAM that is really fitted.
// 24 MB (16 + 8) is not a power of two: use a 32 MB region with the upper subregions disabled (SRD).
#include <Arduino.h>
extern "C" uint8_t external_psram_size;
extern "C" FLASHMEM void startup_middle_hook(void) {
  const uint32_t RNR = 0xE000ED98UL, RBAR = 0xE000ED9CUL, RASR = 0xE000EDA0UL;
  int reg = -1;
  uint32_t ra = 0;
  for (int r = 0; r < 16; r++) {                       // find the region based at 0x70000000
    *(volatile uint32_t *)RNR = (uint32_t)r;
    __asm__ volatile ("dsb" ::: "memory");
    uint32_t b = *(volatile uint32_t *)RBAR & 0xFFFFFFE0UL;
    uint32_t a = *(volatile uint32_t *)RASR;
    if (b == 0x70000000UL && (a & 1u)) { reg = r; ra = a; break; }
  }
  if (reg < 0) return;                                 // not found: leave the core setup alone
  uint32_t mb = external_psram_size;
  uint32_t sz, srd = 0;                                // SIZE: 4 = 32 B, 22 = 8 MB, 23 = 16 MB, 24 = 32 MB
  if (mb == 0)       sz = 4;
  else if (mb <= 8)  sz = 22;
  else if (mb <= 16) sz = 23;
  else {
    sz = 24;                                           // 32 MB region
    if (mb < 32) {                                     // 24 MB: disable the subregions above it
      uint32_t n = (mb + 3) / 4;                       // enabled 4 MB subregions (6 for 24 MB)
      srd = (0xFFu << n) & 0xFFu;                      // bit set = subregion disabled
    }
  }
  uint32_t na = (ra & ~((0x1Fu << 1) | (0xFFu << 8))) | (sz << 1) | (srd << 8);
  if (na == ra) return;                                // already correct
  uint32_t pm;
  __asm__ volatile ("mrs %0, primask" : "=r" (pm));
  __disable_irq();
  uint32_t ctrl = SCB_MPU_CTRL;
  __asm__ volatile ("dmb" ::: "memory");
  SCB_MPU_CTRL = 0;
  *(volatile uint32_t *)RNR = (uint32_t)reg;
  *(volatile uint32_t *)RASR = na;
  SCB_MPU_CTRL = ctrl;
  __asm__ volatile ("dsb" ::: "memory");
  __asm__ volatile ("isb" ::: "memory");
  if (!(pm & 1u)) __enable_irq();
}

So a fix in startup.c should handle the non-power-of-two case the same way (SRD or two regions) instead of just picking the next larger size.
 
This actually makes me realize there may be a simple fix for this after all: just set FLEXSPI2_FLSHA2CR0 to 32MB, always.
- no PSRAM: no real change to what the current code does (leaves FLSHA1CR0 and FLSHA2CR0 at default values)
- 1x 8MB PSRAM: again no real change to current behavior, FLSHA2CR0 is already left at the default value
- 2x 8MB PSRAM: all reads beyond 16MB are guaranteed to go to the second chip, either wrapping the address or returning invalid data. Either option will not result in an AHB timeout.
- any other configuration: same as previous.
 
Before I consider a simple fix to be merged into the official core library, given all this new info is there a reliable way to reproduce this problem? Can it be done with a relatively small program not depending on many libraries and external hardware?

I'd really like to have a test case to verify the fix is effective, and to add to testing on future software releases.
 
Before I consider a simple fix to be merged into the official core library, given all this new info is there a reliable way to reproduce this problem? Can it be done with a relatively small program not depending on many libraries and external hardware?

I'd really like to have a test case to verify the fix is effective, and to add to testing on future software releases.
Paul, yes: a small reproduction exists. It needs only a Teensy 4.1 with less than 32 MB of PSRAM fitted, no libraries and no other hardware (attached below, about 40 lines). It reads 8 words behind the end of the PSRAM and times each read. Results on my board (2 x 8 MB = 16 MB, 720 MHz):

Stock core 1.62.0 (single 32 MB MPU region, FLSHA2CR0 = 0x2000 = 8 MB as set by the core), same test, INTR cleared before the read (INTR = 0x40 before): the first read stalls 268431415 CPU cycles (0.373 s) and ends in a BusFault (BFAR 0x71000040, CFSR 0x8200), FLEXSPI2_INTR = 0x440 afterwards, i.e. bit 10 (AHB bus timeout) is set by this very read; SEQTIMEOUT (bit 11) is clear, STS1 = 0, MCR1 = 0xFFFFFFFF.

jmarsh's change (FLEXSPI2_FLSHA2CR0 = 32 MB, MCR0[MDIS] set while writing it, module enabled again afterwards; MPU left at 32 MB). I cleared FLEXSPI2_INTR first and invalidated the cache line before each read:

Code:
INTR before = 0x40, after clearing = 0x40, FLSHA2CR0 = 0x8000
  0x71000040 -> 0x00000000, 329 cycles
  0x71100040 -> 0x00000000, 331 cycles
  0x71200040 -> 0x00000000, 335 cycles
  0x71300040 -> 0x00000000, 335 cycles
  0x71400040 -> 0x00000000, 838 cycles
  0x71500040 -> 0x00000000, 335 cycles
  0x71600040 -> 0x00000000, 331 cycles
  0x71700040 -> 0x00000000, 331 cycles
FLSHA1CR0 = 0x2000, FLSHA2CR0 = 0x8000, INTR = 0x40, STS1 = 0

So with FLSHA2CR0 = 32 MB all eight reads behind the PSRAM return in about 330 cycles (a real external read, the line was invalidated before), no fault, no timeout (INTR bit 10 stays clear, STS1 = 0). That is almost six orders of magnitude faster than the stock behaviour, so it fixes the stall at its source. The MPU-based variant (region resized to the PSRAM) also works but faults on such an access instead of returning data.

One pitfall for a regression test: in my first attempt I did not clear INTR and did not invalidate the cache line, and got 22 cycles and INTR = 0x440 even with the fix. Most likely a speculative access had timed out earlier (before the register change) and left the flag set and a zero line in the cache. So the test should clear INTR and invalidate the line first, as the attached program does.

Test program (PASS: all reads fast, INTR bit 10 clear; FAIL on the stock core: stall plus BusFault, the CrashReport after the automatic reboot shows BFAR = first address behind the PSRAM):

Code:
#include <Arduino.h>
#include <CrashReport.h>
extern "C" uint8_t external_psram_size;

void setup() {
  Serial.begin(115200);
  uint32_t t = millis();
  while (!Serial && millis() - t < 5000) ;
  delay(300);
  if (CrashReport) Serial.print(CrashReport);
  uint32_t mb = external_psram_size;
  Serial.printf("PSRAM %lu MB, FLSHA1CR0=0x%lX FLSHA2CR0=0x%lX\n", (unsigned long)mb,
                (unsigned long)FLEXSPI2_FLSHA1CR0, (unsigned long)FLEXSPI2_FLSHA2CR0);
  if (mb == 0 || mb >= 32) { Serial.println("nothing to test"); return; }
  FLEXSPI2_INTR = 0xFFFFFFFFUL;
  Serial.flush();
  uint32_t base = 0x70000000UL + mb * 0x100000UL;
  int fail = 0;
  for (int k = 0; k < 8; k++) {
    uint32_t a = base + (uint32_t)k * 0x100000UL + 0x40UL;
    arm_dcache_delete((void *)(a & ~31UL), 32);
    uint32_t t0 = ARM_DWT_CYCCNT;
    uint32_t v = *(volatile uint32_t *)a;
    uint32_t dt = ARM_DWT_CYCCNT - t0;
    Serial.printf("  0x%08lX -> 0x%08lX, %lu cycles\n", (unsigned long)a, (unsigned long)v, (unsigned long)dt);
    if (dt > 1000000UL) fail++;
  }
  uint32_t intr = FLEXSPI2_INTR;
  Serial.printf("FLEXSPI2_INTR = 0x%lX\n", (unsigned long)intr);
  Serial.println((fail || (intr & 0x400)) ? "FAIL" : "PASS");
}
void loop() {}

Speculative variant

In my application the code never dereferences the bad address itself, the stall comes from the CPU. I tried to reproduce that with a tiny program as well: train the branch predictor on "if (cond) sink = *p;" with a valid RAM pointer and cond = 1 (200 times), then call the same function with cond = 0 and p pointing behind the PSRAM, 40 rounds, timing the call with DWT_CYCCNT. Result on the stock core: worst case 14 cycles, no stall. So this simple mispredicted-branch pattern does not trigger the speculative access on the M7 (the branch is probably resolved before the load is issued). In my application the stall only appeared while micros() was in 0x71000000..0x71FFFFFF, so it needs some other instruction sequence that I have not isolated; therefore the direct read above is the reliable test, and the 2^30-cycle stall in my logger (4 x 2^28) matches jmarsh's cache line explanation.
 
This actually makes me realize there may be a simple fix for this after all: just set FLEXSPI2_FLSHA2CR0 to 32MB, always.

How about just leaving it at its 64MB default?

In other words, can this issue be fully solved by just commenting out line 545 in startup.c?

Code:
                        FLEXSPI2_FLSHA2CR0 = size2 << 10;
 
How about just leaving it at its 64MB default?

In other words, can this issue be fully solved by just commenting out line 545 in startup.c?

Code:
                        FLEXSPI2_FLSHA2CR0 = size2 << 10;
Tested: leaving FLEXSPI2_FLSHA2CR0 at its 64 MB reset default works on my board (2 x APS6404L = 16 MB).

Method
Same test as before (sts1_test, stock core, MPU region still 32 MB). The core has already written FLSHA2CR0 = size2 << 10 (0x2000 = 8 MB here). In setup the sketch toggles MCR0[MDIS], writes FLEXSPI2_FLSHA2CR0 = 64 * 1024 (0x10000 = reset value) and clears MDIS again, which gives the same final register state as commenting out line 545 in startup.c. Then it clears INTR and reads 8 addresses behind the PSRAM, 2 MB apart (0x71000040 ... 0x71E00040, i.e. the whole hole up to the end of the 32 MB MPU region), with arm_dcache_delete() on the cache line before each read.

Result
Code:
PSRAM: 16 MB. FLSHA1CR0=0x2000 FLSHA2CR0=0x2000 MCR1=0xFFFFFFFF
INTR parast kustutamist = 0x40, FLSHA2CR0 = 0x10000
  0x71000040 -> 0x00000000, 333 cycles
  0x71200040 -> 0x00000000, 331 cycles
  0x71400040 -> 0x00000000, 335 cycles
  0x71600040 -> 0x00000000, 834 cycles
  0x71800040 -> 0x00000000, 834 cycles
  0x71A00040 -> 0x00000000, 331 cycles
  0x71C00040 -> 0x00000000, 331 cycles
  0x71E00040 -> 0x00000000, 335 cycles
done, no fault. FLSHA1CR0=0x2000 FLSHA2CR0=0x10000 INTR=0x40 STS1=0x0
No stall, no BusFault, INTR bit 10 (AHBBUSTIMEOUT) stays clear. INTR = 0x40 is bit 6 (IPTXWE), which was also set in the MPU fix run and is not an error. Stock core for comparison: 268,431,504 cycles, then BusFault, INTR bit 10 set.

So on this board all three work: jmarsh's 32 MB, the 64 MB default (line 545 removed), and my MPU resize.

Differences
  • With the A2CR0 variants a stray read in the hole just returns data from the second chip (address wraps) instead of faulting, so a bad pointer becomes silent. The MPU resize gives an immediate MemManage fault (DACCVIOL, MMFAR = 0x71000000, 116 cycles), which is easier to debug.
  • I could only test the 16 MB (two chip) case. With a single 8 MB chip, A2 would stay at 64 MB with no chip behind chip select 2, so someone with an 8 MB board should check that case before this goes into the core.
  • I have not tested writes into the hole.

My logger is still running the MPU resize (mpu_fix.h); two clean overnight runs (12 h 9 min and 8 h 35 min, 16 windows with micros() in 0x71xxxxxx, 0 bad frames) and a third is running now. I can run the same overnight test with the line 545 variant if that helps.
 
How about just leaving it at its 64MB default?

In other words, can this issue be fully solved by just commenting out line 545 in startup.c?

Code:
                        FLEXSPI2_FLSHA2CR0 = size2 << 10;
If the second chip is absent or PSRAM: yes.
If the second chip is flash and the combined sum of both chips is smaller than 32MB: no, because LittleFS will overwrite FLEXSPI2_FLSHA2CR0.
 
Last edited:
Ok, just to make sure I understand this, it seems the fundamental problem is Cortex M7 speculatively fetches beyond actually accessed memory.

I have seen mention about the cache controller speculatively fetching the next row after what the program actually used. I'm a bit skeptical about the explanation of merely having an address in a register with no LD or ST instruction actually using it. Whatever the reason, what matters is understanding how far beyond the end of actually accessed memory we need to anticipate?
 
Back
Top