The user wants a Linux character device driver for a virtual device. This is a classic systems programming task.
-
Understand the Goal: The objective is to write C code that compiles as a kernel module. This module should register a character device, allowing user-space programs to read from it, write to it, and possibly control it via ioctl.
-
Identify Key Components of a Char Driver:
- Module boilerplate:
module_init, module_exit, MODULE_LICENSE, etc.
- Device Number Allocation: Either static (
register_chrdev_region) or dynamic (alloc_chrdev_region). Dynamic is safer for examples.
- File Operations Structure (
file_operations): This links system calls (open, read, write, release) to the driver's specific functions.
- The Device Structure: A custom struct to hold device state (buffer, mutex/semaphore, cdev struct).
- Concurrency Control: Since it's a virtual device, multiple processes might try to access it. A mutex is standard.
- Implementation of
open and release: usually simple, maybe incrementing a usage counter (though strictly not necessary with modern kernels handling file structs, but good for demonstration).
- Implementation of
read: Copy data from kernel space (the virtual buffer) to user space (copy_to_user). Handle offsets and buffer limits.
- Implementation of
write: Copy data from user space (copy_from_user) to kernel space (the virtual buffer).
- Cdev Initialization:
cdev_init and cdev_add.
- Device Class/Node Creation (Optional but helpful): Using
class_create and device_create to automatically make the device appear in /dev (via udev). Without this, the user has to manually mknod, which is annoying.
-
Drafting the Code Structure:
-
Includes: <linux/module.h>, <linux/kernel.h>, <linux/fs.h>, <linux/uaccess.h>, <linux/cdev.h>, <linux/device.h>, <linux/slab.h>, <linux/mutex.h>.
-
Defines: Buffer size (e.g., 1024 bytes).
-
Device Data Structure:
struct virtual_dev {
char *data;
unsigned long size;
struct mutex lock;
struct cdev cdev;
};
-
File Operations:
my_open: Minimal logic.
my_release: Minimal logic.
my_read: Acquire lock -> copy_to_user -> update offset (actually, read uses f_pos passed by pointer, need to handle that) -> release lock. Correction: Standard read/write implementations often just handle the buffer. Let's make it a simple buffer that holds the last written data. If nothing is written, it returns zeros or default. Let's keep it simple: a circular buffer or just a fixed buffer where read consumes from start and write adds to end? Actually, the simplest "virtual device" usually acts like a memory buffer.
my_write: Acquire lock -> copy_from_user -> update size -> release lock.
-
Refining the Read/Write Logic:
- Read: User wants N bytes. We have M bytes in the buffer.
- If
*ppos >= buffer_size, return EOF (0).
- Copy
min(N, remaining) bytes to user.
- Update
*ppos.
- Write: User gives N bytes.
- If buffer is full, return error or partial write?
- Let's implement a "retention" model: Write overwrites the buffer. Read reads back what was written.
-
Adding "Auto-population" of /dev node:
- This is standard modern practice. Create a class "virtual_class", then a device "virtual_dev".
-
Writing the User Space Test Program:
- A driver is useless without a way to test it.
- Open
/dev/virtual_device.
- Write a string.
- Seek to start.
- Read string back.
- Print result.
-
Step-by-Step Implementation Plan:
-
Self-Correction/Edge Cases during drafting:
- Concurrency: Must use
mutex_lock and mutex_unlock in read/write to prevent race conditions if two processes write at once.
- Memory: Use
kmalloc in init and kfree in exit.
- Permissions: The device created via
device_create needs mode settings (e.g., 0666) so non-root users can read/write, or the test program needs to be run as sudo. I will set the default mode in the code or just assume sudo for the test.
-
Code Details:
-
Final Review of the Output:
- Does the code look like valid Kernel C? Yes (standard types like
ssize_t, loff_t, __user).
- Is the Makefile correct? Yes.
- Are the instructions clear? Yes.
Let's assemble the response. I will provide the complete C source code, a Makefile, a user-space test program, and step-by-step instructions.
Self-Correction on copy_to/from_user: I must remember to check the return value. If it returns non-zero, bytes weren't copied, and I should return -EFAULT.
Self-Correction on ioctl: The prompt just says "virtual device". Adding ioctl makes it complex. Read/Write is sufficient for a basic implementation. I will stick to Read/Write to keep the code understandable but mention where ioctl would go.
Self-Correction on Device Creation: class_create macro changed in recent kernels (requires THIS_MODULE argument in 6.4+). I will stick to the standard widely compatible syntax, usually class_create(THIS_MODULE, CLASS_NAME).
Let's generate the artifacts.
- Driver Name:
vchar_driver
- Class Name:
vchar_class
- Device Name:
vchar_dev
All set. Proceeding to generate output.
This is a complete implementation of a Linux kernel module that creates a virtual character device. The device acts like a memory buffer: you can write strings to it and read them back.
The implementation includes:
- The Kernel Module Source (
vchar.c): The core driver logic.
- The Makefile: To compile the driver.
- A User Space Test Program: To verify the driver works.
- Step-by-Step Instructions: How to build, load, and test the driver.
1. The Kernel Driver Code (vchar.c)
This driver creates a device /dev/vchar_dev. It uses a mutex to prevent race conditions if multiple processes try to read/write at the same time.
#include <linux/init.h> // Macros used to mark up functions e.g., __init __exit
#include <linux/module.h> // Core header for loading LKMs
#include <linux/device.h> // Header to support the Device Driver Model
#include <linux/kernel.h> // Contains types, macros and functions of the kernel
#include <linux/fs.h> // Header for the Linux file system support
#include <linux/uaccess.h> // Required for the copy to user function
#include <linux/slab.h> // Required for kmalloc/kfree
#include <linux/mutex.h> // Required for mutex locking
#define DEVICE_NAME "vchar_dev" // The device will appear at /dev/vchar_dev
#define CLASS_NAME "vchar" // The device class -- /sys/class/vchar
#define BUFFER_SIZE 1024 // Max size of the message buffer
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Assistant");
MODULE_DESCRIPTION("A simple Linux virtual character driver");
MODULE_VERSION("1.0");
// Function prototypes
static int dev_open(struct inode *, struct file *);
static int dev_release(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char *, size_t, loff_t *);
static ssize_t dev_write(struct file *, const char *, size_t, loff_t *);
// Global variables
static int majorNumber;
static char *message_ptr = NULL; // Pointer to the kernel buffer
static size_t message_len = 0; // Length of the message currently stored
static struct class* vcharClass = NULL;
static struct device* vcharDevice = NULL;
static DEFINE_MUTEX(vchar_mutex); // Mutex for thread safety
// The file operations structure connects our callbacks to the system calls
static struct file_operations fops =
{
.owner = THIS_MODULE,
.open = dev_open,
.read = dev_read,
.write = dev_write,
.release = dev_release,
};
// Initialization function
static int __init vchar_init(void){
printk(KERN_INFO "VChar: Initializing the VChar LKM\n");
// 1. Allocate Major Number dynamically
majorNumber = register_chrdev(0, DEVICE_NAME, &fops);
if (majorNumber < 0){
printk(KERN_ALERT "VChar: failed to register a major number\n");
return majorNumber;
}
printk(KERN_INFO "VChar: registered correctly with major number %d\n", majorNumber);
// 2. Create the struct class
vcharClass = class_create(CLASS_NAME);
if (IS_ERR(vcharClass)){
unregister_chrdev(majorNumber, DEVICE_NAME);
printk(KERN_ALERT "VChar: Failed to register device class\n");
return PTR_ERR(vcharClass);
}
printk(KERN_INFO "VChar: device class registered correctly\n");
// 3. Create the device driver
vcharDevice = device_create(vcharClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME);
if (IS_ERR(vcharDevice)){
class_destroy(vcharClass);
unregister_chrdev(majorNumber, DEVICE_NAME);
printk(KERN_ALERT "VChar: Failed to create the device\n");
return PTR_ERR(vcharDevice);
}
printk(KERN_INFO "VChar: device class created correctly\n");
// 4. Allocate the internal buffer
message_ptr = kmalloc(BUFFER_SIZE, GFP_KERNEL);
if (!message_ptr) {
device_destroy(vcharClass, MKDEV(majorNumber, 0));
class_destroy(vcharClass);
unregister_chrdev(majorNumber, DEVICE_NAME);
printk(KERN_ALERT "VChar: Failed to allocate memory\n");
return -ENOMEM;
}
memset(message_ptr, 0, BUFFER_SIZE);
mutex_init(&vchar_mutex);
return 0;
}
// Cleanup function
static void __exit vchar_exit(void){
mutex_destroy(&vchar_mutex);
kfree(message_ptr);
device_destroy(vcharClass, MKDEV(majorNumber, 0));
class_unregister(vcharClass);
class_destroy(vcharClass);
unregister_chrdev(majorNumber, DEVICE_NAME);
printk(KERN_INFO "VChar: Goodbye from the LKM!\n");
}
static int dev_open(struct inode *inodep, struct file *filep){
// We don't need exclusive access logic here usually,
// but we lock during read/write operations.
printk(KERN_INFO "VChar: Device opened\n");
return 0;
}
static int dev_release(struct inode *inodep, struct file *filep){
printk(KERN_INFO "VChar: Device successfully closed\n");
return 0;
}
// Called when user reads from the device
// Note: Standard behavior for char devices implies reading consumes the data
// or requires the user to handle lseek (f_pos).
// Here, we implement a simplistic "consume" read.
static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset){
mutex_lock(&vchar_mutex);
if (message_len == 0) {
mutex_unlock(&vchar_mutex);
return 0; // EOF
}
// Ensure we don't read more than available
size_t bytes_to_read = len;
if (bytes_to_read > message_len) {
bytes_to_read = message_len;
}
// copy_to_user returns number of bytes that FAILED to copy
int error_count = copy_to_user(buffer, message_ptr, bytes_to_read);
if (error_count==0){
printk(KERN_INFO "VChar: Sent %zu characters to the user\n", bytes_to_read);
// Shift the remaining buffer (simple queue behavior) or just clear it?
// Let's just clear it for simplicity of this example (Read destroys data)
memset(message_ptr, 0, BUFFER_SIZE);
message_len = 0;
mutex_unlock(&vchar_mutex);
return bytes_to_read;
} else {
printk(KERN_INFO "VChar: Failed to send %d characters to the user\n", error_count);
mutex_unlock(&vchar_mutex);
return -EFAULT;
}
}
// Called when user writes to the device
static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset){
mutex_lock(&vchar_mutex);
if (len > BUFFER_SIZE) {
printk(KERN_WARNING "VChar: Write size %zu exceeds buffer %d\n", len, BUFFER_SIZE);
mutex_unlock(&vchar_mutex);
return -ENOBUFS;
}
// copy_from_user returns number of bytes that FAILED to copy
int error_count = copy_from_user(message_ptr, buffer, len);
if (error_count==0){
message_len = len; // Update current data length
printk(KERN_INFO "VChar: Received %zu characters from the user\n", len);
mutex_unlock(&vchar_mutex);
return len;
} else {
printk(KERN_INFO "VChar: Failed to receive %d characters from the user\n", error_count);
mutex_unlock(&vchar_mutex);
return -EFAULT;
}
}
module_init(vchar_init);
module_exit(vchar_exit);
2. The Makefile
Save this as Makefile (case sensitive) in the same directory as vchar.c.
obj-m += vchar.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
3. Test Program (test.c)
This program writes a string to the driver and then reads it back.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define DEVICE_PATH "/dev/vchar_dev"
#define BUFFER_SIZE 1024
int main() {
int fd;
char write_buf[BUFFER_SIZE] = "Hello from user space!";
char read_buf[BUFFER_SIZE];
printf("Testing VChar Driver...\n");
// Open the device
fd = open(DEVICE_PATH, O_RDWR);
if (fd < 0) {
perror("Failed to open the device");
return -1;
}
// Write to device
printf("Writing to device: \"%s\"\n", write_buf);
if (write(fd, write_buf, strlen(write_buf)) < 0) {
perror("Failed to write to device");
close(fd);
return -1;
}
// Read from device
memset(read_buf, 0, BUFFER_SIZE);
if (read(fd, read_buf, BUFFER_SIZE) < 0) {
perror("Failed to read from device");
close(fd);
return -1;
}
printf("Read from device: \"%s\"\n", read_buf);
close(fd);
return 0;
}
4. Build and Run Instructions
Step 1: Install Prerequisites
You need the kernel headers and build tools for your current running kernel.
sudo apt-get update
sudo apt-get install build-essential linux-headers-$(uname -r)
Step 2: Compile the Module
Run the make command in the directory containing the C file and Makefile.
make
Output should include vchar.ko.
Step 3: Load the Module
Insert the module into the kernel.
sudo insmod vchar.ko
Check the kernel log to verify it loaded:
dmesg | tail
You should see "VChar: Initializing the VChar LKM" and the assigned Major number.
Step 4: Permissions
By default, the device /dev/vchar_dev is owned by root. To allow your user to read/write it without sudo (for the test program):
sudo chmod 666 /dev/vchar_dev
Step 5: Compile and Run the Test Program
gcc test.c -o test
./test
Expected Output:
Testing VChar Driver...
Writing to device: "Hello from user space!"
Read from device: "Hello from user space!"
Step 6: Unload the Module
When finished, remove the module.
sudo rmmod vchar
How it works
- Module Init (
vchar_init):
- Requests a Major Number from the OS.
- Registers a device class (
/sys/class/vchar).
- Creates the device node (
/dev/vchar_dev).
- Allocates kernel memory (kmalloc) for the buffer.
- File Operations (
fops):
- Links the standard system calls (
open, read, write, close) to our specific C functions.
- Write:
- Takes data from the user space (using
copy_from_user) and stores it in the kernel buffer.
- Uses a Mutex (
mutex_lock) to ensure that two processes don't write at the exact same time, which would corrupt the memory.
- Read:
- Takes data from the kernel buffer and sends it to user space (using
copy_to_user).
- Clears the buffer in this implementation (simulating a queue behavior where reading consumes the data).
- Module Exit (
vchar_exit):
- Cleans up memory, destroys the device node, and unregisters the major number.