Linux 裝置驅動是核心與硬體間的介面,將硬體操作抽象為檔案操作(open/read/write/ioctl)。本文以最簡單的字符設備驅動為例,完整展示從資料結構、核心函數實作、模組載入/卸載到裝置檔案建立的全流程(基於核心 2.0.x/2.2.x 經典架構,現代核心 API 有所不同,原理相通)。
驅動程式核心在於填充 struct file_operations,每個函數指標對應一個系統呼叫:
struct file_operations {
int (*open) (struct inode *, struct file *);
int (*release)(struct inode *, struct file *);
int (*read) (struct inode *, struct file *, char *, int);
int (*write) (struct inode *, struct file *, const char *, int);
int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
// ... 其他如 llseek, mmap, poll 等
};
#define __NO_VERSION__
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <asm/uaccess.h> // copy_to/from_user
static int major = 0;
static char msg[256] = "Hello from kernel!";
static int msg_len = 0;
// open: 增加模組使用計數
static int dev_open(struct inode *inode, struct file *filp) {
MOD_INC_USE_COUNT;
return 0;
}
// release: 減少使用計數
static int dev_release(struct inode *inode, struct file *filp) {
MOD_DEC_USE_COUNT;
return 0;
}
// read: 將核心資料複製到用戶空間
static ssize_t dev_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) {
if (*f_pos >= msg_len) return 0;
if (count > msg_len - *f_pos) count = msg_len - *f_pos;
if (copy_to_user(buf, msg + *f_pos, count)) return -EFAULT;
*f_pos += count;
return count;
}
// write: 從用戶空間接收資料
static ssize_t dev_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos) {
if (count > 255) count = 255;
if (copy_from_user(msg, buf, count)) return -EFAULT;
msg_len = count;
return count;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = dev_open,
.release = dev_release,
.read = dev_read,
.write = dev_write,
};
// 模組初始化:註冊字符設備
int init_module(void) {
major = register_chrdev(0, "simple_char", &fops);
if (major < 0) {
printk(KERN_ERR "simple_char: cannot register\n");
return major;
}
printk(KERN_INFO "simple_char: registered with major %d\n", major);
return 0;
}
// 模組清理:註銷字符設備
void cleanup_module(void) {
unregister_chrdev(major, "simple_char");
printk(KERN_INFO "simple_char: unregistered\n");
}
MODULE_LICENSE("GPL");
obj-m += simple_char.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
make insmod simple_char.ko dmesg | tail # 確認主設備號 mknod /dev/simple_char c 254 0 # 主設備號依實際輸出調整 echo "test" > /dev/simple_char cat /dev/simple_char rmmod simple_char
copy_to_user/copy_from_user 或 put_user/get_user,不可直接解參考用戶指標。spinlock、mutex、wait_queue 處理併發存取。module_param 允許載入時指定參數。struct file_operations 增加 .owner、loff_t 位移型別、ssize_t 回傳型別、MOD_INC/DEC_USE_COUNT 改用 try_module_get/module_put、裝置模型 (kobject/sysfs) 整合等。