per_cpu_array.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. use core::{cell::UnsafeCell, marker::PhantomData, mem, ptr::NonNull};
  2. use aya_bpf_cty::c_void;
  3. use crate::{
  4. bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_PERCPU_ARRAY},
  5. helpers::bpf_map_lookup_elem,
  6. maps::PinningType,
  7. };
  8. #[repr(transparent)]
  9. pub struct PerCpuArray<T> {
  10. def: UnsafeCell<bpf_map_def>,
  11. _t: PhantomData<T>,
  12. }
  13. unsafe impl<T: Sync> Sync for PerCpuArray<T> {}
  14. impl<T> PerCpuArray<T> {
  15. pub const fn with_max_entries(max_entries: u32, flags: u32) -> PerCpuArray<T> {
  16. PerCpuArray {
  17. def: UnsafeCell::new(bpf_map_def {
  18. type_: BPF_MAP_TYPE_PERCPU_ARRAY,
  19. key_size: mem::size_of::<u32>() as u32,
  20. value_size: mem::size_of::<T>() as u32,
  21. max_entries,
  22. map_flags: flags,
  23. id: 0,
  24. pinning: PinningType::None as u32,
  25. }),
  26. _t: PhantomData,
  27. }
  28. }
  29. pub const fn pinned(max_entries: u32, flags: u32) -> PerCpuArray<T> {
  30. PerCpuArray {
  31. def: UnsafeCell::new(bpf_map_def {
  32. type_: BPF_MAP_TYPE_PERCPU_ARRAY,
  33. key_size: mem::size_of::<u32>() as u32,
  34. value_size: mem::size_of::<T>() as u32,
  35. max_entries,
  36. map_flags: flags,
  37. id: 0,
  38. pinning: PinningType::ByName as u32,
  39. }),
  40. _t: PhantomData,
  41. }
  42. }
  43. #[inline(always)]
  44. pub fn get(&self, index: u32) -> Option<&T> {
  45. unsafe {
  46. // FIXME: alignment
  47. self.lookup(index).map(|p| p.as_ref())
  48. }
  49. }
  50. #[inline(always)]
  51. pub fn get_mut(&self, index: u32) -> Option<&mut T> {
  52. unsafe {
  53. // FIXME: alignment
  54. self.lookup(index).map(|mut p| p.as_mut())
  55. }
  56. }
  57. #[inline(always)]
  58. unsafe fn lookup(&self, index: u32) -> Option<NonNull<T>> {
  59. let ptr = bpf_map_lookup_elem(
  60. self.def.get() as *mut _,
  61. &index as *const _ as *const c_void,
  62. );
  63. NonNull::new(ptr as *mut T)
  64. }
  65. }