forked from M-Labs/artiq-zynq
add reference counting functions
This commit is contained in:
@@ -118,8 +118,9 @@ pub fn resolve(required: &[u8]) -> Option<u32> {
|
||||
api!(i2c_read = i2c::read),
|
||||
api!(i2c_switch_select = i2c::switch_select),
|
||||
|
||||
// dynamic memory allocation
|
||||
api!(nac3_free = mem::nac3_free),
|
||||
// dynamic memory allocation and reference counting
|
||||
api!(nac3_rc_incr = mem::nac3_rc_incr),
|
||||
api!(nac3_rc_decr = mem::nac3_rc_decr),
|
||||
api!(nac3_malloc = mem::nac3_malloc),
|
||||
|
||||
// subkernel
|
||||
|
||||
@@ -2,18 +2,37 @@ use alloc::alloc::{Layout, alloc, dealloc};
|
||||
use core::mem;
|
||||
|
||||
pub unsafe extern "C" fn nac3_malloc(size: usize) -> *mut u8 {
|
||||
let ptr = alloc(Layout::from_size_align_unchecked(size + mem::size_of::<usize>(), 8));
|
||||
let ptr = alloc(
|
||||
Layout::from_size_align_unchecked(size + 2 * mem::size_of::<usize>(), 8)
|
||||
);
|
||||
let size_ptr = ptr.cast::<usize>();
|
||||
*size_ptr = size;
|
||||
|
||||
ptr.add(mem::size_of::<usize>())
|
||||
let rc_ptr = size_ptr.add(1);
|
||||
*rc_ptr = 0;
|
||||
|
||||
rc_ptr.add(1).cast()
|
||||
}
|
||||
|
||||
pub unsafe extern "C" fn nac3_free(ptr: *mut u8) {
|
||||
let size_ptr = ptr.sub(mem::size_of::<usize>()).cast::<usize>();
|
||||
pub unsafe extern "C" fn nac3_rc_incr(ptr: *mut u8) {
|
||||
let ptr = ptr.cast::<usize>().sub(1);
|
||||
*ptr += 1;
|
||||
}
|
||||
|
||||
pub unsafe extern "C" fn nac3_rc_decr(ptr: *mut u8) {
|
||||
let rc_ptr = ptr.cast::<usize>().sub(1);
|
||||
*rc_ptr -= 1;
|
||||
|
||||
if *ptr == 0 {
|
||||
nac3_free(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn nac3_free(ptr: *mut u8) {
|
||||
let size_ptr = ptr.sub(2 * mem::size_of::<usize>()).cast::<usize>();
|
||||
|
||||
dealloc(
|
||||
size_ptr.cast::<u8>(),
|
||||
Layout::from_size_align_unchecked(*size_ptr + mem::size_of::<usize>(), 8),
|
||||
Layout::from_size_align_unchecked(*size_ptr + 2 * mem::size_of::<usize>(), 8),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user