machine/flash: remove FlashBuffer, modify flash example to use BlockDevice interface

Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
deadprogram
2023-05-09 22:03:11 +02:00
committed by Ron Evans
parent 6435f62dcc
commit b56a263d0d
2 changed files with 38 additions and 90 deletions
-79
View File
@@ -64,82 +64,3 @@ type BlockDevice interface {
// EraseBlockSize to map addresses to blocks.
EraseBlocks(start, len int64) error
}
// FlashBuffer implements the ReadWriteCloser interface using the BlockDevice interface.
type FlashBuffer struct {
b BlockDevice
// start is actual address
start uintptr
// offset is relative to start
offset uintptr
}
// OpenFlashBuffer opens a FlashBuffer.
func OpenFlashBuffer(b BlockDevice, address uintptr) *FlashBuffer {
return &FlashBuffer{b: b, start: address}
}
// Read data from a FlashBuffer.
func (fl *FlashBuffer) Read(p []byte) (n int, err error) {
n, err = fl.b.ReadAt(p, int64(fl.offset))
fl.offset += uintptr(n)
return
}
// Write data to a FlashBuffer.
func (fl *FlashBuffer) Write(p []byte) (n int, err error) {
// any new pages needed?
// NOTE probably will not work as expected if you try to write over page boundary
// of pages with different sizes.
pagesize := uintptr(fl.b.EraseBlockSize())
// calculate currentPageBlock relative to fl.start, meaning that
// block 0 -> fl.start
// block 1 -> fl.start + pagesize
// block 2 -> fl.start + pagesize*2
// ...
currentPageBlock := (fl.start + fl.offset - FlashDataStart()) + (pagesize-1)/pagesize
lastPageBlockNeeded := (fl.start + fl.offset + uintptr(len(p)) - FlashDataStart()) + (pagesize-1)/pagesize
// erase enough blocks to hold the data
if err := fl.b.EraseBlocks(int64(currentPageBlock), int64(lastPageBlockNeeded-currentPageBlock)); err != nil {
return 0, err
}
// write the data
for i := 0; i < len(p); i += int(pagesize) {
var last int = i + int(pagesize)
if i+int(pagesize) > len(p) {
last = len(p)
}
_, err := fl.b.WriteAt(p[i:last], int64(fl.offset))
if err != nil {
return 0, err
}
fl.offset += uintptr(len(p[i:last]))
}
return len(p), nil
}
// Close the FlashBuffer.
func (fl *FlashBuffer) Close() error {
return nil
}
// Seek implements io.Seeker interface, but with limitations.
// You can only seek relative to the start.
// Also, you cannot use seek before write operations, only read.
func (fl *FlashBuffer) Seek(offset int64, whence int) (int64, error) {
if whence != io.SeekStart {
panic("you can only Seek relative to Start")
}
fl.offset = uintptr(offset)
return offset, nil
}