适用范围:Linux 4.19 / 5.x / 6.x 内核模块开发
头文件分类总览
include/linux/ 下有上千个头文件,但写驱动真正高频使用的约 60 个。按「功能域」划分,判断引入哪个头会快得多。

八大功能域详解
模块与入口
| 头文件 | 功能 |
|---|
linux/module.h | module_init / module_exit、MODULE_LICENSE/DESCRIPTION/AUTHOR、THIS_MODULE、try_module_get |
linux/init.h | __init / __exit / __initdata 段属性(init 段代码在加载后释放,节省内存) |
linux/export.h | EXPORT_SYMBOL / EXPORT_SYMBOL_GPL,把符号导出给其他模块使用 |
linux/moduleparam.h | module_param / module_param_array / MODULE_PARM_DESC,支持 insmod xxx.ko key=1 |
linux/version.h | LINUX_VERSION_CODE、KERNEL_VERSION(a,b,c),用于版本条件编译 |
字符设备与用户态交互
| 头文件 | 功能 |
|---|
linux/cdev.h | struct cdev、cdev_init / cdev_add / cdev_del |
linux/fs.h | 核心头文件:struct file、struct inode、file_operations、register_chrdev_region / alloc_chrdev_region、unregister_chrdev_region |
linux/uaccess.h | copy_to_user / copy_from_user、get_user / put_user、access_ok(老代码写 asm/uaccess.h) |
linux/ioctl.h | _IO / _IOR / _IOW / _IOWR / _IOC 命令码编码宏 |
linux/kdev_t.h | MKDEV / MAJOR / MINOR / new_encode_dev |
linux/poll.h | poll_wait、struct poll_table,实现 .poll 以支持 select/epoll |
linux/miscdevice.h | misc_register / misc_deregister,最省事的字符设备注册方式(自动分配次设备号) |
linux/seq_file.h | seq_operations、single_open,procfs/sysfs 输出大段文本时使用 |
linux/uio.h | struct iovec,实现 .read_iter / .write_iter |
linux/compat.h | .compat_ioctl,32 位用户态程序跑在 64 位内核上的兼容处理 |
并发与同步
| 头文件 | 功能 |
|---|
linux/mutex.h | mutex_init / mutex_lock / mutex_unlock,可睡眠的互斥锁(进程上下文) |
linux/spinlock.h | spin_lock_irqsave / spin_unlock_irqrestore,中断上下文必须用它 |
linux/semaphore.h | 老式信号量 down / up(新代码基本被 mutex 取代) |
linux/wait.h | wait_queue_head_t、wait_event_interruptible、wake_up_interruptible(阻塞式 read 靠它) |
linux/completion.h | wait_for_completion / complete,一次性的同步点 |
linux/atomic.h | atomic_t、atomic_inc / atomic_dec / atomic_read / atomic_set |
linux/refcount.h、linux/kref.h | 引用计数(防溢出 / 带自动释放回调) |
linux/rcupdate.h | RCU,读多写少场景 |
linux/seqlock.h、linux/rwlock.h | 顺序锁 / 读写锁 |
linux/local_lock.h | 5.8+ 引入的 per-CPU 锁 |
中断、时间与延后执行
| 头文件 | 功能 |
|---|
linux/interrupt.h | request_irq / request_threaded_irq / free_irq、irqreturn_t、IRQF_SHARED / IRQF_TRIGGER_*、disable_irq |
linux/irqreturn.h | IRQ_HANDLED / IRQ_NONE(新版常被 interrupt.h 带出,显式包含更稳) |
linux/timer.h | timer_setup / add_timer / mod_timer / del_timer_sync |
linux/hrtimer.h | 高精度定时器 hrtimer_init / hrtimer_start |
linux/workqueue.h | INIT_WORK / schedule_work / queue_work、alloc_workqueue、INIT_DELAYED_WORK |
linux/delay.h | udelay / mdelay / msleep / msleep_interruptible / fsleep |
linux/jiffies.h | HZ、jiffies、msecs_to_jiffies、time_after 等比较宏 |
linux/ktime.h | ktime_get / ktime_get_ns,高精度取时间 |
linux/timekeeping.h | ktime_get_real_ts64,取墙钟时间 |
设备模型与 sysfs
| 头文件 | 功能 |
|---|
linux/device.h | class_create / device_create / device_destroy、devm_* 资源托管、dev_err / dev_info |
linux/kobject.h | struct kobject / kset,sysfs 的底层对象与引用计数 |
linux/sysfs.h | DEVICE_ATTR_RW / DEVICE_ATTR_RO、attribute_group、sysfs_emit |
linux/platform_device.h | platform_driver / platform_device、module_platform_driver、probe/remove |
linux/mod_devicetable.h | struct of_device_id / platform_device_id 匹配表 |
linux/idr.h | ida_alloc / idr_alloc,动态分配次设备号 |
linux/device/class.h | 6.x 从 device.h 拆出的子头,直接包含可缩短编译时间 |
linux/device/driver.h | 同上,struct device_driver 相关声明 |
内存分配与地址映射
| 头文件 | 功能 |
|---|
linux/slab.h | kmalloc / kzalloc / kfree、kmem_cache_create、kstrdup |
linux/vmalloc.h | vmalloc / vfree,大块但物理不连续的内存 |
linux/gfp.h | GFP_KERNEL / GFP_ATOMIC / GFP_DMA / __GFP_ZERO 分配标志 |
linux/mm.h | struct page、virt_to_phys / phys_to_virt、get_zeroed_page |
linux/io.h | 寄存器操作:ioremap / ioremap_wc / iounmap、readl / writel / readb、memcpy_toio |
linux/ioport.h | request_mem_region / request_region / release_mem_region、struct resource |
linux/dma-mapping.h | dma_alloc_coherent、dma_map_single / dma_unmap_single |
硬件抽象与外设总线
| 头文件 | 功能 |
|---|
linux/of.h | 设备树:of_property_read_u32 / _string、of_get_child_by_name、for_each_available_child_of_node、of_match_device |
linux/of_address.h | of_iomap,直接从 DT 节点映射寄存器 |
linux/of_irq.h | irq_of_parse_and_map、of_irq_get |
linux/gpio/consumer.h | 新 GPIO API:gpiod_get / gpiod_set_value / gpiod_to_irq(推荐) |
linux/gpio.h | 旧的整数编号 GPIO API(legacy,新驱动不建议使用) |
linux/i2c.h | i2c_driver、i2c_transfer、i2c_smbus_read_byte_data 等 |
linux/spi/spi.h | spi_driver、spi_sync / spi_async、spi_write_then_read |
linux/pci.h | pci_driver、pci_enable_device、pci_iomap、pci_read_config_dword |
linux/usb.h | usb_driver、struct urb、usb_submit_urb |
linux/clk.h | 时钟:clk_get / clk_prepare_enable / clk_disable_unprepare |
linux/regulator/consumer.h | 电源管理芯片:regulator_get / regulator_enable |
linux/pinctrl/consumer.h | 引脚复用配置 |
linux/pm.h、linux/pm_runtime.h | dev_pm_ops、SET_SYSTEM_SLEEP_PM_OPS、pm_runtime_get_sync |
linux/input.h | 输入子系统:input_register_device、input_report_key |
支撑工具与调试
| 头文件 | 功能 |
|---|
linux/list.h | 极常用:list_head、list_add / list_del、list_for_each_entry、INIT_LIST_HEAD |
linux/kernel.h | container_of(从成员反推宿主结构体)、ARRAY_SIZE、min / max / clamp、roundup |
linux/types.h | u8/u16/u32/u64、dev_t、loff_t、gfp_t、__iomem、__user |
linux/compiler.h | __user / __iomem / __must_check、likely / unlikely、READ_ONCE / WRITE_ONCE |
linux/err.h | IS_ERR / PTR_ERR / ERR_PTR,让指针同时携带负数错误码 |
linux/errno.h | -EINVAL / -ENOMEM / -EFAULT / -ENODEV 等错误码 |
linux/string.h | memcpy / memset、kstrtoint / kstrtouint / kstrtobool、sysfs_streq |
linux/bitops.h、linux/bitmap.h | BIT() / GENMASK()、test_bit / set_bit |
linux/printk.h | pr_info / pr_err / pr_debug、pr_fmt 宏(5.18+ 从 kernel.h 拆出) |
linux/bug.h | BUG_ON / WARN_ON / WARN_ON_ONCE |
linux/proc_fs.h | proc_create / proc_remove(老的 create_proc_entry 已删除) |
linux/debugfs.h | debugfs_create_file / debugfs_create_dir,调试接口首选 |
linux/firmware.h | request_firmware / release_firmware,加载固件 |
linux/random.h | get_random_bytes、get_random_u32 |
常用 API 写法示例
本章代码基于 4.19+,标注版本分界的地方给出两套写法。
所有片段都可以直接粘进驱动,仅省去了 MODULE_LICENSE 等模板行。
最简模块骨架
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h>
static int __init demo_init(void) { pr_info("demo: loaded\n"); return 0; }
static void __exit demo_exit(void) { pr_info("demo: unloaded\n"); }
module_init(demo_init); module_exit(demo_exit);
MODULE_LICENSE("GPL"); MODULE_AUTHOR("you"); MODULE_DESCRIPTION("minimal demo module");
|
要点
pr_info() 系列自带 KERN_INFO 级别,比 printk(KERN_INFO ...) 短,且支持 pr_fmt 统一定前缀- 返回非 0 表示加载失败,
insmod 会直接报错退出 __init / __exit 让函数进入独立段,加载完成后内存被回收
字符设备:file_operations 全套回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
| #include <linux/fs.h> #include <linux/cdev.h> #include <linux/uaccess.h> #include <linux/poll.h> #include <linux/slab.h>
struct demo_dev { struct cdev cdev; struct mutex lock; wait_queue_head_t rq; char *buf; size_t size; bool data_ready; int value; };
static int demo_open(struct inode *inode, struct file *filp) { struct demo_dev *dev = container_of(inode->i_cdev, struct demo_dev, cdev);
filp->private_data = dev; return 0; }
static int demo_release(struct inode *inode, struct file *filp) { return 0; }
static ssize_t demo_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos) { struct demo_dev *dev = filp->private_data; int ret;
if (filp->f_flags & O_NONBLOCK) return dev->data_ready ? 0 : -EAGAIN;
ret = wait_event_interruptible(dev->rq, dev->data_ready); if (ret) return -ERESTARTSYS;
mutex_lock(&dev->lock); if (*ppos >= dev->size) { mutex_unlock(&dev->lock); return 0; } if (len > dev->size - *ppos) len = dev->size - *ppos;
if (copy_to_user(buf, dev->buf + *ppos, len)) { mutex_unlock(&dev->lock); return -EFAULT; } *ppos += len; mutex_unlock(&dev->lock);
return len; }
static ssize_t demo_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos) { struct demo_dev *dev = filp->private_data;
mutex_lock(&dev->lock); if (*ppos >= dev->size) { mutex_unlock(&dev->lock); return -ENOSPC; } if (len > dev->size - *ppos) len = dev->size - *ppos;
if (copy_from_user(dev->buf + *ppos, buf, len)) { mutex_unlock(&dev->lock); return -EFAULT; } *ppos += len; dev->data_ready = true; mutex_unlock(&dev->lock);
wake_up_interruptible(&dev->rq); return len; }
static loff_t demo_llseek(struct file *filp, loff_t off, int whence) { struct demo_dev *dev = filp->private_data; loff_t newpos;
switch (whence) { case SEEK_SET: newpos = off; break; case SEEK_CUR: newpos = filp->f_pos + off; break; case SEEK_END: newpos = dev->size + off; break; default: return -EINVAL; }
if (newpos < 0 || newpos > dev->size) return -EINVAL;
filp->f_pos = newpos; return newpos; }
static long demo_unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct demo_dev *dev = filp->private_data; void __user *argp = (void __user *)arg; int val;
if (_IOC_TYPE(cmd) != DEMO_IOC_MAGIC) return -ENOTTY; if (_IOC_NR(cmd) >= DEMO_IOC_MAXNR) return -ENOTTY;
switch (cmd) { case DEMO_GET_VAL: val = dev->value; if (copy_to_user(argp, &val, sizeof(val))) return -EFAULT; return 0;
case DEMO_SET_VAL: if (copy_from_user(&val, argp, sizeof(val))) return -EFAULT; dev->value = val; return 0;
default: return -ENOTTY; } }
#ifdef CONFIG_COMPAT
static long demo_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { return demo_unlocked_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)); } #endif
static __poll_t demo_poll(struct file *filp, struct poll_table_struct *wait) { struct demo_dev *dev = filp->private_data; __poll_t mask = 0;
poll_wait(filp, &dev->rq, wait);
if (dev->data_ready) mask |= EPOLLIN | EPOLLRDNORM; mask |= EPOLLOUT | EPOLLWRNORM;
return mask; }
static const struct file_operations demo_fops = { .owner = THIS_MODULE, .open = demo_open, .release = demo_release, .read = demo_read, .write = demo_write, .llseek = demo_llseek, .unlocked_ioctl = demo_unlocked_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = demo_compat_ioctl, #endif .poll = demo_poll, };
|
要点
copy_to_user / copy_from_user 必须检查返回值,失败返回 -EFAULT- 不要在持有 spinlock 时调用
copy_*_user(可能睡眠),用 mutex poll 只负责登记等待队列,实际阻塞由 VFS 完成.unlocked_ioctl 里的 unlocked 指内核不再帮你持大内核锁,并发保护要自己做
ioctl 命令码定义(内核与用户态共享)
命令码必须定义在一份头文件里,驱动和应用程序都包含它,否则参数会错位:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #ifndef _DEMO_IOCTL_H #define _DEMO_IOCTL_H
#ifdef __KERNEL__ #include <linux/types.h> #include <linux/ioctl.h> #else #include <linux/types.h> #include <sys/ioctl.h> #endif
struct demo_info { __u32 version; __u32 bufsize; };
#define DEMO_IOC_MAGIC 'D' #define DEMO_IOC_MAXNR 4
#define DEMO_GET_VAL _IOR(DEMO_IOC_MAGIC, 0, int) #define DEMO_SET_VAL _IOW(DEMO_IOC_MAGIC, 1, int) #define DEMO_GET_INFO _IOR(DEMO_IOC_MAGIC, 2, struct demo_info) #define DEMO_RESET _IO (DEMO_IOC_MAGIC, 3)
#endif
|
四个宏怎么选
| 宏 | 数据方向 | 用途 |
|---|
_IO(type, nr) | 无数据 | 纯命令,如 reset |
_IOR(type, nr, t) | 内核 → 用户 | 读设备状态 |
_IOW(type, nr, t) | 用户 → 内核 | 设置参数 |
_IOWR(type, nr, t) | 双向 | 传入并回填结果 |
用 __u32 而不是 u32:用户态没有 u32 这个类型,只有 __u32。
并发与同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/wait.h> #include <linux/completion.h> #include <linux/atomic.h>
static DEFINE_MUTEX(demo_mtx);
static int demo_do_something(void) { mutex_lock(&demo_mtx); mutex_unlock(&demo_mtx); return 0; }
if (mutex_lock_interruptible(&demo_mtx)) return -ERESTARTSYS;
static DEFINE_SPINLOCK(demo_lock); static unsigned long flags;
spin_lock_irqsave(&demo_lock, flags);
spin_unlock_irqrestore(&demo_lock, flags);
struct demo_dev { wait_queue_head_t rq; bool data_ready; };
init_waitqueue_head(&dev->rq);
if (wait_event_interruptible(dev->rq, dev->data_ready)) return -ERESTARTSYS;
if (wait_event_interruptible_timeout(dev->rq, dev->data_ready, msecs_to_jiffies(1000)) == 0) return -ETIMEDOUT;
wake_up_interruptible(&dev->rq);
static DECLARE_COMPLETION(demo_done);
if (wait_for_completion_timeout(&demo_done, msecs_to_jiffies(1000)) == 0) return -ETIMEDOUT;
complete(&demo_done); complete_all(&demo_done);
static atomic_t demo_count = ATOMIC_INIT(0);
atomic_inc(&demo_count); atomic_dec(&demo_count); if (atomic_dec_and_test(&demo_count)) { } int n = atomic_read(&demo_count);
|
选哪个锁
| 场景 | 用什么 | 能否睡眠 |
|---|
| 进程上下文,临界区长,可能要调用睡眠函数 | mutex | 可以 |
| 中断上下文 / 软中断 / 持有 spinlock 内 | spin_lock_irqsave | 不可以 |
| 只保护一个整数计数 | atomic_t | 可以 |
| 等待某个事件发生 | wait_queue / completion | 可以 |
| 读多写少的链表/哈希 | RCU | 读侧不可以,写侧可以 |
中断:request_irq 与 threaded irq
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <linux/interrupt.h>
static irqreturn_t demo_irq(int irq, void *dev_id) { struct demo_dev *dev = dev_id;
dev->data_ready = true; wake_up_interruptible(&dev->rq); schedule_work(&dev->work);
return IRQ_HANDLED; }
static int demo_probe(struct platform_device *pdev) { struct demo_dev *dev; int irq, ret;
irq = platform_get_irq(pdev, 0); if (irq < 0) return irq;
ret = devm_request_irq(&pdev->dev, irq, demo_irq, IRQF_TRIGGER_RISING, dev_name(&pdev->dev), dev); if (ret) return ret; return 0; }
ret = devm_request_irq(&pdev->dev, irq, demo_irq, IRQF_SHARED, "demo", dev);
|
中断线程化——上半部极短,耗时逻辑放到内核线程里,可以睡眠:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| static irqreturn_t demo_irq_hard(int irq, void *dev_id) { return IRQ_WAKE_THREAD; }
static irqreturn_t demo_irq_thread(int irq, void *dev_id) { struct demo_dev *dev = dev_id;
mutex_lock(&dev->lock); mutex_unlock(&dev->lock);
return IRQ_HANDLED; }
ret = devm_request_threaded_irq(&pdev->dev, irq, demo_irq_hard, demo_irq_thread, IRQF_TRIGGER_RISING | IRQF_ONESHOT, dev_name(&pdev->dev), dev);
|
IRQF_ONESHOT:线程处理完成前不重新打开该中断,避免中断风暴。
用 request_threaded_irq 且 handler 传 NULL 时,必须带 IRQF_ONESHOT。
常用 IRQF_* 标志
| 标志 | 含义 |
|---|
IRQF_TRIGGER_RISING / _FALLING / _HIGH / _LOW | 触发方式,设备树里配了就不用写 |
IRQF_SHARED | 共享中断线 |
IRQF_ONESHOT | 线程处理期间屏蔽该中断 |
IRQF_NO_SUSPEND | 系统休眠时该中断仍可唤醒 |
定时器与工作队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include <linux/timer.h> #include <linux/workqueue.h> #include <linux/jiffies.h>
struct demo_dev { struct timer_list timer; struct work_struct work; struct delayed_work dwork; };
static void demo_timer_fn(struct timer_list *t) { struct demo_dev *dev = from_timer(dev, t, timer);
schedule_work(&dev->work);
mod_timer(&dev->timer, jiffies + msecs_to_jiffies(1000)); }
static int demo_probe(struct platform_device *pdev) { struct demo_dev *dev;
timer_setup(&dev->timer, demo_timer_fn, 0); mod_timer(&dev->timer, jiffies + HZ); return 0; }
static int demo_remove(struct platform_device *pdev) { del_timer_sync(&dev->timer); return 0; }
static void demo_work_fn(struct work_struct *work) { struct demo_dev *dev = container_of(work, struct demo_dev, work);
msleep(10); mutex_lock(&dev->lock); mutex_unlock(&dev->lock); }
INIT_WORK(&dev->work, demo_work_fn); schedule_work(&dev->work);
static void demo_dwork_fn(struct work_struct *work) { struct demo_dev *dev = container_of(work, struct demo_dev, dwork.work); }
INIT_DELAYED_WORK(&dev->dwork, demo_dwork_fn); schedule_delayed_work(&dev->dwork, msecs_to_jiffies(100)); cancel_delayed_work_sync(&dev->dwork);
dev->wq = alloc_workqueue("demo_wq", WQ_UNBOUND | WQ_MEM_RECLAIM, 0); queue_work(dev->wq, &dev->work); destroy_workqueue(dev->wq);
msleep(10); udelay(5); fsleep(1000);
|
定时器 vs 工作队列 vs 线程化中断
| 机制 | 运行上下文 | 能否睡眠 | 适用 |
|---|
timer_list | 软中断 | 否 | 精确定时、周期任务 |
workqueue | 内核线程 | 是 | 中断下半部、耗时处理 |
threaded irq | 内核线程 | 是 | 中断处理本身就很重 |
hrtimer | 硬中断/软中断 | 否 | 微秒级精度 |
设备模型与 devm 资源托管
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <linux/device.h> #include <linux/platform_device.h>
static int demo_probe(struct platform_device *pdev) { struct demo_dev *dev; struct resource *res; int ret;
dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM;
dev->regs = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(dev->regs)) return PTR_ERR(dev->regs);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0); dev->regs = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(dev->regs)) return PTR_ERR(dev->regs);
ret = devm_request_irq(&pdev->dev, irq, demo_irq, 0, "demo", dev); if (ret) return ret;
platform_set_drvdata(pdev, dev);
my_class = class_create(THIS_MODULE, "demo"); my_class = class_create("demo");
if (IS_ERR(my_class)) return PTR_ERR(my_class);
device_create(my_class, NULL, devno, dev, "demo%d", 0); return 0; }
|
为什么优先 devm_*
| 写法 | 出错时 |
|---|
kmalloc + 手动 kfree | 每个错误分支都要 goto,漏一个就内存泄漏 |
devm_kzalloc | 内核记录在 &pdev->dev 上,probe 返回非 0 自动全部回收 |
devm_ 版本几乎覆盖了所有资源:devm_kzalloc、devm_ioremap、devm_request_irq、devm_clk_get、devm_gpiod_get、devm_regulator_get。
sysfs 属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <linux/sysfs.h> #include <linux/device.h>
static ssize_t value_show(struct device *dev, struct device_attribute *attr, char *buf) { struct demo_dev *d = dev_get_drvdata(dev);
return sysfs_emit(buf, "%d\n", d->value); }
static ssize_t value_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct demo_dev *d = dev_get_drvdata(dev); int val, ret;
ret = kstrtoint(buf, 10, &val); if (ret) return ret;
if (val < 0 || val > 100) return -EINVAL;
d->value = val; return count; }
static DEVICE_ATTR_RW(value); static DEVICE_ATTR_RO(version);
static struct attribute *demo_attrs[] = { &dev_attr_value.attr, &dev_attr_version.attr, NULL, }; ATTRIBUTE_GROUPS(demo);
|
挂载方式三选一:
1 2 3 4 5 6 7 8 9 10 11
| my_class = class_create("demo"); my_class->dev_groups = demo_groups; device_create(my_class, NULL, devno, dev, "demo%d", 0);
device_create_with_groups(my_class, NULL, devno, dev, demo_groups, "demo%d", 0);
device_create_file(dev, &dev_attr_value); device_remove_file(dev, &dev_attr_value);
|
对应的用户态访问:
1 2
| echo 42 > /sys/class/demo/demo0/value cat /sys/class/demo/demo0/value
|
规则:一个属性文件对应一个值,不要在 show 里做耗时操作——用户态 cat 时会被阻塞在 read 上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include <linux/platform_device.h> #include <linux/of.h> #include <linux/mod_devicetable.h> #include <linux/io.h>
static const struct of_device_id demo_of_match[] = { { .compatible = "vendor,demo-device" }, { .compatible = "vendor,demo-device-v2" }, { } }; MODULE_DEVICE_TABLE(of, demo_of_match);
static int demo_probe(struct platform_device *pdev) { struct demo_dev *dev; u32 freq, mode = 0; int ret, irq;
dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM;
ret = device_property_read_u32(&pdev->dev, "clock-frequency", &freq); if (ret) return ret;
of_property_read_u32(pdev->dev.of_node, "vendor,mode", &mode);
ret = device_property_read_string(&pdev->dev, "label", &dev->label);
dev->regs = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(dev->regs)) return PTR_ERR(dev->regs);
irq = platform_get_irq(pdev, 0); if (irq < 0) return irq;
ret = devm_request_irq(&pdev->dev, irq, demo_irq, 0, dev_name(&pdev->dev), dev); if (ret) return ret;
for_each_available_child_of_node(pdev->dev.of_node, child) { u32 addr; if (of_property_read_u32(child, "reg", &addr)) continue; }
platform_set_drvdata(pdev, dev); dev_info(&pdev->dev, "probed, freq=%u Hz, irq=%d\n", freq, irq); return 0; }
static int demo_remove(struct platform_device *pdev) { return 0; }
static struct platform_driver demo_driver = { .probe = demo_probe, .remove = demo_remove, .driver = { .name = "demo", .of_match_table = demo_of_match, .pm = &demo_pm_ops, }, }; module_platform_driver(demo_driver);
|
对应的设备树节点:
1 2 3 4 5 6 7 8 9
| demo: demo@10000000 { compatible = "vendor,demo-device"; reg = <0x10000000 0x1000>; interrupts = <0 45 4>; clock-frequency = <48000000>; vendor,mode = <2>; label = "demo-0"; status = "okay"; };
|
probe 被调用的条件:driver.of_match_table 里有某个 compatible 与 DT 节点的 compatible 相同,且节点 status = "okay"。
GPIO 描述符 API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <linux/gpio/consumer.h>
struct demo_dev { struct gpio_desc *reset_gpio; struct gpio_desc *irq_gpio; };
static int demo_probe(struct platform_device *pdev) { struct demo_dev *dev;
dev->reset_gpio = devm_gpiod_get(&pdev->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(dev->reset_gpio)) return PTR_ERR(dev->reset_gpio);
dev->irq_gpio = devm_gpiod_get_optional(&pdev->dev, "irq", GPIOD_IN);
gpiod_set_value(dev->reset_gpio, 1); gpiod_set_value_cansleep(dev->reset_gpio, 0);
int level = gpiod_get_value(dev->irq_gpio);
int irq = gpiod_to_irq(dev->irq_gpio);
return 0; }
|
| 老 API(≤ 3.12) | 新 API(3.13+) |
|---|
gpio_request(num, "name") | devm_gpiod_get(dev, "name", flags) |
gpio_direction_output(num, 1) | GPIOD_OUT_HIGH 标志 |
gpio_set_value(num, 1) | gpiod_set_value(desc, 1) |
gpio_get_value(num) | gpiod_get_value(desc) |
gpio_to_irq(num) | gpiod_to_irq(desc) |
gpio_free(num) | devm_ 自动释放 |
GPIOD_OUT_LOW/HIGH 里已经包含”申请 + 设方向”,不要再单独调 gpiod_direction_output,否则复位时序可能出错。
内存与寄存器访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/io.h> #include <linux/ioport.h>
struct demo_dev *dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; kfree(dev);
buf = kmalloc(size, GFP_ATOMIC);
buf = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
buf = vmalloc(4 * 1024 * 1024); if (!buf) return -ENOMEM; vfree(buf);
struct demo_dev { void __iomem *regs; };
dev->regs = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(dev->regs)) return PTR_ERR(dev->regs);
writel(0x1, dev->regs + REG_CTRL); u32 status = readl(dev->regs + REG_STATUS);
writew(0x1, dev->regs + REG_CFG); writeb(0x1, dev->regs + REG_EN);
writel(0x1, dev->regs + REG_CTRL); readl(dev->regs + REG_CTRL);
|
为什么不能 *(u32 *)addr = val
| 写法 | 问题 |
|---|
*(volatile u32 *)addr = val | 在 ARM64 / RISC-V 上可能触发对齐异常;编译器可能拆成多次访问 |
writel(val, addr) | 内部处理字节序、屏障、对齐,是唯一正确做法 |
链表典型用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <linux/list.h>
struct demo_item { int id; char name[32]; struct list_head node; };
static LIST_HEAD(demo_list); static DEFINE_MUTEX(list_mtx);
static int demo_add(int id, const char *name) { struct demo_item *item;
item = kzalloc(sizeof(*item), GFP_KERNEL); if (!item) return -ENOMEM;
item->id = id; strscpy(item->name, name, sizeof(item->name));
mutex_lock(&list_mtx); list_add_tail(&item->node, &demo_list); mutex_unlock(&list_mtx); return 0; }
static void demo_del(int id) { struct demo_item *p, *tmp;
mutex_lock(&list_mtx); list_for_each_entry_safe(p, tmp, &demo_list, node) { if (p->id == id) { list_del(&p->node); kfree(p); } } mutex_unlock(&list_mtx); }
static void demo_dump(void) { struct demo_item *p;
mutex_lock(&list_mtx); list_for_each_entry(p, &demo_list, node) pr_info("item: id=%d name=%s\n", p->id, p->name); mutex_unlock(&list_mtx); }
static void demo_from_node(struct list_head *pos) { struct demo_item *item = list_entry(pos, struct demo_item, node); }
|
list_for_each_entry vs list_for_each_entry_safe
| 宏 | 循环中能否 list_del |
|---|
list_for_each_entry | 不能,删除后 p->node.next 已失效 |
list_for_each_entry_safe | 可以,它提前保存了 next |
错误处理约定
内核不用异常,全部靠返回值。约定是硬性的,违反了会被 review 打回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| static int demo_do(void) { if (!dev) return -ENOMEM; if (copy_from_user(&val, argp, sizeof(val))) return -EFAULT; if (val > MAX_VAL) return -EINVAL; if (!(readl(regs) & READY)) return -EIO; if (!try_module_get(THIS_MODULE)) return -ENODEV; return 0; }
if (ret > 0) return -EIO;
static struct demo_dev *demo_alloc(void) { struct demo_dev *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) return ERR_PTR(-ENOMEM); return dev; }
dev = demo_alloc(); if (IS_ERR(dev)) return PTR_ERR(dev);
kfree(dev); dev = NULL;
dev_err(&pdev->dev, "failed to get irq %d: %d\n", irq, ret);
|
最常用的 12 个错误码
| 错误码 | 含义 | 什么时候用 |
|---|
-ENOMEM | 内存不足 | kmalloc 返回 NULL |
-EINVAL | 参数非法 | 用户传入越界值 |
-EFAULT | 用户态指针错误 | copy_from_user 失败 |
-ENODEV | 设备不存在 | 硬件未就绪 |
-EBUSY | 设备忙 | 已被占用 |
-EIO | I/O 错误 | 硬件读写失败 |
-ENOTTY | 不支持的 ioctl | default 分支 |
-EAGAIN | 暂时不可用 | 非阻塞模式无数据 |
-ERESTARTSYS | 被信号打断 | 等待队列被中断 |
-ETIMEDOUT | 超时 | 等待超时 |
-ENOSPC | 空间不足 | 缓冲区写满 |
-EPERM | 权限不足 | 需要 root 操作 |
三条必须知道的规则
规则一:asm/*.h 是架构相关头文件
asm/io.h、asm/page.h、asm/irq.h、asm/barrier.h 位于:
- x86:
arch/x86/include/asm/ - arm64:
arch/arm64/include/asm/ - 编译时通过
asm-generic 兜底
跨平台代码尽量用 linux/ 下的通用封装,例如用 linux/io.h 而不是 asm/io.h。
规则二:uapi 是对用户态可见的定义
ioctl 命令码、结构体定义通常放在 include/uapi/linux/xxx.h。
- 驱动侧:
#include <linux/xxx.h> 一般已经间接拿到 - 用户态程序:必须包含
/usr/include/linux/xxx.h
两边定义必须一致,否则 ioctl 传参会错位。最稳妥的做法是把命令码定义抽到独立头文件,驱动和用户态程序都包含它。
规则三:5.x 之后要求 “include what you use”
老内核靠 linux/kernel.h 一次性带出几乎所有东西,现在不行了——printk.h、sched.h、delay.h 都被拆开。
不要依赖隐式传递包含,用哪个 API 就显式 include 哪个头。编译时加 make W=1,会报 implicit declaration 之类的警告。
全功能字符设备 include 模板
一个「带 ioctl、阻塞 read、poll、sysfs 属性」的字符设备驱动,标准头文件组合如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/err.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/device.h> #include <linux/uaccess.h> #include <linux/ioctl.h> #include <linux/kdev_t.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/wait.h> #include <linux/poll.h> #include <linux/list.h> #include <linux/string.h> #include <linux/io.h> #include <linux/jiffies.h>
#define DEV_NAME "mychar"
|
对应的 Makefile:
1 2 3 4 5 6 7 8 9
| obj-m := mychar.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
|
常用 API → 头文件反查表
写代码时忘了函数在哪个头,直接查这里:
| API | 头文件 |
|---|
printk / pr_info | linux/printk.h |
container_of / ARRAY_SIZE | linux/kernel.h |
kmalloc / kfree | linux/slab.h |
vmalloc / vfree | linux/vmalloc.h |
ioremap / readl / writel | linux/io.h |
copy_to_user / copy_from_user | linux/uaccess.h |
list_add / list_for_each_entry | linux/list.h |
mutex_lock / mutex_unlock | linux/mutex.h |
spin_lock_irqsave | linux/spinlock.h |
wait_event_interruptible | linux/wait.h |
complete / wait_for_completion | linux/completion.h |
atomic_inc / atomic_read | linux/atomic.h |
request_irq / free_irq | linux/interrupt.h |
timer_setup / mod_timer | linux/timer.h |
schedule_work / queue_work | linux/workqueue.h |
msleep / udelay | linux/delay.h |
msecs_to_jiffies / HZ | linux/jiffies.h |
class_create / device_create | linux/device.h |
DEVICE_ATTR_RW / sysfs_emit | linux/sysfs.h |
platform_driver_register | linux/platform_device.h |
of_property_read_u32 | linux/of.h |
gpiod_get / gpiod_set_value | linux/gpio/consumer.h |
i2c_transfer | linux/i2c.h |
spi_sync | linux/spi/spi.h |
IS_ERR / PTR_ERR | linux/err.h |
proc_create | linux/proc_fs.h |
debugfs_create_file | linux/debugfs.h |
WARN_ON / BUG_ON | linux/bug.h |
request_firmware | linux/firmware.h |
get_random_bytes | linux/random.h |
快速定位 API 所在头文件
用 grep 查
1 2 3 4 5 6 7 8
| grep -rn "copy_to_user" include/linux/ | head
grep -rn "EXPORT_SYMBOL(kmalloc)" mm/
ls include/linux/ | grep -i dma
|
用编译器问
写代码时直接编译一次。找不到声明时编译器会报:
1
| warning: implicit declaration of function 'xxx'
|
这就是信号,去 include/linux/ 里 grep 一下函数名即可定位。
用 man 手册
内核源码文档里也有 man 页(man 9 xxx),但需要先安装:
1 2
| apt install linux-manual-$(uname -r) dnf install kernel-doc
|
附:常用宏速查
| 宏 | 用途 |
|---|
container_of(ptr, type, member) | 由成员地址反推宿主结构体地址 |
ARRAY_SIZE(arr) | 数组元素个数 |
offsetof(type, member) | 成员偏移 |
MIN / MAX / clamp(val, lo, hi) | 数值范围处理 |
BIT(n) / GENMASK(h, l) | 位掩码构造 |
likely(x) / unlikely(x) | 分支预测提示 |
READ_ONCE / WRITE_ONCE | 防编译器优化的一次性读写 |
IS_ERR(p) / PTR_ERR(p) | 指针里藏错误码 |
dev_err(dev, fmt, ...) | 带设备名前缀的日志 |
module_init / module_exit | 模块入口 / 出口 |
MODULE_LICENSE("GPL") | 声明许可,缺了会 taint 内核 |
EXPORT_SYMBOL / EXPORT_SYMBOL_GPL | 导出符号给其他模块 |