Skip to contentSkip to conversation

rust: miscdevice: Provide sample driver using the new MiscDevice bindings

PATCH In review Lee Jones 4 participants 9 messages Dec 13, 2024 – Dec 22, 2024

Subsystems (3)
lore
Share & tools
lore

Lee Jones

author
#0 lore raw

v6 cover rust: miscdevice: Provide sample driver using the new MiscDevice bindings

This set depends on Alice's most recent MiscDevice changes:

https://lore.kernel.org/all/[email protected]/

Changelog v5 -> v6:
- pr_info() to dev_info() conversion (based on Alice's new set)
- Moved the example C program from the commit message to the file comments
- Changed mutex-drop commentary

Lee Jones (5):
Documentation: ioctl-number: Carve out some identifiers for use by
sample drivers
samples: rust: Provide example using the new Rust MiscDevice
abstraction
samples: rust_misc_device: Demonstrate additional get/set value
functionality
MAINTAINERS: Add Rust Misc Sample to MISC entry
samples: rust_misc_device: Provide an example C program to exercise
functionality

 .../userspace-api/ioctl/ioctl-number.rst      |   1 +
 MAINTAINERS                                   |   1 +
 samples/rust/Kconfig                          |  10 +
 samples/rust/Makefile                         |   1 +
 samples/rust/rust_misc_device.rs              | 238 ++++++++++++++++++
 5 files changed, 251 insertions(+)
 create mode 100644 samples/rust/rust_misc_device.rs
Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
author
#1 lore raw

PATCH v6 1/5 Documentation: ioctl-number: Carve out some identifiers for use by sample drivers

32 IDs should be plenty (at yet, not too greedy) since a lot of sample drivers will use their own subsystem allocations.

Sample drivers predominately reside in <KERNEL_ROOT>/samples, but there should be no issue with in-place example drivers using them.

---
 Documentation/userspace-api/ioctl/ioctl-number.rst | 1 +
 1 file changed, 1 insertion(+)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index 243f1f1b554a..dc4bc0cab69f 100644
@@ -311,6 +311,7 @@ Code  Seq#    Include File                                           Comments
                                                                      <mailto:[email protected]>
 'z'   10-4F  drivers/s390/crypto/zcrypt_api.h                        conflict!
 '|'   00-7F  linux/media.h
+'|'   80-9F  samples/                                                Any sample and example drivers
 0x80  00-1F  linux/fb.h
 0x81  00-1F  linux/vduse.h
 0x89  00-06  arch/x86/include/asm/sockios.h
Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
author
#2 lore raw

PATCH v6 2/5 samples: rust: Provide example using the new Rust MiscDevice abstraction

In reply to Lee Jones

This sample driver demonstrates the following basic operations:

* Register a Misc Device
* Create /dev/rust-misc-device
* Provide open call-back for the aforementioned character device
* Operate on the character device via a simple ioctl()
* Provide close call-back for the character device

---
 samples/rust/Kconfig             | 10 ++++
 samples/rust/Makefile            |  1 +
 samples/rust/rust_misc_device.rs | 87 ++++++++++++++++++++++++++++++++
 3 files changed, 98 insertions(+)
 create mode 100644 samples/rust/rust_misc_device.rs
samples/rust/Kconfig +10 -0
index b0f74a81c8f9..df384e679901 100644
@@ -20,6 +20,16 @@ config SAMPLE_RUST_MINIMAL
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_MISC_DEVICE
+	tristate "Misc device"
+	help
+	  This option builds the Rust misc device.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_misc_device.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_PRINT
 	tristate "Printing macros"
 	help
samples/rust/Makefile +1 -0
index c1a5c1655395..ad4b97a98580 100644
@@ -2,6 +2,7 @@
 ccflags-y += -I$(src)				# needed for trace events
 
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
+obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
 
 rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/rust_misc_device.rs new file +87 -0

87 lines not on this page · raw message

Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
reviewer Reviewed-by on v6 2/5
#3 lore raw

Re: [PATCH v6 2/5] samples: rust: Provide example using the new Rust MiscDevice abstraction

Quoted 9 lines · Lee Jones

This sample driver demonstrates the following basic operations:

* Register a Misc Device
* Create /dev/rust-misc-device
* Provide open call-back for the aforementioned character device
* Operate on the character device via a simple ioctl()
* Provide close call-back for the character device

Quoted 137 lines
---
 samples/rust/Kconfig             | 10 ++++
 samples/rust/Makefile            |  1 +
 samples/rust/rust_misc_device.rs | 87 ++++++++++++++++++++++++++++++++
 3 files changed, 98 insertions(+)
 create mode 100644 samples/rust/rust_misc_device.rs
samples/rust/Kconfig +10 -0
index b0f74a81c8f9..df384e679901 100644
@@ -20,6 +20,16 @@ config SAMPLE_RUST_MINIMAL
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_MISC_DEVICE
+	tristate "Misc device"
+	help
+	  This option builds the Rust misc device.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_misc_device.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_PRINT
 	tristate "Printing macros"
 	help
samples/rust/Makefile +1 -0
index c1a5c1655395..ad4b97a98580 100644
@@ -2,6 +2,7 @@
 ccflags-y += -I$(src)				# needed for trace events
 
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
+obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
 
 rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/rust_misc_device.rs new file +87 -0
new file mode 100644
index 000000000000..324c3696ae3f
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2024 Google LLC.
+
+//! Rust misc device sample.
+
+use kernel::{
+    c_str,
+    device::Device,
+    fs::File,
+    ioctl::_IO,
+    miscdevice::{MiscDevice, MiscDeviceOptions, MiscDeviceRegistration},
+    prelude::*,
+    types::ARef,
+};
+
+const RUST_MISC_DEV_HELLO: u32 = _IO('|' as u32, 0x80);
+
+module! {
+    type: RustMiscDeviceModule,
+    name: "rust_misc_device",
+    author: "Lee Jones",
+    description: "Rust misc device sample",
+    license: "GPL",
+}
+
+#[pin_data]
+struct RustMiscDeviceModule {
+    #[pin]
+    _miscdev: MiscDeviceRegistration<RustMiscDevice>,
+}
+
+impl kernel::InPlaceModule for RustMiscDeviceModule {
+    fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
+        pr_info!("Initialising Rust Misc Device Sample\n");
+
+        let options = MiscDeviceOptions {
+            name: c_str!("rust-misc-device"),
+        };
+
+        try_pin_init!(Self {
+            _miscdev <- MiscDeviceRegistration::register(options),
+        })
+    }
+}
+
+struct RustMiscDevice {
+    dev: ARef<Device>,
+}
+
+#[vtable]
+impl MiscDevice for RustMiscDevice {
+    type Ptr = KBox<Self>;
+
+    fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<KBox<Self>> {
+        let dev = ARef::from(misc.device());
+
+        dev_info!(dev, "Opening Rust Misc Device Sample\n");
+
+        Ok(KBox::new(RustMiscDevice { dev }, GFP_KERNEL)?)
+    }
+
+    fn ioctl(
+        me: <Self::Ptr as kernel::types::ForeignOwnable>::Borrowed<'_>,
+        _file: &File,
+        cmd: u32,
+        _arg: usize,
+    ) -> Result<isize> {
+        dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n");
+
+        match cmd {
+            RUST_MISC_DEV_HELLO => dev_info!(me.dev, "Hello from the Rust Misc Device\n"),
+            _ => {
+                dev_err!(me.dev, "-> IOCTL not recognised: {}\n", cmd);
+                return Err(ENOTTY);
+            }
+        }
+
+        Ok(0)
+    }
+}
+
+impl Drop for RustMiscDevice {
+    fn drop(&mut self) {
+        dev_info!(self.dev, "Exiting the Rust Misc Device Sample\n");
+    }
+}
Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
#4 lore raw

Re: [PATCH v6 2/5] samples: rust: Provide example using the new Rust MiscDevice abstraction

In reply to Lee Jones
kernel test robot noticed the following build errors:

Hi Lee,

kernel test robot noticed the following build errors:

[auto build test ERROR on rust/rust-next]
[also build test ERROR on lee-leds/for-leds-next soc/for-next linus/master v6.13-rc3] [cannot apply to next-20241220]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Lee-Jones/Documentation-ioctl-number-Carve-out-some-identifiers-for-use-by-sample-drivers/20241213-215003
base:   https://github.com/Rust-for-Linux/linux rust-next
patch link:    https://lore.kernel.org/r/20241213134715.601415-3-lee%40kernel.org
patch subject: [PATCH v6 2/5] samples: rust: Provide example using the new Rust MiscDevice abstraction
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20241222/[email protected]/config)
compiler: clang version 19.1.3 (https://github.com/llvm/llvm-project ab51eccf88f5321e7c60591c5546b254b6afab99)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20241222/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

error[E0050]: method open has 2 parameters but the declaration in trait open has 0 --> samples/rust/rust_misc_device.rs:55:20
|
55 | fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<KBox<Self>> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 0 parameters, found 2
|

>> = note: `open` from trait: `fn() -> core::result::Result<<Self as MiscDevice>::Ptr, kernel::error::Error>`

--
error[E0050]: method ioctl has 4 parameters but the declaration in trait ioctl has 3 --> samples/rust/rust_misc_device.rs:64:13
|

   64 |           me: <Self::Ptr as kernel::types::ForeignOwnable>::Borrowed<'_>,
   |  _____________^
   65 | |         _file: &File,
   66 | |         cmd: u32,
   67 | |         _arg: usize,
   | |___________________^ expected 3 parameters, found 4
   |
>> = note: `ioctl` from trait: `fn(<<Self as MiscDevice>::Ptr as ForeignOwnable>::Borrowed<'_>, u32, usize) -> core::result::Result<isize, kernel::error::Error>`
--
>> error[E0599]: no method named `device` found for reference `&MiscDeviceRegistration<RustMiscDevice>` in the current scope

--> samples/rust/rust_misc_device.rs:56:35
|
56 | let dev = ARef::from(misc.device());
| ^^^^^^ method not found in &MiscDeviceRegistration<RustMiscDevice>
--

>> error[E0282]: type annotations needed for `ARef<T>`

--> samples/rust/rust_misc_device.rs:56:13
|
56 | let dev = ARef::from(misc.device());
| ^^^
57 |
58 | dev_info!(dev, "Opening Rust Misc Device Samplen");
| --------------------------------------------------- type must be known at this point
|
help: consider giving dev an explicit type, where the type for type parameter T is specified |
56 | let dev: ARef<T> = ARef::from(misc.device());
| +++++++++

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author
#5 lore raw

PATCH v6 3/5 samples: rust_misc_device: Demonstrate additional get/set value functionality

In reply to Lee Jones

Expand the complexity of the sample driver by providing the ability to get and set an integer. The value is protected by a mutex.

---
 samples/rust/rust_misc_device.rs | 89 +++++++++++++++++++++++++++-----
 1 file changed, 75 insertions(+), 14 deletions(-)
samples/rust/rust_misc_device.rs +75 -14
index 324c3696ae3f..ae1474a451f1 100644
@@ -4,17 +4,24 @@
 
 //! Rust misc device sample.
 
+use core::pin::Pin;
+
 use kernel::{
     c_str,
     device::Device,
     fs::File,
-    ioctl::_IO,
+    ioctl::{_IO, _IOC_SIZE, _IOR, _IOW},
     miscdevice::{MiscDevice, MiscDeviceOptions, MiscDeviceRegistration},
+    new_mutex,
     prelude::*,
+    sync::Mutex,
     types::ARef,
+    uaccess::{UserSlice, UserSliceReader, UserSliceWriter},
 };
 
 const RUST_MISC_DEV_HELLO: u32 = _IO('|' as u32, 0x80);
+const RUST_MISC_DEV_GET_VALUE: u32 = _IOR::<i32>('|' as u32, 0x81);
+const RUST_MISC_DEV_SET_VALUE: u32 = _IOW::<i32>('|' as u32, 0x82);
 
 module! {
     type: RustMiscDeviceModule,
@@ -44,44 +51,98 @@ fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
     }
 }
 
+struct Inner {
+    value: i32,
+}
+
+#[pin_data(PinnedDrop)]
 struct RustMiscDevice {
+    #[pin]
+    inner: Mutex<Inner>,
     dev: ARef<Device>,
 }
 
 #[vtable]
 impl MiscDevice for RustMiscDevice {
-    type Ptr = KBox<Self>;
+    type Ptr = Pin<KBox<Self>>;
 
-    fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<KBox<Self>> {
+    fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Self>>> {
         let dev = ARef::from(misc.device());
 
         dev_info!(dev, "Opening Rust Misc Device Sample\n");
 
-        Ok(KBox::new(RustMiscDevice { dev }, GFP_KERNEL)?)
+        KBox::try_pin_init(
+            try_pin_init! {
+                RustMiscDevice {
+                    inner <- new_mutex!( Inner{ value: 0_i32 } ),
+                    dev: dev,
+                }
+            },
+            GFP_KERNEL,
+        )
     }
 
-    fn ioctl(
-        me: <Self::Ptr as kernel::types::ForeignOwnable>::Borrowed<'_>,
-        _file: &File,
-        cmd: u32,
-        _arg: usize,
-    ) -> Result<isize> {
+    fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize) -> Result<isize> {
         dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n");
 
+        let size = _IOC_SIZE(cmd);
+
         match cmd {
-            RUST_MISC_DEV_HELLO => dev_info!(me.dev, "Hello from the Rust Misc Device\n"),
+            RUST_MISC_DEV_GET_VALUE => me.get_value(UserSlice::new(arg, size).writer())?,
+            RUST_MISC_DEV_SET_VALUE => me.set_value(UserSlice::new(arg, size).reader())?,
+            RUST_MISC_DEV_HELLO => me.hello()?,
             _ => {
                 dev_err!(me.dev, "-> IOCTL not recognised: {}\n", cmd);
                 return Err(ENOTTY);
             }
-        }
+        };
 
         Ok(0)
     }
 }
 
-impl Drop for RustMiscDevice {
-    fn drop(&mut self) {
+#[pinned_drop]
+impl PinnedDrop for RustMiscDevice {
+    fn drop(self: Pin<&mut Self>) {
         dev_info!(self.dev, "Exiting the Rust Misc Device Sample\n");
     }
 }
+
+impl RustMiscDevice {
+    fn set_value(&self, mut reader: UserSliceReader) -> Result<isize> {
+        let new_value = reader.read::<i32>()?;
+        let mut guard = self.inner.lock();
+
+        dev_info!(
+            self.dev,
+            "-> Copying data from userspace (value: {})\n",
+            new_value
+        );
+
+        guard.value = new_value;
+        Ok(0)
+    }
+
+    fn get_value(&self, mut writer: UserSliceWriter) -> Result<isize> {
+        let guard = self.inner.lock();
+        let value = guard.value;
+
+        // Free-up the lock and use our locally cached instance from here
+        drop(guard);
+
+        dev_info!(
+            self.dev,
+            "-> Copying data to userspace (value: {})\n",
+            &value
+        );
+
+        writer.write::<i32>(&value)?;
+        Ok(0)
+    }
+
+    fn hello(&self) -> Result<isize> {
+        dev_info!(self.dev, "-> Hello from the Rust Misc Device\n");
+
+        Ok(0)
+    }
+}
Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
author
#6 lore raw

PATCH v6 4/5 MAINTAINERS: Add Rust Misc Sample to MISC entry

In reply to Lee Jones
---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
index 81348dbce8ca..d3e3b20e0376 100644
@@ -5346,6 +5346,7 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/char-misc.git
 F:	drivers/char/
 F:	drivers/misc/
 F:	include/linux/miscdevice.h
+F:	samples/rust/rust_misc_device.rs
 X:	drivers/char/agp/
 X:	drivers/char/hw_random/
 X:	drivers/char/ipmi/
Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
author
#7 lore raw

PATCH v6 5/5 samples: rust_misc_device: Provide an example C program to exercise functionality

In reply to Lee Jones

Here is the expected output (manually spliced together):

USERSPACE: Opening /dev/rust-misc-device for reading and writing
KERNEL: rust_misc_device: Opening Rust Misc Device Sample
USERSPACE: Calling Hello
KERNEL: rust_misc_device: IOCTLing Rust Misc Device Sample
KERNEL: rust_misc_device: -> Hello from the Rust Misc Device
USERSPACE: Fetching initial value
KERNEL: rust_misc_device: IOCTLing Rust Misc Device Sample
KERNEL: rust_misc_device: -> Copying data to userspace (value: 0)
USERSPACE: Submitting new value (1)
KERNEL: rust_misc_device: IOCTLing Rust Misc Device Sample
KERNEL: rust_misc_device: -> Copying data from userspace (value: 1)
USERSPACE: Fetching new value
KERNEL: rust_misc_device: IOCTLing Rust Misc Device Sample
KERNEL: rust_misc_device: -> Copying data to userspace (value: 1)
USERSPACE: Attempting to call in to an non-existent IOCTL
KERNEL: rust_misc_device: IOCTLing Rust Misc Device Sample
KERNEL: rust_misc_device: -> IOCTL not recognised: 20992
USERSPACE: ioctl: Succeeded to fail - this was expected: Inappropriate ioctl for device
USERSPACE: Closing /dev/rust-misc-device
KERNEL: rust_misc_device: Exiting the Rust Misc Device Sample
USERSPACE: Success

---
 samples/rust/rust_misc_device.rs | 90 ++++++++++++++++++++++++++++++++
 1 file changed, 90 insertions(+)
samples/rust/rust_misc_device.rs +90 -0
index ae1474a451f1..40ad7266c225 100644
@@ -4,6 +4,96 @@
 
 //! Rust misc device sample.
 
+/// Below is an example userspace C program that exercises this sample's functionality.
+///
+/// ```c
+/// #include <stdio.h>
+/// #include <stdlib.h>
+/// #include <errno.h>
+/// #include <fcntl.h>
+/// #include <unistd.h>
+/// #include <sys/ioctl.h>
+///
+/// #define RUST_MISC_DEV_FAIL _IO('|', 0)
+/// #define RUST_MISC_DEV_HELLO _IO('|', 0x80)
+/// #define RUST_MISC_DEV_GET_VALUE _IOR('|', 0x81, int)
+/// #define RUST_MISC_DEV_SET_VALUE _IOW('|', 0x82, int)
+///
+/// int main() {
+///   int value, new_value;
+///   int fd, ret;
+///
+///   // Open the device file
+///   printf("Opening /dev/rust-misc-device for reading and writing\n");
+///   fd = open("/dev/rust-misc-device", O_RDWR);
+///   if (fd < 0) {
+///     perror("open");
+///     return errno;
+///   }
+///
+///   // Make call into driver to say "hello"
+///   printf("Calling Hello\n");
+///   ret = ioctl(fd, RUST_MISC_DEV_HELLO, NULL);
+///   if (ret < 0) {
+///     perror("ioctl: Failed to call into Hello");
+///     close(fd);
+///     return errno;
+///   }
+///
+///   // Get initial value
+///   printf("Fetching initial value\n");
+///   ret = ioctl(fd, RUST_MISC_DEV_GET_VALUE, &value);
+///   if (ret < 0) {
+///     perror("ioctl: Failed to fetch the initial value");
+///     close(fd);
+///     return errno;
+///   }
+///
+///   value++;
+///
+///   // Set value to something different
+///   printf("Submitting new value (%d)\n", value);
+///   ret = ioctl(fd, RUST_MISC_DEV_SET_VALUE, &value);
+///   if (ret < 0) {
+///     perror("ioctl: Failed to submit new value");
+///     close(fd);
+///     return errno;
+///   }
+///
+///   // Ensure new value was applied
+///   printf("Fetching new value\n");
+///   ret = ioctl(fd, RUST_MISC_DEV_GET_VALUE, &new_value);
+///   if (ret < 0) {
+///     perror("ioctl: Failed to fetch the new value");
+///     close(fd);
+///     return errno;
+///   }
+///
+///   if (value != new_value) {
+///     printf("Failed: Committed and retrieved values are different (%d - %d)\n", value, new_value);
+///     close(fd);
+///     return -1;
+///   }
+///
+///   // Call the unsuccessful ioctl
+///   printf("Attempting to call in to an non-existent IOCTL\n");
+///   ret = ioctl(fd, RUST_MISC_DEV_FAIL, NULL);
+///   if (ret < 0) {
+///     perror("ioctl: Succeeded to fail - this was expected");
+///   } else {
+///     printf("ioctl: Failed to fail\n");
+///     close(fd);
+///     return -1;
+///   }
+///
+///   // Close the device file
+///   printf("Closing /dev/rust-misc-device\n");
+///   close(fd);
+///
+///   printf("Success\n");
+///   return 0;
+/// }
+/// ```
 use core::pin::Pin;
 
 use kernel::{
Signature · 1 line
2.47.1.613.gc27f4b7a9f-goog
maintainer
#8 lore raw
In reply to Lee Jones
Quoted 8 lines · Lee Jones

This set depends on Alice's most recent MiscDevice changes:

https://lore.kernel.org/all/[email protected]/

Changelog v5 -> v6:
- pr_info() to dev_info() conversion (based on Alice's new set)
- Moved the example C program from the commit message to the file comments
- Changed mutex-drop commentary

Much nicer, thanks! I've applied, and Alice's changes, to my driver-core-testing branch, let's see what 0-day has to say about them...

greg k-h