zynq-rs/libcortex_a9/src/uncached.rs

68 lines
1.9 KiB
Rust
Raw Permalink Normal View History

2020-06-15 05:50:39 +08:00
use core::{
ops::{Deref, DerefMut},
mem::{align_of, size_of},
};
use alloc::alloc::{dealloc, Layout, LayoutError};
2020-06-15 05:50:39 +08:00
use crate::mmu::{L1_PAGE_SIZE, L1Table};
2020-06-18 06:51:13 +08:00
pub struct UncachedSlice<T: 'static> {
2020-06-15 05:50:39 +08:00
layout: Layout,
2020-06-18 06:51:13 +08:00
slice: &'static mut [T],
2020-06-15 05:50:39 +08:00
}
2020-06-18 06:51:13 +08:00
impl<T> UncachedSlice<T> {
2020-06-15 05:50:39 +08:00
/// allocates in chunks of 1 MB
pub fn new<F: Fn() -> T>(len: usize, default: F) -> Result<Self, LayoutError> {
2020-06-15 05:50:39 +08:00
// round to full pages
2020-06-18 06:51:13 +08:00
let size = ((len * size_of::<T>() - 1) | (L1_PAGE_SIZE - 1)) + 1;
2020-06-15 05:50:39 +08:00
let align = align_of::<T>()
.max(L1_PAGE_SIZE);
let layout = Layout::from_size_align(size, align)?;
let ptr = unsafe { alloc::alloc::alloc(layout).cast::<T>() };
let start = ptr as usize;
2020-06-18 06:51:13 +08:00
assert_eq!(start & (L1_PAGE_SIZE - 1), 0);
2020-06-15 05:50:39 +08:00
for page_start in (start..(start + size)).step_by(L1_PAGE_SIZE) {
// non-shareable device
2020-06-15 05:50:39 +08:00
L1Table::get()
.update(page_start as *const (), |l1_section| {
l1_section.tex = 0b10;
l1_section.cacheable = true;
2020-06-15 05:50:39 +08:00
l1_section.bufferable = false;
});
}
2020-06-18 06:51:13 +08:00
let slice = unsafe { core::slice::from_raw_parts_mut(ptr, len) };
// verify size
assert!(unsafe { slice.get_unchecked(len) } as *const _ as usize <= start + size);
2020-06-15 05:50:39 +08:00
// initialize
2020-06-18 06:51:13 +08:00
for e in slice.iter_mut() {
*e = default();
2020-06-15 05:50:39 +08:00
}
2020-06-18 06:51:13 +08:00
Ok(UncachedSlice { layout, slice })
2020-06-15 05:50:39 +08:00
}
}
2020-06-18 06:51:13 +08:00
/// Does not yet mark the pages cachable again
impl<T> Drop for UncachedSlice<T> {
2020-06-15 05:50:39 +08:00
fn drop(&mut self) {
unsafe {
2020-06-18 06:51:13 +08:00
dealloc(self.slice.as_mut_ptr() as *mut _ as *mut u8, self.layout);
2020-06-15 05:50:39 +08:00
}
}
}
2020-06-18 06:51:13 +08:00
impl<T> Deref for UncachedSlice<T> {
type Target = [T];
2020-06-15 05:50:39 +08:00
fn deref(&self) -> &Self::Target {
2020-06-18 06:51:13 +08:00
self.slice
2020-06-15 05:50:39 +08:00
}
}
2020-06-18 06:51:13 +08:00
impl<T> DerefMut for UncachedSlice<T> {
2020-06-15 05:50:39 +08:00
fn deref_mut(&mut self) -> &mut Self::Target {
2020-06-18 06:51:13 +08:00
self.slice
2020-06-15 05:50:39 +08:00
}
}