Browse Source

bpf: make xdp maps functions safe

Values in those map are small enough to return copied values instead of
reference to values.
Tuetuopay 1 year ago
parent
commit
db49633073

+ 2 - 2
bpf/aya-bpf/src/maps/xdp/dev_map.rs

@@ -46,13 +46,13 @@ impl DevMap {
     }
 
     #[inline(always)]
-    pub fn get(&self, index: u32) -> Option<u32> {
+    pub fn get(&self, index: u32) -> Option<bpf_devmap_val> {
         unsafe {
             let value = bpf_map_lookup_elem(
                 self.def.get() as *mut _,
                 &index as *const _ as *const c_void,
             );
-            NonNull::new(value as *mut u32).map(|p| *p.as_ref())
+            NonNull::new(value as *mut bpf_devmap_val).map(|p| *p.as_ref())
         }
     }
 

+ 8 - 8
bpf/aya-bpf/src/maps/xdp/dev_map_hash.rs

@@ -46,21 +46,21 @@ impl DevMapHash {
     }
 
     #[inline(always)]
-    pub unsafe fn get(&self, index: u32) -> Option<&bpf_devmap_val> {
-        let value = bpf_map_lookup_elem(
-            self.def.get() as *mut _,
-            &index as *const _ as *const c_void,
-        );
-        NonNull::new(value as *mut bpf_devmap_val).map(|p| p.as_ref())
+    pub fn get(&self, key: u32) -> Option<bpf_devmap_val> {
+        unsafe {
+            let value =
+                bpf_map_lookup_elem(self.def.get() as *mut _, &key as *const _ as *const c_void);
+            NonNull::new(value as *mut bpf_devmap_val).map(|p| *p.as_ref())
+        }
     }
 
     #[inline(always)]
-    pub fn redirect(&self, index: u32, flags: u64) -> u32 {
+    pub fn redirect(&self, key: u32, flags: u64) -> u32 {
         unsafe {
             // Return XDP_REDIRECT on success, or the value of the two lower bits of the flags
             // argument on error. Thus I have no idea why it returns a long (i64) instead of
             // something saner, hence the unsigned_abs.
-            bpf_redirect_map(self.def.get() as *mut _, index.into(), flags).unsigned_abs() as u32
+            bpf_redirect_map(self.def.get() as *mut _, key.into(), flags).unsigned_abs() as u32
         }
     }
 }

+ 8 - 7
bpf/aya-bpf/src/maps/xdp/xsk_map.rs

@@ -46,13 +46,14 @@ impl XskMap {
     }
 
     #[inline(always)]
-    pub unsafe fn get(&self, index: u32) -> Option<&bpf_xdp_sock> {
-        let value = bpf_map_lookup_elem(
-            self.def.get() as *mut _,
-            &index as *const _ as *const c_void,
-        );
-        // FIXME: alignment
-        NonNull::new(value as *mut bpf_xdp_sock).map(|p| p.as_ref())
+    pub fn get(&self, index: u32) -> Option<u32> {
+        unsafe {
+            let value = bpf_map_lookup_elem(
+                self.def.get() as *mut _,
+                &index as *const _ as *const c_void,
+            );
+            NonNull::new(value as *mut bpf_xdp_sock).map(|p| p.as_ref().queue_id)
+        }
     }
 
     #[inline(always)]