Skip to content

Commit 5e6d3d8

Browse files
hoshinolinajannau
authored andcommitted
rust: kernel: Add simple siphash abstraction
This allows Rust code to use the Hasher interface with the kernel siphash implementation. Signed-off-by: Asahi Lina <lina@asahilina.net>
1 parent d461380 commit 5e6d3d8

5 files changed

Lines changed: 52 additions & 0 deletions

File tree

rust/bindings/bindings_helper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include <linux/poll.h>
3232
#include <linux/property.h>
3333
#include <linux/refcount.h>
34+
#include <linux/siphash.h>
3435
#include <linux/sched.h>
3536
#include <linux/security.h>
3637
#include <linux/slab.h>

rust/helpers/helpers.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
#include "refcount.c"
3030
#include "security.c"
3131
#include "signal.c"
32+
#include "siphash.c"
3233
#include "slab.c"
3334
#include "spinlock.c"
3435
#include "task.c"

rust/helpers/siphash.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
#include <linux/siphash.h>
4+
5+
u64 rust_helper_siphash(const void *data, size_t len,
6+
const siphash_key_t *key)
7+
{
8+
return siphash(data, len, key);
9+
}

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ pub mod rbtree;
7777
pub mod revocable;
7878
pub mod security;
7979
pub mod seq_file;
80+
pub mod siphash;
8081
pub mod sizes;
8182
mod static_assert;
8283
#[doc(hidden)]

rust/kernel/siphash.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! A core::hash::Hasher wrapper for the kernel siphash implementation.
4+
//!
5+
//! This module allows Rust code to use the kernel's siphash implementation
6+
//! to hash Rust objects.
7+
8+
use core::hash::Hasher;
9+
10+
/// A Hasher implementation that uses the kernel siphash implementation.
11+
#[derive(Default)]
12+
pub struct SipHasher {
13+
// SipHash state is 4xu64, but the Linux implementation
14+
// doesn't expose incremental hashing so let's just chain
15+
// individual SipHash calls for now, which return a u64
16+
// hash.
17+
state: u64,
18+
}
19+
20+
impl SipHasher {
21+
/// Create a new SipHasher with zeroed state.
22+
pub fn new() -> Self {
23+
SipHasher { state: 0 }
24+
}
25+
}
26+
27+
impl Hasher for SipHasher {
28+
fn finish(&self) -> u64 {
29+
self.state
30+
}
31+
32+
fn write(&mut self, bytes: &[u8]) {
33+
let key = bindings::siphash_key_t {
34+
key: [self.state, 0],
35+
};
36+
37+
// SAFETY: Safe to call on a valid slice
38+
self.state = unsafe { bindings::siphash(bytes.as_ptr() as *const _, bytes.len(), &key) };
39+
}
40+
}

0 commit comments

Comments
 (0)