I'm starting to flesh out the core functionality. My focus is on creating a virtual character device driver. The primary need is to manage data transfer via kernel buffers. I'll need to define read and write operations.
Outlining Implementation Strategy
I'm presently building the file_operations structure. The plan involves creating handlers for open, read, write, and release. I'm focusing on ensuring data integrity between user space and the kernel buffer. The most recent task involves defining the structure of the character device.
Elaborating the Components
I'm now structuring the necessary file operations. I'm focusing on defining read and write functions using copy_to_user and copy_from_user for data transfer. I'll include checks for valid offsets and buffer boundaries. I'm also preparing the device number registration and cdev initialization.
Preparing Device Registration
I'm now integrating the class_create and device_create functions. I'll add the necessary includes for automatic device node creation. This allows the user to interact with /dev/virt_char_dev directly. I'll be mindful of the initialization and cleanup sequences, especially when dealing with the class and device structures.
Structuring the Response
I'm now writing the outline for the document, including the core driver code (simple_char_driver.c), a Makefile for building the module, and a user-space testing application. I'll include detailed instructions on how to compile, load, test, and unload the driver. Finally, I will review the code, especially focusing on read and write functions, ensuring *ppos is managed correctly.
Mapping Functions and Structures
I'm now implementing the open, read, write, and release functions, alongside the device registration. I'm focusing on user-space interaction. I plan to use copy_to_user and copy_from_user for data transfer. I'll need to update *ppos correctly to track read and write positions.
This is a complete implementation of a basic Linux character device driver for a virtual device. This driver allocates a kernel buffer, allows user-space programs to write to it, and allows them to read that data back.
It includes:
The Driver Source Code (virt_dev.c)
The Makefile
A User-space Test Program
Instructions to compile and run
1. The Driver Source Code (virt_dev.c)
c
2. Makefile
Create a file named Makefile (case sensitive) in the same directory.
Create a file named test_app.c to verify the driver works.
c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#define DEVICE "/dev/virt_cdev"
int main() {
int fd;
char write_buf[] = "Hello from User space!";
char read_buf[1024];
printf("Opening device %s...\n", DEVICE);
fd = open(DEVICE, O_RDWR);
if (fd < 0) {
perror("Failed to open the device");
return -1;
}
printf("Writing message to device: '%s'\n", write_buf);
int ret = write(fd, write_buf, strlen(write_buf));
if (ret < 0) {
perror("Failed to write to the device");
close(fd);
return -1;
}
// Reset file pointer to the beginning to read back
lseek(fd, 0, SEEK_SET);
printf("Reading from device...\n");
ret = read(fd, read_buf, sizeof(read_buf));
if (ret < 0) {
perror("Failed to read from the device");
close(fd);
return -1;
}
printf("Received Data: '%s'\n", read_buf);
close(fd);
return 0;
}
4. Instructions to Run
To perform these steps, you need to have Linux kernel headers installed (usually package linux-headers-$(uname -r)).
Step 1: Compile the Driver and Test App
bash
make
gcc test_app.c -o test_app
Step 2: Load the Kernel Module
bash
sudo insmod virt_dev.ko
Note: Because we used class_create and device_create in the code, /dev/virt_cdev is created automatically with the correct permissions. verify using ls -l /dev/virt_cdev.
Step 3: Change Permissions (Optional but likely needed)
Depending on your udev rules, the device might belong to root only.
bash
sudo chmod 666 /dev/virt_cdev
Step 4: Run the Test
bash
./test_app
Expected Output:
code
Opening device /dev/virt_cdev...
Writing message to device: 'Hello from User space!'
Reading from device...
Received Data: 'Hello from User space!'
Step 5: View Kernel Logs
You can see the debug print statements we added in the C code:
bash
sudo dmesg | tail -n 10
Step 6: Unload the Module
bash
sudo rmmod virt_dev
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h> // For copy_to_user, copy_from_user
#include <linux/device.h> // For class_create, device_create
#define DEVICE_NAME "virt_cdev"
#define CLASS_NAME "virt_class"
#define BUFFER_SIZE 1024
MODULE_LICENSE("GPL");
MODULE_AUTHOR("User");
MODULE_DESCRIPTION("A simple virtual Linux character device driver");
MODULE_VERSION("1.0");
// Global variables
static int major_number;
static char device_buffer[BUFFER_SIZE];
static struct class* virt_class = NULL;
static struct device* virt_device = NULL;
// The prototype functions for the character driver
static int dev_open(struct inode *, struct file *);
static int dev_release(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char __user *, size_t, loff_t *);
static ssize_t dev_write(struct file *, const char __user *, size_t, loff_t *);
// File operations structure
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = dev_open,
.read = dev_read,
.write = dev_write,
.release = dev_release,
};
// 1. Initialization Function
static int __init virt_dev_init(void) {
printk(KERN_INFO "VirtDev: Initializing the VirtDev LKM\n");
// Allocate a major number dynamically
major_number = register_chrdev(0, DEVICE_NAME, &fops);
if (major_number < 0) {
printk(KERN_ALERT "VirtDev: Failed to register a major number\n");
return major_number;
}
printk(KERN_INFO "VirtDev: Registered correctly with major number %d\n", major_number);
// Register the device class
virt_class = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(virt_class)) {
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "VirtDev: Failed to register device class\n");
return PTR_ERR(virt_class);
}
// Register the device driver
virt_device = device_create(virt_class, NULL, MKDEV(major_number, 0), NULL, DEVICE_NAME);
if (IS_ERR(virt_device)) {
class_destroy(virt_class);
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "VirtDev: Failed to create the device\n");
return PTR_ERR(virt_device);
}
memset(device_buffer, 0, BUFFER_SIZE); // Clear buffer
printk(KERN_INFO "VirtDev: Device class created correctly\n");
return 0;
}
// 2. Cleanup Function
static void __exit virt_dev_exit(void) {
device_destroy(virt_class, MKDEV(major_number, 0)); // Remove the device
class_unregister(virt_class); // Unregister the class
class_destroy(virt_class); // Remove the class
unregister_chrdev(major_number, DEVICE_NAME); // Unregister the major number
printk(KERN_INFO "VirtDev: Goodbye from the LKM!\n");
}
// 3. Open
static int dev_open(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "VirtDev: Device has been opened\n");
return 0;
}
// 4. Read
static ssize_t dev_read(struct file *filep, char __user *buffer, size_t len, loff_t *offset) {
int bytes_to_read;
int uncopied_bytes;
// Check if we are at the end of the buffer
if (*offset >= BUFFER_SIZE) {
return 0;
}
// Determine how much data to read (don't overflow buffer)
bytes_to_read = len;
if (*offset + len > BUFFER_SIZE) {
bytes_to_read = BUFFER_SIZE - *offset;
}
// Copy data from kernel buffer to user buffer
uncopied_bytes = copy_to_user(buffer, device_buffer + *offset, bytes_to_read);
if (uncopied_bytes) {
printk(KERN_ALERT "VirtDev: Failed to send %d bytes to the user\n", uncopied_bytes);
return -EFAULT;
}
// Update the file position
*offset += bytes_to_read;
printk(KERN_INFO "VirtDev: Sent %d bytes to the user\n", bytes_to_read);
return bytes_to_read;
}
// 5. Write
static ssize_t dev_write(struct file *filep, const char __user *buffer, size_t len, loff_t *offset) {
int bytes_to_write;
int uncopied_bytes;
// Check space
if (*offset >= BUFFER_SIZE) {
return -ENOSPC; // No Space Left
}
bytes_to_write = len;
if (*offset + len > BUFFER_SIZE) {
bytes_to_write = BUFFER_SIZE - *offset;
}
// Copy data from user buffer to kernel buffer
uncopied_bytes = copy_from_user(device_buffer + *offset, buffer, bytes_to_write);
if (uncopied_bytes) {
printk(KERN_ALERT "VirtDev: Failed to receive %d bytes from the user\n", uncopied_bytes);
return -EFAULT;
}
*offset += bytes_to_write;
printk(KERN_INFO "VirtDev: Received %zu bytes from the user\n", len);
return bytes_to_write;
}
// 6. Release
static int dev_release(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "VirtDev: Device successfully closed\n");
return 0;
}
module_init(virt_dev_init);
module_exit(virt_dev_exit);