github.com/usbarmory/tamago@v0.0.0-20240508072735-8612bbe1e454/dma/block.go (about) 1 // First-fit memory allocator for DMA buffers 2 // https://github.com/usbarmory/tamago 3 // 4 // Copyright (c) WithSecure Corporation 5 // https://foundry.withsecure.com 6 // 7 // Use of this source code is governed by the license 8 // that can be found in the LICENSE file. 9 10 package dma 11 12 import ( 13 "reflect" 14 "unsafe" 15 ) 16 17 type block struct { 18 // pointer address 19 addr uint 20 // buffer size 21 size uint 22 // distinguish regular (`Alloc`/`Free`) and reserved 23 // (`Reserve`/`Release`) blocks. 24 res bool 25 } 26 27 func (b *block) read(off uint, buf []byte) { 28 var ptr unsafe.Pointer 29 30 ptr = unsafe.Add(ptr, b.addr+off) 31 mem := unsafe.Slice((*byte)(ptr), len(buf)) 32 33 copy(buf, mem) 34 } 35 36 func (b *block) write(off uint, buf []byte) { 37 var ptr unsafe.Pointer 38 39 ptr = unsafe.Add(ptr, b.addr+off) 40 mem := unsafe.Slice((*byte)(ptr), len(buf)) 41 42 copy(mem, buf) 43 } 44 45 func (b *block) slice() (buf []byte) { 46 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) 47 hdr.Data = uintptr(unsafe.Pointer(uintptr(b.addr))) 48 hdr.Len = int(b.size) 49 hdr.Cap = hdr.Len 50 51 return 52 }