forked from M-Labs/zynq-rs
1
0
Fork 0
zynq-rs/libcortex_a9/src/uncached.rs

66 lines
1.8 KiB
Rust
Raw Normal View History

2020-06-15 05:50:39 +08:00
use core::{
ops::{Deref, DerefMut},
mem::{align_of, size_of},
};
2020-06-18 06:51:13 +08:00
use alloc::alloc::{dealloc, Layout, LayoutErr};
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
2020-06-18 06:51:13 +08:00
pub fn new<F: Fn() -> T>(len: usize, default: F) -> Result<Self, LayoutErr> {
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) {
L1Table::get()
.update(page_start as *const (), |l1_section| {
l1_section.cacheable = false;
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
}
}