Resguardo inicial

This commit is contained in:
lastdragon
2026-09-06 12:53:21 -06:00
parent 662efe3c2a
commit ad2088d178
94853 changed files with 43200404 additions and 0 deletions
+182
View File
@@ -0,0 +1,182 @@
# SPDX-License-Identifier: GPL-2.0
menuconfig SAMPLES_RUST
bool "Rust samples"
depends on RUST
help
You can build sample Rust kernel code here.
If unsure, say N.
if SAMPLES_RUST
config SAMPLE_RUST_CONFIGFS
tristate "Configfs sample"
depends on CONFIGFS_FS
help
This option builds the Rust configfs sample.
To compile this as a module, choose M here:
the module will be called rust_configfs.
If unsure, say N.
config SAMPLE_RUST_MINIMAL
tristate "Minimal"
help
This option builds the Rust minimal module sample.
To compile this as a module, choose M here:
the module will be called 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
This option builds the Rust printing macros sample.
To compile this as a module, choose M here:
the module will be called rust_print.
If unsure, say N.
config SAMPLE_RUST_DMA
tristate "DMA Test Driver"
depends on PCI
help
This option builds the Rust DMA Test driver sample.
To compile this as a module, choose M here:
the module will be called rust_dma.
If unsure, say N.
config SAMPLE_RUST_DEBUGFS
tristate "DebugFS Test Module"
depends on DEBUG_FS
help
This option builds the Rust DebugFS Test module sample.
To compile this as a module, choose M here:
the module will be called rust_debugfs.
If unsure, say N.
config SAMPLE_RUST_DEBUGFS_SCOPED
tristate "Scoped DebugFS Test Module"
depends on DEBUG_FS
help
This option builds the Rust Scoped DebugFS Test module sample.
To compile this as a module, choose M here:
the module will be called rust_debugfs_scoped.
If unsure, say N.
config SAMPLE_RUST_DRIVER_I2C
tristate "I2C Driver"
depends on I2C=y
help
This option builds the Rust I2C driver sample.
To compile this as a module, choose M here:
the module will be called rust_driver_i2c.
If unsure, say N.
config SAMPLE_RUST_I2C_CLIENT
tristate "I2C Client Registration"
depends on I2C=y
help
This option builds the Rust I2C client manual creation
sample.
To compile this as a module, choose M here:
the module will be called rust_i2c_client.
If unsure, say N.
config SAMPLE_RUST_DRIVER_PCI
tristate "PCI Driver"
depends on PCI
help
This option builds the Rust PCI driver sample.
To compile this as a module, choose M here:
the module will be called rust_driver_pci.
If unsure, say N.
config SAMPLE_RUST_DRIVER_PLATFORM
tristate "Platform Driver"
help
This option builds the Rust Platform driver sample.
To compile this as a module, choose M here:
the module will be called rust_driver_platform.
If unsure, say N.
config SAMPLE_RUST_DRIVER_USB
tristate "USB Driver"
depends on USB = y
help
This option builds the Rust USB driver sample.
To compile this as a module, choose M here:
the module will be called rust_driver_usb.
If unsure, say N.
config SAMPLE_RUST_DRIVER_FAUX
tristate "Faux Driver"
help
This option builds the Rust Faux driver sample.
To compile this as a module, choose M here:
the module will be called rust_driver_faux.
If unsure, say N.
config SAMPLE_RUST_DRIVER_AUXILIARY
tristate "Auxiliary Driver"
depends on PCI
select AUXILIARY_BUS
help
This option builds the Rust auxiliary driver sample.
To compile this as a module, choose M here:
the module will be called rust_driver_auxiliary.
If unsure, say N.
config SAMPLE_RUST_SOC
tristate "SoC Driver"
select SOC_BUS
help
This option builds the Rust SoC driver sample.
To compile this as a module, choose M here:
the module will be called rust_soc.
If unsure, say N.
config SAMPLE_RUST_HOSTPROGS
bool "Host programs"
help
This option builds the Rust host program samples.
If unsure, say N.
endif # SAMPLES_RUST
+22
View File
@@ -0,0 +1,22 @@
# SPDX-License-Identifier: GPL-2.0
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
obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) += rust_debugfs.o
obj-$(CONFIG_SAMPLE_RUST_DEBUGFS_SCOPED) += rust_debugfs_scoped.o
obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o
obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C) += rust_driver_i2c.o
obj-$(CONFIG_SAMPLE_RUST_I2C_CLIENT) += rust_i2c_client.o
obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o
obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o
obj-$(CONFIG_SAMPLE_RUST_DRIVER_USB) += rust_driver_usb.o
obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) += rust_driver_faux.o
obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY) += rust_driver_auxiliary.o
obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o
obj-$(CONFIG_SAMPLE_RUST_SOC) += rust_soc.o
rust_print-y := rust_print_main.o rust_print_events.o
subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS) += hostprogs
@@ -0,0 +1,3 @@
# SPDX-License-Identifier: GPL-2.0
single
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-2.0
hostprogs-always-y := single
single-rust := y
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust single host program sample: module `a`.
pub(crate) fn f(x: i32) {
println!("The number is {}.", x);
}
+5
View File
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust single host program sample: module `b`.
pub(crate) const CONSTANT: i32 = 42;
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust single host program sample.
mod a;
mod b;
fn main() {
println!("Hello world!");
a::f(b::CONSTANT);
}
+191
View File
@@ -0,0 +1,191 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust configfs sample.
use kernel::alloc::flags;
use kernel::configfs;
use kernel::configfs::configfs_attrs;
use kernel::new_mutex;
use kernel::page::PAGE_SIZE;
use kernel::prelude::*;
use kernel::sync::Mutex;
module! {
type: RustConfigfs,
name: "rust_configfs",
authors: ["Rust for Linux Contributors"],
description: "Rust configfs sample",
license: "GPL",
}
#[pin_data]
struct RustConfigfs {
#[pin]
config: configfs::Subsystem<Configuration>,
}
#[pin_data]
struct Configuration {
message: &'static CStr,
#[pin]
bar: Mutex<(KBox<[u8; PAGE_SIZE]>, usize)>,
}
impl Configuration {
fn new() -> impl PinInit<Self, Error> {
try_pin_init!(Self {
message: c"Hello World\n",
bar <- new_mutex!((KBox::new([0; PAGE_SIZE], flags::GFP_KERNEL)?, 0)),
})
}
}
impl kernel::InPlaceModule for RustConfigfs {
fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
pr_info!("Rust configfs sample (init)\n");
// Define a subsystem with the data type `Configuration`, two
// attributes, `message` and `bar` and child group type `Child`. `mkdir`
// in the directory representing this subsystem will create directories
// backed by the `Child` type.
let item_type = configfs_attrs! {
container: configfs::Subsystem<Configuration>,
data: Configuration,
child: Child,
attributes: [
message: 0,
bar: 1,
],
};
try_pin_init!(Self {
config <- configfs::Subsystem::new(
c"rust_configfs", item_type, Configuration::new()
),
})
}
}
#[vtable]
impl configfs::GroupOperations for Configuration {
type Child = Child;
fn make_group(&self, name: &CStr) -> Result<impl PinInit<configfs::Group<Child>, Error>> {
// Define a group with data type `Child`, one attribute `baz` and child
// group type `GrandChild`. `mkdir` in the directory representing this
// group will create directories backed by the `GrandChild` type.
let tpe = configfs_attrs! {
container: configfs::Group<Child>,
data: Child,
child: GrandChild,
attributes: [
baz: 0,
],
};
Ok(configfs::Group::new(name.try_into()?, tpe, Child::new()))
}
}
#[vtable]
impl configfs::AttributeOperations<0> for Configuration {
type Data = Configuration;
fn show(container: &Configuration, page: &mut [u8; PAGE_SIZE]) -> Result<usize> {
pr_info!("Show message\n");
let data = container.message.to_bytes();
page[0..data.len()].copy_from_slice(data);
Ok(data.len())
}
}
#[vtable]
impl configfs::AttributeOperations<1> for Configuration {
type Data = Configuration;
fn show(container: &Configuration, page: &mut [u8; PAGE_SIZE]) -> Result<usize> {
pr_info!("Show bar\n");
let guard = container.bar.lock();
let data = guard.0.as_slice();
let len = guard.1;
page[0..len].copy_from_slice(&data[0..len]);
Ok(len)
}
fn store(container: &Configuration, page: &[u8]) -> Result {
pr_info!("Store bar\n");
let mut guard = container.bar.lock();
guard.0[0..page.len()].copy_from_slice(page);
guard.1 = page.len();
Ok(())
}
}
// `pin_data` cannot handle structs without braces.
#[pin_data]
struct Child {}
impl Child {
fn new() -> impl PinInit<Self, Error> {
try_pin_init!(Self {})
}
}
#[vtable]
impl configfs::GroupOperations for Child {
type Child = GrandChild;
fn make_group(&self, name: &CStr) -> Result<impl PinInit<configfs::Group<GrandChild>, Error>> {
// Define a group with data type `GrandChild`, one attribute `gc`. As no
// child type is specified, it will not be possible to create subgroups
// in this group, and `mkdir`in the directory representing this group
// will return an error.
let tpe = configfs_attrs! {
container: configfs::Group<GrandChild>,
data: GrandChild,
attributes: [
gc: 0,
],
};
Ok(configfs::Group::new(
name.try_into()?,
tpe,
GrandChild::new(),
))
}
}
#[vtable]
impl configfs::AttributeOperations<0> for Child {
type Data = Child;
fn show(_container: &Child, page: &mut [u8; PAGE_SIZE]) -> Result<usize> {
pr_info!("Show baz\n");
let data = c"Hello Baz\n".to_bytes();
page[0..data.len()].copy_from_slice(data);
Ok(data.len())
}
}
// `pin_data` cannot handle structs without braces.
#[pin_data]
struct GrandChild {}
impl GrandChild {
fn new() -> impl PinInit<Self, Error> {
try_pin_init!(Self {})
}
}
#[vtable]
impl configfs::AttributeOperations<0> for GrandChild {
type Data = GrandChild;
fn show(_container: &GrandChild, page: &mut [u8; PAGE_SIZE]) -> Result<usize> {
pr_info!("Show grand child\n");
let data = c"Hello GC\n".to_bytes();
page[0..data.len()].copy_from_slice(data);
Ok(data.len())
}
}
+178
View File
@@ -0,0 +1,178 @@
// SPDX-License-Identifier: GPL-2.0
// Copyright (C) 2025 Google LLC.
//! Sample DebugFS exporting platform driver
//!
//! To successfully probe this driver with ACPI, use an ssdt that looks like
//!
//! ```dsl
//! DefinitionBlock ("", "SSDT", 2, "TEST", "VIRTACPI", 0x00000001)
//! {
//! Scope (\_SB)
//! {
//! Device (T432)
//! {
//! Name (_HID, "LNUXBEEF") // ACPI hardware ID to match
//! Name (_UID, 1)
//! Name (_STA, 0x0F) // Device present, enabled
//! Name (_DSD, Package () { // Sample attribute
//! ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
//! Package() {
//! Package(2) {"compatible", "sample-debugfs"}
//! }
//! })
//! Name (_CRS, ResourceTemplate ()
//! {
//! Memory32Fixed (ReadWrite, 0xFED00000, 0x1000)
//! })
//! }
//! }
//! }
//! ```
use core::str::FromStr;
use kernel::{
acpi,
debugfs::{
Dir,
File, //
},
device::Core,
new_mutex,
of,
platform,
prelude::*,
sizes::*,
str::CString,
sync::{
aref::ARef,
atomic::{
Atomic,
Relaxed, //
},
Mutex,
}, //
};
kernel::module_platform_driver! {
type: RustDebugFs,
name: "rust_debugfs",
authors: ["Matthew Maurer"],
description: "Rust DebugFS usage sample",
license: "GPL",
}
#[pin_data]
struct RustDebugFs {
pdev: ARef<platform::Device>,
// As we only hold these for drop effect (to remove the directory/files) we have a leading
// underscore to indicate to the compiler that we don't expect to use this field directly.
_debugfs: Dir,
#[pin]
_compatible: File<CString>,
#[pin]
counter: File<Atomic<usize>>,
#[pin]
inner: File<Mutex<Inner>>,
#[pin]
array_blob: File<Mutex<[u8; 4]>>,
#[pin]
vector_blob: File<Mutex<KVec<u8>>>,
}
#[derive(Debug)]
struct Inner {
x: u32,
y: u32,
}
impl FromStr for Inner {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let mut parts = s.split_whitespace();
let x = parts
.next()
.ok_or(EINVAL)?
.parse::<u32>()
.map_err(|_| EINVAL)?;
let y = parts
.next()
.ok_or(EINVAL)?
.parse::<u32>()
.map_err(|_| EINVAL)?;
if parts.next().is_some() {
return Err(EINVAL);
}
Ok(Inner { x, y })
}
}
kernel::acpi_device_table!(
ACPI_TABLE,
MODULE_ACPI_TABLE,
<RustDebugFs as platform::Driver>::IdInfo,
[(acpi::DeviceId::new(c"LNUXBEEF"), ())]
);
impl platform::Driver for RustDebugFs {
type IdInfo = ();
type Data<'bound> = Self;
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
fn probe<'bound>(
pdev: &'bound platform::Device<Core<'_>>,
_info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self, Error> + 'bound {
RustDebugFs::new(pdev).pin_chain(|this| {
this.counter.store(91, Relaxed);
{
let mut guard = this.inner.lock();
guard.x = guard.y;
guard.y = 42;
}
Ok(())
})
}
}
impl RustDebugFs {
fn build_counter(dir: &Dir) -> impl PinInit<File<Atomic<usize>>> + '_ {
dir.read_write_file(c"counter", Atomic::<usize>::new(0))
}
fn build_inner(dir: &Dir) -> impl PinInit<File<Mutex<Inner>>> + '_ {
dir.read_write_file(c"pair", new_mutex!(Inner { x: 3, y: 10 }))
}
fn new<'a>(pdev: &'a platform::Device<Core<'_>>) -> impl PinInit<Self, Error> + 'a {
let debugfs = Dir::new(c"sample_debugfs");
let dev = pdev.as_ref();
try_pin_init! {
Self {
_compatible <- debugfs.read_only_file(
c"compatible",
dev.fwnode()
.ok_or(ENOENT)?
.property_read::<CString>(c"compatible")
.required_by(dev)?,
),
counter <- Self::build_counter(&debugfs),
inner <- Self::build_inner(&debugfs),
array_blob <- debugfs.read_write_binary_file(
c"array_blob",
new_mutex!([0x62, 0x6c, 0x6f, 0x62]),
),
vector_blob <- debugfs.read_write_binary_file(
c"vector_blob",
new_mutex!(kernel::kvec!(0x42; SZ_4K)?),
),
_debugfs: debugfs,
pdev: pdev.into(),
}
}
}
}
@@ -0,0 +1,144 @@
// SPDX-License-Identifier: GPL-2.0
// Copyright (C) 2025 Google LLC.
//! Sample DebugFS exporting platform driver that demonstrates the use of
//! `Scope::dir` to create a variety of files without the need to separately
//! track them all.
use kernel::{
debugfs::{
Dir,
Scope, //
},
new_mutex,
prelude::*,
sizes::*,
str::CString,
sync::{
atomic::Atomic,
Mutex, //
},
};
module! {
type: RustScopedDebugFs,
name: "rust_debugfs_scoped",
authors: ["Matthew Maurer"],
description: "Rust Scoped DebugFS usage sample",
license: "GPL",
}
fn remove_file_write(
mod_data: &ModuleData,
reader: &mut kernel::uaccess::UserSliceReader,
) -> Result {
let mut buf = [0u8; 128];
if reader.len() >= buf.len() {
return Err(EINVAL);
}
let n = reader.len();
reader.read_slice(&mut buf[..n])?;
let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?.trim();
let nul_idx = s.len();
buf[nul_idx] = 0;
let to_remove = CStr::from_bytes_with_nul(&buf[..nul_idx + 1]).map_err(|_| EINVAL)?;
mod_data
.devices
.lock()
.retain(|device| device.name.to_bytes() != to_remove.to_bytes());
Ok(())
}
fn create_file_write(
mod_data: &ModuleData,
reader: &mut kernel::uaccess::UserSliceReader,
) -> Result {
let mut buf = [0u8; 128];
if reader.len() > buf.len() {
return Err(EINVAL);
}
let n = reader.len();
reader.read_slice(&mut buf[..n])?;
let mut nums = KVec::new();
let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?.trim();
let mut items = s.split_whitespace();
let name_str = items.next().ok_or(EINVAL)?;
let name = CString::try_from_fmt(fmt!("{name_str}"))?;
let file_name = CString::try_from_fmt(fmt!("{name_str}"))?;
for sub in items {
nums.push(
Atomic::<usize>::new(sub.parse().map_err(|_| EINVAL)?),
GFP_KERNEL,
)?;
}
let blob = KBox::pin_init(new_mutex!([0x42; SZ_4K]), GFP_KERNEL)?;
let scope = KBox::pin_init(
mod_data.device_dir.scope(
DeviceData { name, nums, blob },
&file_name,
|dev_data, dir| {
for (idx, val) in dev_data.nums.iter().enumerate() {
let Ok(name) = CString::try_from_fmt(fmt!("{idx}")) else {
return;
};
dir.read_write_file(&name, val);
}
dir.read_write_binary_file(c"blob", &dev_data.blob);
},
),
GFP_KERNEL,
)?;
(*mod_data.devices.lock()).push(scope, GFP_KERNEL)?;
Ok(())
}
struct RustScopedDebugFs {
_data: Pin<KBox<Scope<ModuleData>>>,
}
#[pin_data]
struct ModuleData {
device_dir: Dir,
#[pin]
devices: Mutex<KVec<Pin<KBox<Scope<DeviceData>>>>>,
}
impl ModuleData {
fn init(device_dir: Dir) -> impl PinInit<Self> {
pin_init! {
Self {
device_dir: device_dir,
devices <- new_mutex!(KVec::new())
}
}
}
}
struct DeviceData {
name: CString,
nums: KVec<Atomic<usize>>,
blob: Pin<KBox<Mutex<[u8; SZ_4K]>>>,
}
fn init_control(base_dir: &Dir, dyn_dirs: Dir) -> impl PinInit<Scope<ModuleData>> + '_ {
base_dir.scope(ModuleData::init(dyn_dirs), c"control", |data, dir| {
dir.write_only_callback_file(c"create", data, &create_file_write);
dir.write_only_callback_file(c"remove", data, &remove_file_write);
})
}
impl kernel::Module for RustScopedDebugFs {
fn init(_module: &'static kernel::ThisModule) -> Result<Self> {
let base_dir = Dir::new(c"rust_scoped_debugfs");
let dyn_dirs = base_dir.subdir(c"dynamic");
Ok(Self {
_data: KBox::pin_init(init_control(&base_dir, dyn_dirs), GFP_KERNEL)?,
})
}
}
+133
View File
@@ -0,0 +1,133 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust DMA api test (based on QEMU's `pci-testdev`).
//!
//! To make this driver probe, QEMU must be run with `-device pci-testdev`.
use kernel::{
device::Core,
dma::{
Coherent,
DataDirection,
Device,
DmaMask, //
},
page, pci,
prelude::*,
scatterlist::{Owned, SGTable},
sync::aref::ARef,
};
#[pin_data(PinnedDrop)]
struct DmaSampleDriver {
pdev: ARef<pci::Device>,
ca: Coherent<[MyStruct]>,
#[pin]
sgt: SGTable<Owned<VVec<u8>>>,
}
const TEST_VALUES: [(u32, u32); 5] = [
(0xa, 0xb),
(0xc, 0xd),
(0xe, 0xf),
(0xab, 0xba),
(0xcd, 0xef),
];
struct MyStruct {
h: u32,
b: u32,
}
impl MyStruct {
fn new(h: u32, b: u32) -> Self {
Self { h, b }
}
}
// SAFETY: All bit patterns are acceptable values for `MyStruct`.
unsafe impl kernel::transmute::AsBytes for MyStruct {}
// SAFETY: Instances of `MyStruct` have no uninitialized portions.
unsafe impl kernel::transmute::FromBytes for MyStruct {}
kernel::pci_device_table!(
PCI_TABLE,
MODULE_PCI_TABLE,
<DmaSampleDriver as pci::Driver>::IdInfo,
[(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
);
impl pci::Driver for DmaSampleDriver {
type IdInfo = ();
type Data<'bound> = Self;
const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
fn probe<'bound>(
pdev: &'bound pci::Device<Core<'_>>,
_info: &'bound Self::IdInfo,
) -> impl PinInit<Self, Error> + 'bound {
pin_init::pin_init_scope(move || {
dev_info!(pdev, "Probe DMA test driver.\n");
let mask = DmaMask::new::<64>();
// SAFETY: There are no concurrent calls to DMA allocation and mapping primitives.
unsafe { pdev.dma_set_mask_and_coherent(mask)? };
let ca: Coherent<[MyStruct]> =
Coherent::zeroed_slice(pdev.as_ref(), TEST_VALUES.len(), GFP_KERNEL)?;
for (i, value) in TEST_VALUES.into_iter().enumerate() {
kernel::dma_write!(ca, [try: i], MyStruct::new(value.0, value.1));
}
let size = 4 * page::PAGE_SIZE;
let pages = VVec::with_capacity(size, GFP_KERNEL)?;
let sgt = SGTable::new(pdev.as_ref(), pages, DataDirection::ToDevice, GFP_KERNEL);
Ok(try_pin_init!(Self {
pdev: pdev.into(),
ca,
sgt <- sgt,
}))
})
}
}
impl DmaSampleDriver {
fn check_dma(&self) {
for (i, value) in TEST_VALUES.into_iter().enumerate() {
let val0 = kernel::dma_read!(self.ca, [panic: i].h);
let val1 = kernel::dma_read!(self.ca, [panic: i].b);
assert_eq!(val0, value.0);
assert_eq!(val1, value.1);
}
}
}
#[pinned_drop]
impl PinnedDrop for DmaSampleDriver {
fn drop(self: Pin<&mut Self>) {
dev_info!(self.pdev, "Unload DMA test driver.\n");
self.check_dma();
for (i, entry) in self.sgt.iter().enumerate() {
dev_info!(
self.pdev,
"Entry[{}]: DMA address: {:#x}",
i,
entry.dma_address(),
);
}
}
}
kernel::module_pci_driver! {
type: DmaSampleDriver,
name: "rust_dma",
authors: ["Abdiel Janulgue"],
description: "Rust DMA test",
license: "GPL v2",
}
@@ -0,0 +1,162 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust auxiliary driver sample (based on a PCI driver for QEMU's `pci-testdev`).
//!
//! To make this driver probe, QEMU must be run with `-device pci-testdev`.
use kernel::{
auxiliary,
device::{
Bound,
Core, //
},
driver,
pci,
prelude::*,
types::ForLt,
InPlaceModule, //
};
const MODULE_NAME: &CStr = <LocalModule as kernel::ModuleMetadata>::NAME;
const AUXILIARY_NAME: &CStr = c"auxiliary";
struct AuxiliaryDriver;
kernel::auxiliary_device_table!(
AUX_TABLE,
MODULE_AUX_TABLE,
<AuxiliaryDriver as auxiliary::Driver>::IdInfo,
[(auxiliary::DeviceId::new(MODULE_NAME, AUXILIARY_NAME), ())]
);
impl auxiliary::Driver for AuxiliaryDriver {
type IdInfo = ();
type Data<'bound> = Self;
const ID_TABLE: auxiliary::IdTable<Self::IdInfo> = &AUX_TABLE;
fn probe<'bound>(
adev: &'bound auxiliary::Device<Core<'_>>,
_info: &'bound Self::IdInfo,
) -> impl PinInit<Self, Error> + 'bound {
dev_info!(
adev,
"Probing auxiliary driver for auxiliary device with id={}\n",
adev.id()
);
ParentDriver::connect(adev)?;
Ok(Self)
}
}
struct Data<'bound> {
index: u32,
parent: &'bound pci::Device<Bound>,
}
struct ParentDriver;
#[allow(clippy::type_complexity)]
struct ParentData<'bound> {
_reg0: auxiliary::Registration<'bound, ForLt!(Data<'_>)>,
_reg1: auxiliary::Registration<'bound, ForLt!(Data<'_>)>,
}
kernel::pci_device_table!(
PCI_TABLE,
MODULE_PCI_TABLE,
<ParentDriver as pci::Driver>::IdInfo,
[(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
);
impl pci::Driver for ParentDriver {
type IdInfo = ();
type Data<'bound> = ParentData<'bound>;
const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
fn probe<'bound>(
pdev: &'bound pci::Device<Core<'_>>,
_info: &'bound Self::IdInfo,
) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
Ok(ParentData {
// SAFETY: `ParentData` is the driver's private data, which is dropped when the
// device is unbound; i.e. `mem::forget()` is never called on it.
_reg0: unsafe {
auxiliary::Registration::new_with_lt(
pdev.as_ref(),
AUXILIARY_NAME,
0,
MODULE_NAME,
Data {
index: 0,
parent: pdev,
},
)?
},
// SAFETY: See `_reg0` above.
_reg1: unsafe {
auxiliary::Registration::new_with_lt(
pdev.as_ref(),
AUXILIARY_NAME,
1,
MODULE_NAME,
Data {
index: 1,
parent: pdev,
},
)?
},
})
}
}
impl ParentDriver {
fn connect(adev: &auxiliary::Device<Bound>) -> Result {
let data = adev.registration_data::<ForLt!(Data<'_>)>()?;
let pdev = data.parent;
dev_info!(
pdev,
"Connect auxiliary {} with parent: VendorID={}, DeviceID={:#x}\n",
adev.id(),
pdev.vendor_id(),
pdev.device_id()
);
dev_info!(
pdev,
"Connected to auxiliary device with index {}.\n",
data.index
);
Ok(())
}
}
#[pin_data]
struct SampleModule {
#[pin]
_pci_driver: driver::Registration<pci::Adapter<ParentDriver>>,
#[pin]
_aux_driver: driver::Registration<auxiliary::Adapter<AuxiliaryDriver>>,
}
impl InPlaceModule for SampleModule {
fn init(module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
try_pin_init!(Self {
_pci_driver <- driver::Registration::new(MODULE_NAME, module),
_aux_driver <- driver::Registration::new(MODULE_NAME, module),
})
}
}
module! {
type: SampleModule,
name: "rust_driver_auxiliary",
authors: ["Danilo Krummrich"],
description: "Rust auxiliary driver",
license: "GPL v2",
}
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: GPL-2.0-only
//! Rust faux device sample.
use kernel::{
faux,
prelude::*,
Module, //
};
module! {
type: SampleModule,
name: "rust_faux_driver",
authors: ["Lyude Paul"],
description: "Rust faux device sample",
license: "GPL",
}
struct SampleModule {
_reg: faux::Registration,
}
impl Module for SampleModule {
fn init(_module: &'static ThisModule) -> Result<Self> {
pr_info!("Initialising Rust Faux Device Sample\n");
let reg = faux::Registration::new(c"rust-faux-sample-device", None)?;
dev_info!(reg, "Hello from faux device!\n");
Ok(Self { _reg: reg })
}
}
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust I2C driver sample.
use kernel::{
acpi,
device::Core,
i2c,
of,
prelude::*, //
};
struct SampleDriver;
kernel::acpi_device_table! {
ACPI_TABLE,
MODULE_ACPI_TABLE,
<SampleDriver as i2c::Driver>::IdInfo,
[(acpi::DeviceId::new(c"LNUXBEEF"), 0)]
}
kernel::i2c_device_table! {
I2C_TABLE,
MODULE_I2C_TABLE,
<SampleDriver as i2c::Driver>::IdInfo,
[(i2c::DeviceId::new(c"rust_driver_i2c"), 0)]
}
kernel::of_device_table! {
OF_TABLE,
MODULE_OF_TABLE,
<SampleDriver as i2c::Driver>::IdInfo,
[(of::DeviceId::new(c"test,rust_driver_i2c"), 0)]
}
impl i2c::Driver for SampleDriver {
type IdInfo = u32;
type Data<'bound> = Self;
const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
const I2C_ID_TABLE: Option<i2c::IdTable<Self::IdInfo>> = Some(&I2C_TABLE);
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
fn probe<'bound>(
idev: &'bound i2c::I2cClient<Core<'_>>,
info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self, Error> + 'bound {
let dev = idev.as_ref();
dev_info!(dev, "Probe Rust I2C driver sample.\n");
if let Some(info) = info {
dev_info!(dev, "Probed with info: '{}'.\n", info);
}
Ok(Self)
}
fn shutdown<'bound>(idev: &'bound i2c::I2cClient<Core<'_>>, _this: Pin<&Self>) {
dev_info!(idev.as_ref(), "Shutdown Rust I2C driver sample.\n");
}
fn unbind<'bound>(idev: &'bound i2c::I2cClient<Core<'_>>, _this: Pin<&Self>) {
dev_info!(idev.as_ref(), "Unbind Rust I2C driver sample.\n");
}
}
kernel::module_i2c_driver! {
type: SampleDriver,
name: "rust_driver_i2c",
authors: ["Igor Korotin"],
description: "Rust I2C driver",
license: "GPL v2",
}
+194
View File
@@ -0,0 +1,194 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust PCI driver sample (based on QEMU's `pci-testdev`).
//!
//! To make this driver probe, QEMU must be run with `-device pci-testdev`.
use kernel::{
device::{
Bound,
Core, //
},
io::{
register,
register::Array,
Io, //
},
num::Bounded,
pci,
prelude::*, //
};
mod regs {
use super::*;
register! {
pub(super) TEST(u8) @ 0x0 {
7:0 index => TestIndex;
}
pub(super) OFFSET(u32) @ 0x4 {
31:0 offset;
}
pub(super) DATA(u8) @ 0x8 {
7:0 data;
}
pub(super) COUNT(u32) @ 0xC {
31:0 count;
}
}
pub(super) const END: usize = 0x10;
}
type Bar0<'bound> = pci::Bar<'bound, { regs::END }>;
#[derive(Copy, Clone, Debug)]
struct TestIndex(u8);
impl From<Bounded<u8, 8>> for TestIndex {
fn from(value: Bounded<u8, 8>) -> Self {
Self(value.into())
}
}
impl From<TestIndex> for Bounded<u8, 8> {
fn from(value: TestIndex) -> Self {
value.0.into()
}
}
impl TestIndex {
const NO_EVENTFD: Self = Self(0);
}
struct SampleDriverData<'bound> {
pdev: &'bound pci::Device,
bar: Bar0<'bound>,
index: TestIndex,
}
struct SampleDriver;
kernel::pci_device_table!(
PCI_TABLE,
MODULE_PCI_TABLE,
<SampleDriver as pci::Driver>::IdInfo,
[(
pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5),
TestIndex::NO_EVENTFD
)]
);
impl SampleDriverData<'_> {
fn testdev(index: &TestIndex, bar: &Bar0<'_>) -> Result<u32> {
// Select the test.
bar.write_reg(regs::TEST::zeroed().with_index(*index));
let offset = bar.read(regs::OFFSET).into_raw() as usize;
let data = bar.read(regs::DATA).into();
// Write `data` to `offset` to increase `count` by one.
//
// Note that we need `try_write8`, since `offset` can't be checked at compile-time.
bar.try_write8(data, offset)?;
Ok(bar.read(regs::COUNT).into())
}
fn config_space(pdev: &pci::Device<Bound>) {
let config = pdev.config_space();
// Some PCI configuration space registers.
register! {
VENDOR_ID(u16) @ 0x0 {
15:0 vendor_id;
}
REVISION_ID(u8) @ 0x8 {
7:0 revision_id;
}
BAR(u32)[6] @ 0x10 {
31:0 value;
}
}
dev_info!(
pdev,
"pci-testdev config space read8 rev ID: {:x}\n",
config.read(REVISION_ID).revision_id()
);
dev_info!(
pdev,
"pci-testdev config space read16 vendor ID: {:x}\n",
config.read(VENDOR_ID).vendor_id()
);
dev_info!(
pdev,
"pci-testdev config space read32 BAR 0: {:x}\n",
config.read(BAR::at(0)).value()
);
}
}
impl pci::Driver for SampleDriver {
type IdInfo = TestIndex;
type Data<'bound> = SampleDriverData<'bound>;
const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
fn probe<'bound>(
pdev: &'bound pci::Device<Core<'_>>,
info: &'bound Self::IdInfo,
) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
let vendor = pdev.vendor_id();
dev_dbg!(
pdev,
"Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n",
vendor,
pdev.device_id()
);
pdev.enable_device_mem()?;
pdev.set_master();
let bar = pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci")?;
dev_info!(
pdev,
"pci-testdev data-match count: {}\n",
SampleDriverData::testdev(info, &bar)?
);
SampleDriverData::config_space(pdev);
Ok(SampleDriverData {
pdev,
bar,
index: *info,
})
}
fn unbind<'bound>(_pdev: &'bound pci::Device<Core<'_>>, this: Pin<&Self::Data<'bound>>) {
this.bar
.write_reg(regs::TEST::zeroed().with_index(this.index));
}
}
impl Drop for SampleDriverData<'_> {
fn drop(&mut self) {
dev_dbg!(self.pdev, "Remove Rust PCI driver sample.\n");
}
}
kernel::module_pci_driver! {
type: SampleDriver,
name: "rust_driver_pci",
authors: ["Danilo Krummrich"],
description: "Rust PCI driver",
license: "GPL v2",
}
@@ -0,0 +1,194 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust Platform driver sample.
//! ACPI match table test
//!
//! This demonstrates how to test an ACPI-based Rust platform driver using QEMU
//! with a custom SSDT.
//!
//! Steps:
//!
//! 1. **Create an SSDT source file** (`ssdt.dsl`) with the following content:
//!
//! ```asl
//! DefinitionBlock ("", "SSDT", 2, "TEST", "VIRTACPI", 0x00000001)
//! {
//! Scope (\_SB)
//! {
//! Device (T432)
//! {
//! Name (_HID, "LNUXBEEF") // ACPI hardware ID to match
//! Name (_UID, 1)
//! Name (_STA, 0x0F) // Device present, enabled
//! Name (_CRS, ResourceTemplate ()
//! {
//! Memory32Fixed (ReadWrite, 0xFED00000, 0x1000)
//! })
//! }
//! }
//! }
//! ```
//!
//! 2. **Compile the table**:
//!
//! ```sh
//! iasl -tc ssdt.dsl
//! ```
//!
//! This generates `ssdt.aml`
//!
//! 3. **Run QEMU** with the compiled AML file:
//!
//! ```sh
//! qemu-system-x86_64 -m 512M \
//! -enable-kvm \
//! -kernel path/to/bzImage \
//! -append "root=/dev/sda console=ttyS0" \
//! -hda rootfs.img \
//! -serial stdio \
//! -acpitable file=ssdt.aml
//! ```
//!
//! Requirements:
//! - The `rust_driver_platform` must be present either:
//! - built directly into the kernel (`bzImage`), or
//! - available as a `.ko` file and loadable from `rootfs.img`
//!
//! 4. **Verify it worked** by checking `dmesg`:
//!
//! ```
//! rust_driver_platform LNUXBEEF:00: Probed with info: '0'.
//! ```
//!
use kernel::{
acpi,
device::{
self,
property::{
FwNodeReferenceArgs,
NArgs, //
},
Core,
},
of,
platform,
prelude::*,
str::CString,
sync::aref::ARef, //
};
struct SampleDriver {
pdev: ARef<platform::Device>,
}
struct Info(u32);
kernel::of_device_table!(
OF_TABLE,
MODULE_OF_TABLE,
<SampleDriver as platform::Driver>::IdInfo,
[(of::DeviceId::new(c"test,rust-device"), Info(42))]
);
kernel::acpi_device_table!(
ACPI_TABLE,
MODULE_ACPI_TABLE,
<SampleDriver as platform::Driver>::IdInfo,
[(acpi::DeviceId::new(c"LNUXBEEF"), Info(0))]
);
impl platform::Driver for SampleDriver {
type IdInfo = Info;
type Data<'bound> = Self;
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
fn probe<'bound>(
pdev: &'bound platform::Device<Core<'_>>,
info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self, Error> + 'bound {
let dev = pdev.as_ref();
dev_dbg!(dev, "Probe Rust Platform driver sample.\n");
if let Some(info) = info {
dev_info!(dev, "Probed with info: '{}'.\n", info.0);
}
if dev.fwnode().is_some_and(|node| node.is_of_node()) {
Self::properties_parse(dev)?;
}
Ok(Self { pdev: pdev.into() })
}
}
impl SampleDriver {
fn properties_parse(dev: &device::Device) -> Result {
let fwnode = dev.fwnode().ok_or(ENOENT)?;
if let Ok(idx) = fwnode.property_match_string(c"compatible", c"test,rust-device") {
dev_info!(dev, "matched compatible string idx = {}\n", idx);
}
let name = c"compatible";
let prop = fwnode.property_read::<CString>(name).required_by(dev)?;
dev_info!(dev, "'{name}'='{prop:?}'\n");
let name = c"test,bool-prop";
let prop = fwnode.property_read_bool(c"test,bool-prop");
dev_info!(dev, "'{name}'='{prop}'\n");
if fwnode.property_present(c"test,u32-prop") {
dev_info!(dev, "'test,u32-prop' is present\n");
}
let name = c"test,u32-optional-prop";
let prop = fwnode.property_read::<u32>(name).or(0x12);
dev_info!(dev, "'{name}'='{prop:#x}' (default = 0x12)\n");
// A missing required property will print an error. Discard the error to
// prevent properties_parse from failing in that case.
let name = c"test,u32-required-prop";
let _ = fwnode.property_read::<u32>(name).required_by(dev);
let name = c"test,u32-prop";
let prop: u32 = fwnode.property_read(name).required_by(dev)?;
dev_info!(dev, "'{name}'='{prop:#x}'\n");
let name = c"test,i16-array";
let prop: [i16; 4] = fwnode.property_read(name).required_by(dev)?;
dev_info!(dev, "'{name}'='{prop:?}'\n");
let len = fwnode.property_count_elem::<u16>(name)?;
dev_info!(dev, "'{name}' length is {len}\n");
let name = c"test,i16-array";
let prop: KVec<i16> = fwnode.property_read_array_vec(name, 4)?.required_by(dev)?;
dev_info!(dev, "'{name}'='{prop:?}' (KVec)\n");
for child in fwnode.children() {
let name = c"test,ref-arg";
let nargs = NArgs::N(2);
let prop: FwNodeReferenceArgs = child.property_get_reference_args(name, nargs, 0)?;
dev_info!(dev, "'{name}'='{prop:?}'\n");
}
Ok(())
}
}
impl Drop for SampleDriver {
fn drop(&mut self) {
dev_dbg!(self.pdev, "Remove Rust Platform driver sample.\n");
}
}
kernel::module_platform_driver! {
type: SampleDriver,
name: "rust_driver_platform",
authors: ["Danilo Krummrich"],
description: "Rust Platform driver",
license: "GPL v2",
}
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: GPL-2.0
// SPDX-FileCopyrightText: Copyright (C) 2025 Collabora Ltd.
//! Rust USB driver sample.
use kernel::{
device::{
self,
Core, //
},
prelude::*,
sync::aref::ARef,
usb, //
};
struct SampleDriver {
_intf: ARef<usb::Interface>,
}
kernel::usb_device_table!(
USB_TABLE,
MODULE_USB_TABLE,
<SampleDriver as usb::Driver>::IdInfo,
[(usb::DeviceId::from_id(0x1234, 0x5678), ()),]
);
impl usb::Driver for SampleDriver {
type IdInfo = ();
type Data<'bound> = Self;
const ID_TABLE: usb::IdTable<Self::IdInfo> = &USB_TABLE;
fn probe<'bound>(
intf: &'bound usb::Interface<Core<'_>>,
_id: &usb::DeviceId,
_info: &'bound Self::IdInfo,
) -> impl PinInit<Self, Error> + 'bound {
let dev: &device::Device<Core<'_>> = intf.as_ref();
dev_info!(dev, "Rust USB driver sample probed\n");
Ok(Self { _intf: intf.into() })
}
fn disconnect<'bound>(intf: &'bound usb::Interface<Core<'_>>, _data: Pin<&Self>) {
let dev: &device::Device<Core<'_>> = intf.as_ref();
dev_info!(dev, "Rust USB driver sample disconnected\n");
}
}
kernel::module_usb_driver! {
type: SampleDriver,
name: "rust_driver_usb",
authors: ["Daniel Almeida"],
description: "Rust USB driver sample",
license: "GPL v2",
}
+150
View File
@@ -0,0 +1,150 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust I2C client registration sample.
//!
//! An I2C client in Rust cannot exist on its own. To register a new I2C client,
//! it must be bound to a parent device. In this sample driver, a platform device
//! is used as the parent.
//!
//! ACPI match table test
//!
//! This demonstrates how to test an ACPI-based Rust I2C client registration driver
//! using QEMU with a custom SSDT.
//!
//! Steps:
//!
//! 1. **Create an SSDT source file** (`ssdt.dsl`) with the following content:
//!
//! ```asl
//! DefinitionBlock ("", "SSDT", 2, "TEST", "VIRTACPI", 0x00000001)
//! {
//! Scope (\_SB)
//! {
//! Device (T432)
//! {
//! Name (_HID, "LNUXBEEF") // ACPI hardware ID to match
//! Name (_UID, 1)
//! Name (_STA, 0x0F) // Device present, enabled
//! Name (_CRS, ResourceTemplate ()
//! {
//! Memory32Fixed (ReadWrite, 0xFED00000, 0x1000)
//! })
//! }
//! }
//! }
//! ```
//!
//! 2. **Compile the table**:
//!
//! ```sh
//! iasl -tc ssdt.dsl
//! ```
//!
//! This generates `ssdt.aml`
//!
//! 3. **Run QEMU** with the compiled AML file:
//!
//! ```sh
//! qemu-system-x86_64 -m 512M \
//! -enable-kvm \
//! -kernel path/to/bzImage \
//! -append "root=/dev/sda console=ttyS0" \
//! -hda rootfs.img \
//! -serial stdio \
//! -acpitable file=ssdt.aml
//! ```
//!
//! Requirements:
//! - The `rust_driver_platform` must be present either:
//! - built directly into the kernel (`bzImage`), or
//! - available as a `.ko` file and loadable from `rootfs.img`
//!
//! 4. **Verify it worked** by checking `dmesg`:
//!
//! ```
//! rust_driver_platform LNUXBEEF:00: Probed with info: '0'.
//! ```
//!
use kernel::{
acpi,
device,
devres::Devres,
i2c,
of,
platform,
prelude::*,
sync::aref::ARef, //
};
#[pin_data]
struct SampleDriver {
parent_dev: ARef<platform::Device>,
#[pin]
_reg: Devres<i2c::Registration>,
}
kernel::of_device_table!(
OF_TABLE,
MODULE_OF_TABLE,
<SampleDriver as platform::Driver>::IdInfo,
[(of::DeviceId::new(c"test,rust-device"), ())]
);
kernel::acpi_device_table!(
ACPI_TABLE,
MODULE_ACPI_TABLE,
<SampleDriver as platform::Driver>::IdInfo,
[(acpi::DeviceId::new(c"LNUXBEEF"), ())]
);
const SAMPLE_I2C_CLIENT_ADDR: u16 = 0x30;
const SAMPLE_I2C_ADAPTER_INDEX: i32 = 0;
const BOARD_INFO: i2c::I2cBoardInfo =
i2c::I2cBoardInfo::new(c"rust_driver_i2c", SAMPLE_I2C_CLIENT_ADDR);
impl platform::Driver for SampleDriver {
type IdInfo = ();
type Data<'bound> = Self;
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
fn probe<'bound>(
pdev: &'bound platform::Device<device::Core<'_>>,
_info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self, Error> + 'bound {
dev_info!(
pdev.as_ref(),
"Probe Rust I2C Client registration sample.\n"
);
kernel::try_pin_init!( Self {
parent_dev: pdev.into(),
_reg <- {
let adapter = i2c::I2cAdapter::get(SAMPLE_I2C_ADAPTER_INDEX)?;
i2c::Registration::new(&adapter, &BOARD_INFO, pdev.as_ref())
}
})
}
fn unbind<'bound>(
pdev: &'bound platform::Device<device::Core<'_>>,
_this: Pin<&Self::Data<'bound>>,
) {
dev_info!(
pdev.as_ref(),
"Unbind Rust I2C Client registration sample.\n"
);
}
}
kernel::module_platform_driver! {
type: SampleDriver,
name: "rust_device_i2c",
authors: ["Danilo Krummrich", "Igor Korotin"],
description: "Rust I2C client registration",
license: "GPL v2",
}
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust minimal sample.
use kernel::prelude::*;
module! {
type: RustMinimal,
name: "rust_minimal",
authors: ["Rust for Linux Contributors"],
description: "Rust minimal sample",
license: "GPL",
params: {
test_parameter: i64 {
default: 1,
description: "This parameter has a default of 1",
},
},
}
struct RustMinimal {
numbers: KVec<i32>,
}
impl kernel::Module for RustMinimal {
fn init(_module: &'static ThisModule) -> Result<Self> {
pr_info!("Rust minimal sample (init)\n");
pr_info!("Am I built-in? {}\n", !cfg!(MODULE));
pr_info!(
"test_parameter: {}\n",
*module_parameters::test_parameter.value()
);
let mut numbers = KVec::new();
numbers.push(72, GFP_KERNEL)?;
numbers.push(108, GFP_KERNEL)?;
numbers.push(200, GFP_KERNEL)?;
Ok(RustMinimal { numbers })
}
}
impl Drop for RustMinimal {
fn drop(&mut self) {
pr_info!("My numbers are {:?}\n", self.numbers);
pr_info!("Rust minimal sample (exit)\n");
}
}
@@ -0,0 +1,291 @@
// SPDX-License-Identifier: GPL-2.0
// Copyright (C) 2024 Google LLC.
//! 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 kernel::{
device::Device,
fs::{
File,
Kiocb, //
},
ioctl::{
_IO,
_IOC_SIZE,
_IOR,
_IOW, //
},
iov::{
IovIterDest,
IovIterSource, //
},
miscdevice::{
MiscDevice,
MiscDeviceOptions,
MiscDeviceRegistration, //
},
new_mutex,
prelude::*,
sync::{
aref::ARef,
Mutex, //
},
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,
name: "rust_misc_device",
authors: ["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"rust-misc-device",
};
try_pin_init!(Self {
_miscdev <- MiscDeviceRegistration::register(options),
})
}
}
struct Inner {
value: i32,
buffer: KVVec<u8>,
}
#[pin_data(PinnedDrop)]
struct RustMiscDevice {
#[pin]
inner: Mutex<Inner>,
dev: ARef<Device>,
}
#[vtable]
impl MiscDevice for RustMiscDevice {
type Ptr = Pin<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");
KBox::try_pin_init(
try_pin_init! {
RustMiscDevice {
inner <- new_mutex!(Inner {
value: 0_i32,
buffer: KVVec::new(),
}),
dev: dev,
}
},
GFP_KERNEL,
)
}
fn read_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterDest<'_>) -> Result<usize> {
let me = kiocb.file();
dev_info!(me.dev, "Reading from Rust Misc Device Sample\n");
let inner = me.inner.lock();
// Read the buffer contents, taking the file position into account.
let read = iov.simple_read_from_buffer(kiocb.ki_pos_mut(), &inner.buffer)?;
Ok(read)
}
fn write_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterSource<'_>) -> Result<usize> {
let me = kiocb.file();
dev_info!(me.dev, "Writing to Rust Misc Device Sample\n");
let mut inner = me.inner.lock();
// Replace buffer contents.
inner.buffer.clear();
let len = iov.copy_from_iter_vec(&mut inner.buffer, GFP_KERNEL)?;
// Set position to zero so that future `read` calls will see the new contents.
*kiocb.ki_pos_mut() = 0;
Ok(len)
}
fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize) -> Result<isize> {
dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n");
// Treat the ioctl argument as a user pointer.
let arg = UserPtr::from_addr(arg);
let size = _IOC_SIZE(cmd);
match cmd {
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)
}
}
#[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)
}
}
@@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright 2024 Google LLC
*/
#define CREATE_TRACE_POINTS
#define CREATE_RUST_TRACE_POINTS
#include <trace/events/rust_sample.h>
+117
View File
@@ -0,0 +1,117 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust printing macros sample.
use kernel::pr_cont;
use kernel::prelude::*;
module! {
type: RustPrint,
name: "rust_print",
authors: ["Rust for Linux Contributors"],
description: "Rust printing macros sample",
license: "GPL",
}
struct RustPrint;
#[expect(clippy::disallowed_macros)]
fn arc_print() -> Result {
use kernel::sync::*;
let a = Arc::new(1, GFP_KERNEL)?;
let b = UniqueArc::new("hello, world", GFP_KERNEL)?;
// Prints the value of data in `a`.
pr_info!("{}", a);
// Uses ":?" to print debug fmt of `b`.
pr_info!("{:?}", b);
let a: Arc<&str> = b.into();
let c = a.clone();
// Uses `dbg` to print, will move `c` (for temporary debugging purposes).
dbg!(c);
{
// `Arc` can be used to delegate dynamic dispatch and the following is an example.
// Both `i32` and `&str` implement `Display`. This enables us to express a unified
// behaviour, contract or protocol on both `i32` and `&str` into a single `Arc` of
// type `Arc<dyn Display>`.
use kernel::fmt::Display;
fn arc_dyn_print(arc: &Arc<dyn Display>) {
pr_info!("Arc<dyn Display> says {arc}");
}
let a_i32_display: Arc<dyn Display> = Arc::new(42i32, GFP_KERNEL)?;
let a_str_display: Arc<dyn Display> = a.clone();
arc_dyn_print(&a_i32_display);
arc_dyn_print(&a_str_display);
}
// Pretty-prints the debug formatting with lower-case hexadecimal integers.
pr_info!("{:#x?}", a);
Ok(())
}
impl kernel::Module for RustPrint {
fn init(_module: &'static ThisModule) -> Result<Self> {
pr_info!("Rust printing macros sample (init)\n");
pr_emerg!("Emergency message (level 0) without args\n");
pr_alert!("Alert message (level 1) without args\n");
pr_crit!("Critical message (level 2) without args\n");
pr_err!("Error message (level 3) without args\n");
pr_warn!("Warning message (level 4) without args\n");
pr_notice!("Notice message (level 5) without args\n");
pr_info!("Info message (level 6) without args\n");
pr_info!("A line that");
pr_cont!(" is continued");
pr_cont!(" without args\n");
pr_emerg!("{} message (level {}) with args\n", "Emergency", 0);
pr_alert!("{} message (level {}) with args\n", "Alert", 1);
pr_crit!("{} message (level {}) with args\n", "Critical", 2);
pr_err!("{} message (level {}) with args\n", "Error", 3);
pr_warn!("{} message (level {}) with args\n", "Warning", 4);
pr_notice!("{} message (level {}) with args\n", "Notice", 5);
pr_info!("{} message (level {}) with args\n", "Info", 6);
pr_info!("A {} that", "line");
pr_cont!(" is {}", "continued");
pr_cont!(" with {}\n", "args");
arc_print()?;
trace::trace_rust_sample_loaded(42);
Ok(RustPrint)
}
}
impl Drop for RustPrint {
fn drop(&mut self) {
pr_info!("Rust printing macros sample (exit)\n");
}
}
mod trace {
use kernel::prelude::*;
kernel::declare_trace! {
/// # Safety
///
/// Always safe to call.
unsafe fn rust_sample_loaded(magic: c_int);
}
pub(crate) fn trace_rust_sample_loaded(magic: i32) {
// SAFETY: Always safe to call.
unsafe { rust_sample_loaded(magic as c_int) }
}
}
+80
View File
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: GPL-2.0
//! Rust SoC Platform driver sample.
use kernel::{
acpi,
device::Core,
of,
platform,
prelude::*,
soc,
str::CString,
sync::aref::ARef, //
};
use pin_init::pin_init_scope;
#[pin_data]
struct SampleSocDriver {
pdev: ARef<platform::Device>,
#[pin]
_dev_reg: soc::Registration,
}
kernel::of_device_table!(
OF_TABLE,
MODULE_OF_TABLE,
<SampleSocDriver as platform::Driver>::IdInfo,
[(of::DeviceId::new(c"test,rust-device"), ())]
);
kernel::acpi_device_table!(
ACPI_TABLE,
MODULE_ACPI_TABLE,
<SampleSocDriver as platform::Driver>::IdInfo,
[(acpi::DeviceId::new(c"LNUXBEEF"), ())]
);
impl platform::Driver for SampleSocDriver {
type IdInfo = ();
type Data<'bound> = Self;
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
fn probe<'bound>(
pdev: &'bound platform::Device<Core<'_>>,
_info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self, Error> + 'bound {
dev_dbg!(pdev, "Probe Rust SoC driver sample.\n");
let pdev = pdev.into();
pin_init_scope(move || {
let machine = CString::try_from(c"My cool ACME15 dev board")?;
let family = CString::try_from(c"ACME")?;
let revision = CString::try_from(c"1.2")?;
let serial_number = CString::try_from(c"12345")?;
let soc_id = CString::try_from(c"ACME15")?;
let attr = soc::Attributes {
machine: Some(machine),
family: Some(family),
revision: Some(revision),
serial_number: Some(serial_number),
soc_id: Some(soc_id),
};
Ok(try_pin_init!(SampleSocDriver {
pdev: pdev,
_dev_reg <- soc::Registration::new(attr),
}? Error))
})
}
}
kernel::module_platform_driver! {
type: SampleSocDriver,
name: "rust_soc",
authors: ["Matthew Maurer"],
description: "Rust SoC Driver",
license: "GPL",
}