Skip to content

Commit

Permalink
Implement THIS_MODULE.
Browse files Browse the repository at this point in the history
Closes #15
Fixes #10
  • Loading branch information
alex committed Jan 22, 2021
1 parent d8e8a16 commit 6e23284
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
5 changes: 2 additions & 3 deletions rust/kernel/chrdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl Builder {
self
}

pub fn build(self) -> KernelResult<Registration> {
pub fn build(self, this_module: &'static crate::ThisModule) -> KernelResult<Registration> {
let mut dev: bindings::dev_t = 0;
let res = unsafe {
bindings::alloc_chrdev_region(
Expand All @@ -58,8 +58,7 @@ impl Builder {
for (i, file_op) in self.file_ops.iter().enumerate() {
unsafe {
bindings::cdev_init(&mut cdevs[i], *file_op);
// TODO: proper `THIS_MODULE` handling
cdevs[i].owner = core::ptr::null_mut();
cdevs[i].owner = this_module.0;
let rc = bindings::cdev_add(&mut cdevs[i], dev + i as bindings::dev_t, 1);
if rc != 0 {
// Clean up the ones that were allocated.
Expand Down
12 changes: 12 additions & 0 deletions rust/kernel/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ pub trait KernelModule: Sized + Sync {
fn init() -> KernelResult<Self>;
}

/// An instance equivalent to `THIS_MODULE` in C code.
pub struct ThisModule(*mut bindings::module);

// Safe because THIS_MODULE may be used from all threads within a module.
unsafe impl Sync for ThisModule {}

impl ThisModule {
pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
ThisModule(ptr)
}
}

extern "C" {
fn rust_helper_BUG() -> !;
}
Expand Down
5 changes: 5 additions & 0 deletions rust/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,11 @@ pub fn module(ts: TokenStream) -> TokenStream {
"
static mut __MOD: Option<{type_}> = None;
#[cfg(MODULE)]
static THIS_MODULE: kernel::ThisModule = unsafe { kernel::ThisModule::from_ptr(&mut kernel::bindings::__this_module) };
#[cfg(not(MODULE))]
static THIS_MODULE: kernel::ThisModule = unsafe { kernel::ThisModule::from_ptr(core::ptr::null_mut()) };
// Loadable modules need to export the `{{init,cleanup}}_module` identifiers
#[cfg(MODULE)]
#[no_mangle]
Expand Down

0 comments on commit 6e23284

Please sign in to comment.