|
| 1 | +//! (TODO) Bypass cache |
| 2 | +//! |
| 3 | +//! Todo: verify this module! |
| 4 | +
|
| 5 | +use core::slice; |
| 6 | + |
| 7 | +/// Convert a buffer or a pointer into ones with uncached address. |
| 8 | +/// |
| 9 | +/// Section 3.4.1, Kendryte K210 Datasheet |
| 10 | +pub fn uncached<T: Uncache>(buf: T) -> T { |
| 11 | + buf.uncache() |
| 12 | +} |
| 13 | + |
| 14 | +/// Uncacheable buffer or pointer. |
| 15 | +pub trait Uncache { |
| 16 | + /// Convert this buffer or pointer to uncached addressed ones |
| 17 | + fn uncache(self) -> Self; |
| 18 | +} |
| 19 | + |
| 20 | +impl<T> Uncache for &T { |
| 21 | + #[inline] |
| 22 | + fn uncache(self) -> Self { |
| 23 | + let addr = self as *const T as usize; |
| 24 | + assert_addr_cached(addr); |
| 25 | + // note(unsafe): safe for source address is safe |
| 26 | + unsafe { &*((addr - 0x4000_0000) as *const T) } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +impl<T> Uncache for &mut T { |
| 31 | + #[inline] |
| 32 | + fn uncache(self) -> Self { |
| 33 | + let addr = self as *mut T as usize; |
| 34 | + assert_addr_cached(addr); |
| 35 | + // note(unsafe): safe for source address is safe |
| 36 | + unsafe { &mut *((addr - 0x4000_0000) as *mut T) } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl<T> Uncache for &[T] { |
| 41 | + #[inline] |
| 42 | + fn uncache(self) -> Self { |
| 43 | + let addr = self.as_ptr() as usize; |
| 44 | + assert_addr_cached(addr); |
| 45 | + let new_ptr = (addr - 0x4000_0000) as *const T; |
| 46 | + // note(unsafe): source address is safe; passing ownership |
| 47 | + unsafe { slice::from_raw_parts(new_ptr, self.len()) } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<T> Uncache for &mut [T] { |
| 52 | + #[inline] |
| 53 | + fn uncache(self) -> Self { |
| 54 | + let addr = self.as_ptr() as usize; |
| 55 | + assert_addr_cached(addr); |
| 56 | + let new_ptr = (addr - 0x4000_0000) as *mut T; |
| 57 | + // note(unsafe): source address is safe; passing ownership |
| 58 | + unsafe { slice::from_raw_parts_mut(new_ptr, self.len()) } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl<T> Uncache for *const T { |
| 63 | + #[inline] |
| 64 | + fn uncache(self) -> Self { |
| 65 | + assert_addr_cached(self as usize); |
| 66 | + (self as usize - 0x4000_0000) as *const T |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +impl<T> Uncache for *mut T { |
| 71 | + #[inline] |
| 72 | + fn uncache(self) -> Self { |
| 73 | + assert_addr_cached(self as usize); |
| 74 | + (self as usize - 0x4000_0000) as *mut T |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +#[inline] |
| 79 | +fn assert_addr_cached(addr: usize) { |
| 80 | + assert!(addr <= 0x805F_FFFF && addr >= 0x8000_0000); |
| 81 | +} |
0 commit comments