// Cargo.toml for this kernel module (place in a directory like `blinky-driver`)
// [package]
// name = "blinky-driver"
// version = "0.1.0"
// edition = "2021"
//
// [lib]
// crate-type = ["cdylib"]
//
// [dependencies]
// kernel = { git = "https://github.com/Rust-for-Linux/linux.git", tag = "rust-6.10" } # Adjust tag to your kernel version
// [dependencies.kernel.-features]
// CONFIG_BLINKY = []
//! A simple Rust Linux kernel module driver for a custom "Blinky LED Controller" hardware component.
//!
//! ## Hardware Description
//! This driver is for a fictional custom hardware component called "Blinky LED Controller":
//! - **Memory-mapped I/O base address**: `0x1000_0000` (platform-specific, e.g., via device tree).
//! - **Registers**:
//! | Offset | Name | Description |
//! |--------|---------|--------------------------------------|
//! | `0x00` | `CTRL` | Bit 0: Enable (1=enable blinking) |
//! | `0x04` | `STATUS`| Bit 0: Busy (1=blinking in progress) |
//! | `0x08` | `PERIOD`| 32-bit: Blink period in ms (1-65535) |
//!
//! The hardware blinks an LED at the specified period when enabled.
//!
//! ## Prerequisites
//! 1. Linux kernel with Rust support: Follow https://rust-for-linux.com/ (e.g., kernel 6.10+).
//! 2. Device tree overlay or platform data exposing the MMIO region at `0x1000_0000` (for real HW).
//! For testing: Use QEMU virt machine with a custom PL011-like MMIO region or simulate in code.
//! 3. Build: `make -C /path/to/linux M=$PWD modules` (with Rust toolchain).
//! 4. Load: `insmod blinky.ko`, check `/proc/devices` for major number.
//! 5. Char device: `/dev/blinky` (write "1" to enable, "0" to disable; echo period via ioctl if extended).
//!
//! ## Safety Notes
//! - This is a basic example. Production drivers need more error handling, locking, and PM support.
//! - MMIO access uses `core::ptr::read_volatile` and `write_volatile` for correctness.
//! - Tested conceptually; adapt for your exact kernel/hardware.
#![no_std]
#![no_main]
use kernel::{
c_types::c_uint,
chrdev::{
self, register_chrdev_region, unregister_chrdev_region,
ProbeResult::{self, Allocated},
},
device::Device,
error::Result,
file::File,
io_buffer::IoBuffer,
iov_iter::IoSlice,
prelude::*,
pr_info,
sync::{Mutex, UniqueRef},
ThisModule,
};
const BLINKY_BASE_ADDR: usize = 0x1000_0000;
const BLINKY_MMIO_SIZE: usize = 0x10;
const BLINKY_NAME: &'static str = "blinky";
const BLINKY_CLASS_NAME: &'static str = "blinky";
register_module!(BlinkyDriver);
module_param!(enable_logging, bool, 0644, "Enable debug logging");
struct BlinkyRegs {
ctrl: *mut u32,
status: *mut u32,
period: *mut u32,
}
impl BlinkyRegs {
unsafe fn new(base: usize) -> Result<Self> {
core::ptr::write_bytes(base as *mut u8, 0, BLINKY_MMIO_SIZE);
Ok(Self {
ctrl: (base + 0x00) as *mut u32,
status: (base + 0x04) as *mut u32,
period: (base + 0x08) as *mut u32,
})
}
fn enable(&self, on: bool) {
unsafe {
core::ptr::write_volatile(
self.ctrl,
if on { core::ptr::read_volatile(self.ctrl) | 1 } else { 0 },
);
}
}
fn set_period(&self, ms: u32) {
unsafe {
core::ptr::write_volatile(self.period, ms.min(65535));
}
}
fn is_busy(&self) -> bool {
unsafe { core::ptr::read_volatile(self.status) & 1 != 0 }
}
}
#[derive(Clone)]
struct BlinkyDev {
regs: UniqueRef<BlinkyRegs>,
}
static mut MAJOR: u32 = 0;
impl BlinkyDev {
fn new() -> Result<Self> {
let regs = unsafe { BlinkyRegs::new(BLINKY_BASE_ADDR)? }?;
Ok(Self { regs: UniqueRef::try_new(regs)? })
}
}
impl kernel::Driver for BlinkyDev {
const NAME: &'static str = BLINKY_NAME;
fn probe(_dev: &kernel::platform::Device) -> Result<Self> {
let dev = Self::new()?;
pr_info!("Blinky driver probed at {:#x}\n", BLINKY_BASE_ADDR);
Ok(dev)
}
}
impl Device for BlinkyDev {
fn release(self: core::pin::Pin<&mut Self>) {
pr_info!("Blinky device released\n");
}
}
struct BlinkyFile {
dev: core::pin::Pin<&'static mut BlinkyDev>,
}
impl File for BlinkyFile {
type Arg = core::pin::Pin<&'static mut BlinkyDev>;
fn open(shared: &Self::Arg) -> Result<Self> {
Ok(Self { dev: shared.clone() })
}
fn release(self: core::pin::Pin<&mut Self>) {
// Cleanup if needed
}
fn write(&self, _iov: &mut kernel::iov_iter::IoSliceMut) -> Result<usize> {
// Simple: write "1\n" to enable, "0\n" to disable
let mut buf = [0u8; 2];
let len = IoBuffer::try_new(&mut buf[..])?.read_from_iter(_iov)?;
if len > 0 {
let cmd = buf[0] as char;
match cmd {
'1' => self.dev.regs.enable(true),
'0' => self.dev.regs.enable(false),
_ => return Err(kernel::Error::EINVAL),
}
pr_info!("Blinky {} (busy: {})\n", cmd, self.dev.regs.is_busy());
}
Ok(len)
}
fn read(&self, _iov: &mut kernel::iov_iter::IoSlice) -> Result<usize> {
// Read status as "1" if busy, "0" otherwise
let status = if self.dev.regs.is_busy() { b"1\n" } else { b"0\n" };
let mut buf = IoBuffer::new(status);
buf.write_to_iter(_iov)
}
}
impl chrdev::Device for BlinkyDev {
type FopsData = BlinkyFile;
fn chrdev_open(&self) -> Self::FopsData {
BlinkyFile {
dev: self.into_ref(), // Pin to static lifetime
}
}
}
kernel::init!(BlinkyDriver);
struct BlinkyDriver;
impl kernel::PlatformDriver for BlinkyDriver {
type Device = BlinkyDev;
const PLATFORM_DRIVER_NAME: &'static str = BLINKY_NAME;
fn probe(dev: kernel::platform::PlatformDevice) -> ProbeResult<Self::Device> {
match BlinkyDev::probe(&dev) {
Ok(dev) => Allocated(dev),
Err(err) => ProbeResult::No {
error: err.into(),
dev,
},
}
}
}
// Module init/exit
kernel::module_platform_driver!(BlinkyDriver);
kernel::task!(init {
let mut class = kernel::class::Builder::new(BLINKY_CLASS_NAME).build()?;
let _dev = kernel::device::Builder::new(&class, BLINKY_NAME)
.parent(&ThisModule::ref_().device())
.build()?;
unsafe {
MAJOR = chrdev::DynamicMajor::reserve()?
};
pr_info!("Blinky driver loaded (major: {})\n", unsafe { MAJOR });
Ok(())
});
kernel::task!(exit {
unsafe { unregister_chrdev_region(MAJOR, 1) };
pr_info!("Blinky driver unloaded\n");
Ok(())
});
Usage Example
-
Build & Load:
make -C /lib/modules/$(uname -r)/build M=$PWD modules
sudo insmod blinky.ko
sudo mknod /dev/blinky c $(cat /proc/devices | grep blinky | awk '{print $1}') 0
-
Test:
# Enable blinking at default period
echo 1 | sudo tee /dev/blinky
# Check status
cat /dev/blinky # Outputs "1" if busy
# Disable
echo 0 | sudo tee /dev/blinky
-
Extend: Add ioctl for period (use kernel::ioctl!), IRQ handling, or DMA.
This is a complete, self-contained kernel module. Adapt the base address and registers to your hardware. For user-space simulation or bare-metal, let me know! 🕵️