Skip to content

Fix asm::delay() variability due to alignment #587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 14, 2025

Conversation

ianrrees
Copy link
Contributor

@ianrrees ianrrees commented Apr 14, 2025

While testing a new clocking API in atsamd-rs, we encountered a very strange behaviour which took some time to track down - seemingly innocuous changes (eg, enabling features that weren't used by the firmware, or adding a debug call) would result in wildly different execution speed of a test program. In the context of testing at a new clocking API, at least two of us assumed the issue was down to the clock speed changing, but in fact it was the number of cycles of delay we were getting for calls to asm::delay(). This turns out to be a result of the Cortex-M4 taking a variable number of cycles to execute a conditional branch, based on the alignment of the target.

Although the method is strictly conforming to the documentation by delaying /at least/ N cycles, the sensitivity to alignment is quite surprising. This PR aligns the loop target, to remove this surprising behaviour.

Resolves part of #151

@jonathanpallant
Copy link
Contributor

I don't love adding up to six bytes of padding to an inline function, but I think it's a price worth paying to avoid this kind of confusion.

@ianrrees
Copy link
Contributor Author

I suppose once fn_align is stable, that could be another option although it probably won't make much difference in practice.

@adamgreig
Copy link
Member

Thanks for investigating and for this improvement, I think it's well worth the tradeoff to get better determinism.

@adamgreig adamgreig added this pull request to the merge queue Apr 14, 2025
Merged via the queue into rust-embedded:master with commit 5bf528a Apr 14, 2025
11 checks passed
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