Skip to content

rust/kernel: chrdev: remove unnecessary pinning #304

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 8 additions & 36 deletions rust/kernel/chrdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
//!
//! Reference: <https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#char-devices>

use alloc::boxed::Box;
use core::convert::TryInto;
use core::marker::PhantomPinned;
use core::pin::Pin;

use crate::bindings;
use crate::c_types;
Expand Down Expand Up @@ -80,12 +77,11 @@ struct RegistrationInner<const N: usize> {
dev: bindings::dev_t,
used: usize,
cdevs: [Option<Cdev>; N],
_pin: PhantomPinned,
}

/// Character device registration.
///
/// May contain up to a fixed number (`N`) of devices. Must be pinned.
/// May contain up to a fixed number (`N`) of devices.
pub struct Registration<const N: usize> {
name: &'static CStr,
minors_start: u16,
Expand All @@ -97,12 +93,6 @@ impl<const N: usize> Registration<{ N }> {
/// Creates a [`Registration`] object for a character device.
///
/// This does *not* register the device: see [`Self::register()`].
///
/// This associated function is intended to be used when you need to avoid
/// a memory allocation, e.g. when the [`Registration`] is a member of
/// a bigger structure inside your [`crate::KernelModule`] instance. If you
/// are going to pin the registration right away, call
/// [`Self::new_pinned()`] instead.
pub fn new(
name: &'static CStr,
minors_start: u16,
Expand All @@ -116,60 +106,42 @@ impl<const N: usize> Registration<{ N }> {
}
}

/// Creates a pinned [`Registration`] object for a character device.
///
/// This does *not* register the device: see [`Self::register()`].
pub fn new_pinned(
name: &'static CStr,
minors_start: u16,
this_module: &'static crate::ThisModule,
) -> Result<Pin<Box<Self>>> {
Ok(Pin::from(Box::try_new(Self::new(
name,
minors_start,
this_module,
))?))
}

/// Registers a character device.
///
/// You may call this once per device type, up to `N` times.
pub fn register<T: file_operations::FileOpener<()>>(self: Pin<&mut Self>) -> Result {
// SAFETY: We must ensure that we never move out of `this`.
let this = unsafe { self.get_unchecked_mut() };
if this.inner.is_none() {
pub fn register<T: file_operations::FileOpener<()>>(&mut self) -> Result {
if self.inner.is_none() {
let mut dev: bindings::dev_t = 0;
// SAFETY: Calling unsafe function. `this.name` has `'static`
// lifetime.
let res = unsafe {
bindings::alloc_chrdev_region(
&mut dev,
this.minors_start.into(),
self.minors_start.into(),
N.try_into()?,
this.name.as_char_ptr(),
self.name.as_char_ptr(),
)
};
if res != 0 {
return Err(Error::from_kernel_errno(res));
}
const NONE: Option<Cdev> = None;
this.inner = Some(RegistrationInner {
self.inner = Some(RegistrationInner {
dev,
used: 0,
cdevs: [NONE; N],
_pin: PhantomPinned,
});
}

let mut inner = this.inner.as_mut().unwrap();
let mut inner = self.inner.as_mut().unwrap();
if inner.used == N {
return Err(Error::EINVAL);
}

// SAFETY: The adapter doesn't retrieve any state yet, so it's compatible with any
// registration.
let fops = unsafe { file_operations::FileOperationsVtable::<Self, T>::build() };
let mut cdev = Cdev::alloc(fops, &this.this_module)?;
let mut cdev = Cdev::alloc(fops, &self.this_module)?;
cdev.add(inner.dev + inner.used as bindings::dev_t, 1)?;
inner.cdevs[inner.used].replace(cdev);
inner.used += 1;
Expand Down
11 changes: 4 additions & 7 deletions samples/rust/rust_chrdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
#![no_std]
#![feature(allocator_api, global_asm)]

use alloc::boxed::Box;
use core::pin::Pin;
use kernel::prelude::*;
use kernel::{c_str, chrdev, file_operations::FileOperations};

Expand All @@ -26,21 +24,20 @@ impl FileOperations for RustFile {
}

struct RustChrdev {
_dev: Pin<Box<chrdev::Registration<2>>>,
_dev: chrdev::Registration<2>,
}

impl KernelModule for RustChrdev {
fn init() -> Result<Self> {
pr_info!("Rust character device sample (init)\n");

let mut chrdev_reg =
chrdev::Registration::new_pinned(c_str!("rust_chrdev"), 0, &THIS_MODULE)?;
let mut chrdev_reg = chrdev::Registration::new(c_str!("rust_chrdev"), 0, &THIS_MODULE);

// Register the same kind of device twice, we're just demonstrating
// that you can use multiple minors. There are two minors in this case
// because its type is `chrdev::Registration<2>`
chrdev_reg.as_mut().register::<RustFile>()?;
chrdev_reg.as_mut().register::<RustFile>()?;
chrdev_reg.register::<RustFile>()?;
chrdev_reg.register::<RustFile>()?;

Ok(RustChrdev { _dev: chrdev_reg })
}
Expand Down