Crafting educational message
I want to mention the importance of the license and include a message with pr_info in the response. Since this is for educational purposes, I need to clarify that it's not intended for production use. The user hasn’t asked for more details, so I’ll focus on delivering a clear and concise answer that includes these points. It's crucial to ensure they understand the context and limitations! Below is a minimal, modern Linux character device driver implementing a simple in‑memory “virtual” device, plus a Makefile and instructions to build and test it.
1. Driver source: vchar.c
This driver:
- Allocates a character device with a dynamic major number
- Creates
/dev/vchar using cdev + class_create/device_create
- Maintains an in‑kernel buffer (default 4 KB) as the device’s storage
- Implements
open, release, read, write, and llseek
- Uses a mutex to protect the buffer
// vchar.c - Simple virtual character device
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/uaccess.h> // copy_to_user, copy_from_user
#include <linux/slab.h> // kzalloc, kfree
#include <linux/mutex.h>
#define DEVICE_NAME "vchar"
static dev_t dev_num; // Device number (major+minor)
static struct cdev vchar_cdev;
static struct class *vchar_class; // Device class
static char *device_buffer;
static size_t buffer_size = 4096; // 4KB default
static size_t data_size; // Number of valid bytes in buffer
static DEFINE_MUTEX(buffer_mutex);
module_param(buffer_size, ulong, 0444);
MODULE_PARM_DESC(buffer_size, "Size of the virtual device buffer in bytes");
static int vchar_open(struct inode *inode, struct file *file)
{
// Nothing special; could track open count here
return 0;
}
static int vchar_release(struct inode *inode, struct file *file)
{
// Nothing special
return 0;
}
static ssize_t vchar_read(struct file *file, char __user *buf,
size_t len, loff_t *ppos)
{
ssize_t ret;
if (mutex_lock_interruptible(&buffer_mutex))
return -ERESTARTSYS;
if (*ppos >= data_size) {
// EOF
ret = 0;
goto out;
}
if (len > data_size - *ppos)
len = data_size - *ppos;
if (copy_to_user(buf, device_buffer + *ppos, len)) {
ret = -EFAULT;
goto out;
}
*ppos += len;
ret = len;
out:
mutex_unlock(&buffer_mutex);
return ret;
}
static ssize_t vchar_write(struct file *file, const char __user *buf,
size_t len, loff_t *ppos)
{
ssize_t ret;
if (mutex_lock_interruptible(&buffer_mutex))
return -ERESTARTSYS;
if (*ppos >= buffer_size) {
// No space left
ret = -ENOSPC;
goto out;
}
if (len > buffer_size - *ppos)
len = buffer_size - *ppos;
if (!len) {
ret = -ENOSPC;
goto out;
}
if (copy_from_user(device_buffer + *ppos, buf, len)) {
ret = -EFAULT;
goto out;
}
*ppos += len;
if (*ppos > data_size)
data_size = *ppos;
ret = len;
out:
mutex_unlock(&buffer_mutex);
return ret;
}
static loff_t vchar_llseek(struct file *file, loff_t off, int whence)
{
loff_t new_pos;
mutex_lock(&buffer_mutex);
switch (whence) {
case SEEK_SET:
new_pos = off;
break;
case SEEK_CUR:
new_pos = file->f_pos + off;
break;
case SEEK_END:
new_pos = data_size + off;
break;
default:
mutex_unlock(&buffer_mutex);
return -EINVAL;
}
if (new_pos < 0 || new_pos > buffer_size) {
mutex_unlock(&buffer_mutex);
return -EINVAL;
}
file->f_pos = new_pos;
mutex_unlock(&buffer_mutex);
return new_pos;
}
static const struct file_operations vchar_fops = {
.owner = THIS_MODULE,
.open = vchar_open,
.release = vchar_release,
.read = vchar_read,
.write = vchar_write,
.llseek = vchar_llseek,
};
static int __init vchar_init(void)
{
int ret;
// Allocate device number
ret = alloc_chrdev_region(&dev_num, 0, 1, DEVICE_NAME);
if (ret < 0) {
pr_err("vchar: failed to allocate char dev region\n");
return ret;
}
// Initialize and add cdev
cdev_init(&vchar_cdev, &vchar_fops);
vchar_cdev.owner = THIS_MODULE;
ret = cdev_add(&vchar_cdev, dev_num, 1);
if (ret < 0) {
pr_err("vchar: cdev_add failed\n");
goto err_unregister;
}
// Create class
vchar_class = class_create(THIS_MODULE, "vchar_class");
if (IS_ERR(vchar_class)) {
pr_err("vchar: class_create failed\n");
ret = PTR_ERR(vchar_class);
goto err_cdev_del;
}
// Create device node /dev/vchar (udev should handle it)
if (IS_ERR(device_create(vchar_class, NULL, dev_num, NULL, DEVICE_NAME))) {
pr_err("vchar: device_create failed\n");
ret = -EINVAL;
goto err_class_destroy;
}
// Allocate device buffer
device_buffer = kzalloc(buffer_size, GFP_KERNEL);
if (!device_buffer) {
pr_err("vchar: failed to allocate buffer\n");
ret = -ENOMEM;
goto err_device_destroy;
}
data_size = 0;
pr_info("vchar: loaded (major=%d, minor=%d, buffer_size=%zu)\n",
MAJOR(dev_num), MINOR(dev_num), buffer_size);
return 0;
err_device_destroy:
device_destroy(vchar_class, dev_num);
err_class_destroy:
class_destroy(vchar_class);
err_cdev_del:
cdev_del(&vchar_cdev);
err_unregister:
unregister_chrdev_region(dev_num, 1);
return ret;
}
static void __exit vchar_exit(void)
{
kfree(device_buffer);
device_destroy(vchar_class, dev_num);
class_destroy(vchar_class);
cdev_del(&vchar_cdev);
unregister_chrdev_region(dev_num, 1);
pr_info("vchar: unloaded\n");
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Simple virtual character device");
MODULE_VERSION("1.0");
module_init(vchar_init);
module_exit(vchar_exit);
2. Makefile
# Makefile for vchar kernel module
obj-m := vchar.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
3. Build and load
From the directory containing vchar.c and Makefile:
make
sudo insmod vchar.ko
dmesg | tail
You should see a message like:
vchar: loaded (major=246, minor=0, buffer_size=4096)
If udev is running (typical desktop/server), /dev/vchar should appear automatically:
ls -l /dev/vchar
If not, create it manually using the major/minor numbers from dmesg:
sudo mknod /dev/vchar c <major> 0
sudo chmod 666 /dev/vchar
4. Test the virtual device
Write to the device:
echo "hello virtual device" > /dev/vchar
Read back:
cat /dev/vchar
# Output: hello virtual device
Because of the file position, a second cat /dev/vchar will show nothing unless data is written again or the file offset is reset (e.g., with dd or a program using lseek).
Example with dd and seeking:
echo -n "abcdef" > /dev/vchar
dd if=/dev/vchar bs=1 count=3 2>/dev/null # reads "abc"
dd if=/dev/vchar bs=1 skip=3 count=3 2>/dev/null # reads "def"
Unload when done:
sudo rmmod vchar
dmesg | tail
If you want, I can extend this example to support multiple minor devices, ioctl commands, or asynchronous notification (poll/select).