Skip to content

Optimize flash writes on SAMD21 #4905

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

Conversation

mateusznowakdev
Copy link
Contributor

@mateusznowakdev mateusznowakdev commented May 22, 2025

In its current implementation, the machine.Flash.WriteAt() function on SAMD21 will copy data to the internal flash memory in 4-byte chunks -- even if the page buffer is actually 64 bytes long for all chip variants.

The existing code can be improved to get ~12x faster write speeds, which will be useful when #4844 (USB mass storage) is merged and SAMD21 support is added.

I get these results when writing 4kB of data:

at 48MHz at 8MHz
before 229ms 261ms
after 17ms 23ms

This will also make sure that no more than 4 writes are performed to the same flash row (256 bytes long). The datasheet says:

on this flash technology, a max number of 8 consecutive write is allowed per row. Once this number is reached, a row erase is mandatory.

Based on my long-term testing (working on a device that reads and writes a lot), it seems to work as expected. Data is saved to the expected memory location and can be read after the reset. It would be nice if someone else could take a look.

Of course, this is a breaking change. If some application assumes the block size of 4, it will not work properly.

There's also SAMD51 that could benefit from similar change, but I don't have any device to test with.

References:

@deadprogram
Copy link
Member

Thank you very much for this improvement @mateusznowakdev

Of course, this is a breaking change. If some application assumes the block size of 4, it will not work properly.

External consumers should be using the WriteBlockSize() so should not impact any well-behaved code.

I agree that similar change for SAMD51 would benefit. I can test it if you wanted to make this change in another PR.

In any case, thanks again for working on this. Now merging.

@deadprogram deadprogram merged commit 3eeffca into tinygo-org:dev May 23, 2025
19 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.

2 participants