Skip to content

Optimize flash writes on SAMD51 #4908

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
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions src/machine/machine_atsamd51.go
Original file line number Diff line number Diff line change
Expand Up @@ -2163,7 +2163,7 @@ func (f flashBlockDevice) ReadAt(p []byte, off int64) (n int, err error) {
}

// WriteAt writes the given number of bytes to the block device.
// Only word (32 bits) length data can be programmed.
// Data is written to the page buffer in 4-byte chunks, then saved to flash memory.
// See SAM-D5x-E5x-Family-Data-Sheet-DS60001507.pdf page 591-592.
// If the length of p is not long enough it will be padded with 0xFF bytes.
// This method assumes that the destination is already erased.
Expand All @@ -2185,16 +2185,13 @@ func (f flashBlockDevice) WriteAt(p []byte, off int64) (n int, err error) {
waitWhileFlashBusy()

for j := 0; j < len(padded); j += int(f.WriteBlockSize()) {
// write first word using double-word low order word
*(*uint32)(unsafe.Pointer(address)) = binary.LittleEndian.Uint32(padded[j : j+int(f.WriteBlockSize()/2)])

// write second word using double-word high order word
*(*uint32)(unsafe.Add(unsafe.Pointer(address), uintptr(f.WriteBlockSize())/2)) = binary.LittleEndian.Uint32(padded[j+int(f.WriteBlockSize()/2) : j+int(f.WriteBlockSize())])

waitWhileFlashBusy()
// page buffer is 512 bytes long, but only 4 bytes can be written at once
for k := 0; k < int(f.WriteBlockSize()); k += 4 {
*(*uint32)(unsafe.Pointer(address + uintptr(k))) = binary.LittleEndian.Uint32(padded[j+k : j+k+4])
}

sam.NVMCTRL.SetADDR(uint32(address))
sam.NVMCTRL.CTRLB.Set(sam.NVMCTRL_CTRLB_CMD_WQW | (sam.NVMCTRL_CTRLB_CMDEX_KEY << sam.NVMCTRL_CTRLB_CMDEX_Pos))
sam.NVMCTRL.CTRLB.Set(sam.NVMCTRL_CTRLB_CMD_WP | (sam.NVMCTRL_CTRLB_CMDEX_KEY << sam.NVMCTRL_CTRLB_CMDEX_Pos))

waitWhileFlashBusy()

Expand All @@ -2213,7 +2210,7 @@ func (f flashBlockDevice) Size() int64 {
return int64(FlashDataEnd() - FlashDataStart())
}

const writeBlockSize = 8
const writeBlockSize = 512

// WriteBlockSize returns the block size in which data can be written to
// memory. It can be used by a client to optimize writes, non-aligned writes
Expand Down