Linux内核驱动头文件速查手册

适用范围:Linux 4.19 / 5.x / 6.x 内核模块开发

头文件分类总览

include/linux/ 下有上千个头文件,但写驱动真正高频使用的约 60 个。按「功能域」划分,判断引入哪个头会快得多。


八大功能域详解

模块与入口

头文件功能
linux/module.hmodule_init / module_exit、MODULE_LICENSE/DESCRIPTION/AUTHOR、THIS_MODULE、try_module_get
linux/init.h__init / __exit / __initdata 段属性(init 段代码在加载后释放,节省内存)
linux/export.hEXPORT_SYMBOL / EXPORT_SYMBOL_GPL,把符号导出给其他模块使用
linux/moduleparam.hmodule_param / module_param_array / MODULE_PARM_DESC,支持 insmod xxx.ko key=1
linux/version.hLINUX_VERSION_CODE、KERNEL_VERSION(a,b,c),用于版本条件编译

字符设备与用户态交互

头文件功能
linux/cdev.hstruct 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.hcopy_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.hMKDEV / MAJOR / MINOR / new_encode_dev
linux/poll.hpoll_wait、struct poll_table,实现 .poll 以支持 select/epoll
linux/miscdevice.hmisc_register / misc_deregister,最省事的字符设备注册方式(自动分配次设备号)
linux/seq_file.hseq_operations、single_open,procfs/sysfs 输出大段文本时使用
linux/uio.hstruct iovec,实现 .read_iter / .write_iter
linux/compat.h.compat_ioctl,32 位用户态程序跑在 64 位内核上的兼容处理

并发与同步

头文件功能
linux/mutex.hmutex_init / mutex_lock / mutex_unlock,可睡眠的互斥锁(进程上下文)
linux/spinlock.hspin_lock_irqsave / spin_unlock_irqrestore,中断上下文必须用它
linux/semaphore.h老式信号量 down / up(新代码基本被 mutex 取代)
linux/wait.hwait_queue_head_t、wait_event_interruptible、wake_up_interruptible(阻塞式 read 靠它)
linux/completion.hwait_for_completion / complete,一次性的同步点
linux/atomic.hatomic_t、atomic_inc / atomic_dec / atomic_read / atomic_set
linux/refcount.h、linux/kref.h引用计数(防溢出 / 带自动释放回调)
linux/rcupdate.hRCU,读多写少场景
linux/seqlock.h、linux/rwlock.h顺序锁 / 读写锁
linux/local_lock.h5.8+ 引入的 per-CPU 锁

中断、时间与延后执行

头文件功能
linux/interrupt.hrequest_irq / request_threaded_irq / free_irq、irqreturn_t、IRQF_SHARED / IRQF_TRIGGER_*、disable_irq
linux/irqreturn.hIRQ_HANDLED / IRQ_NONE(新版常被 interrupt.h 带出,显式包含更稳)
linux/timer.htimer_setup / add_timer / mod_timer / del_timer_sync
linux/hrtimer.h高精度定时器 hrtimer_init / hrtimer_start
linux/workqueue.hINIT_WORK / schedule_work / queue_work、alloc_workqueue、INIT_DELAYED_WORK
linux/delay.hudelay / mdelay / msleep / msleep_interruptible / fsleep
linux/jiffies.hHZ、jiffies、msecs_to_jiffies、time_after 等比较宏
linux/ktime.hktime_get / ktime_get_ns,高精度取时间
linux/timekeeping.hktime_get_real_ts64,取墙钟时间

设备模型与 sysfs

头文件功能
linux/device.hclass_create / device_create / device_destroy、devm_* 资源托管、dev_err / dev_info
linux/kobject.hstruct kobject / kset,sysfs 的底层对象与引用计数
linux/sysfs.hDEVICE_ATTR_RW / DEVICE_ATTR_RO、attribute_group、sysfs_emit
linux/platform_device.hplatform_driver / platform_device、module_platform_driver、probe/remove
linux/mod_devicetable.hstruct of_device_id / platform_device_id 匹配表
linux/idr.hida_alloc / idr_alloc,动态分配次设备号
linux/device/class.h6.x 从 device.h 拆出的子头,直接包含可缩短编译时间
linux/device/driver.h同上,struct device_driver 相关声明

内存分配与地址映射

头文件功能
linux/slab.hkmalloc / kzalloc / kfree、kmem_cache_create、kstrdup
linux/vmalloc.hvmalloc / vfree,大块但物理不连续的内存
linux/gfp.hGFP_KERNEL / GFP_ATOMIC / GFP_DMA / __GFP_ZERO 分配标志
linux/mm.hstruct page、virt_to_phys / phys_to_virt、get_zeroed_page
linux/io.h寄存器操作:ioremap / ioremap_wc / iounmap、readl / writel / readb、memcpy_toio
linux/ioport.hrequest_mem_region / request_region / release_mem_region、struct resource
linux/dma-mapping.hdma_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.hof_iomap,直接从 DT 节点映射寄存器
linux/of_irq.hirq_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.hi2c_driver、i2c_transfer、i2c_smbus_read_byte_data 等
linux/spi/spi.hspi_driver、spi_sync / spi_async、spi_write_then_read
linux/pci.hpci_driver、pci_enable_device、pci_iomap、pci_read_config_dword
linux/usb.husb_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.hdev_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.hcontainer_of(从成员反推宿主结构体)、ARRAY_SIZE、min / max / clamp、roundup
linux/types.hu8/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.hIS_ERR / PTR_ERR / ERR_PTR,让指针同时携带负数错误码
linux/errno.h-EINVAL / -ENOMEM / -EFAULT / -ENODEV 等错误码
linux/string.hmemcpy / memset、kstrtoint / kstrtouint / kstrtobool、sysfs_streq
linux/bitops.h、linux/bitmap.hBIT() / GENMASK()、test_bit / set_bit
linux/printk.hpr_info / pr_err / pr_debug、pr_fmt 宏(5.18+ 从 kernel.h 拆出)
linux/bug.hBUG_ON / WARN_ON / WARN_ON_ONCE
linux/proc_fs.hproc_create / proc_remove(老的 create_proc_entry 已删除)
linux/debugfs.hdebugfs_create_file / debugfs_create_dir,调试接口首选
linux/firmware.hrequest_firmware / release_firmware,加载固件
linux/random.hget_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> /* printk 在这里;5.18+ 也可用 <linux/printk.h> */

static int __init demo_init(void)
{
pr_info("demo: loaded\n"); /* 不要用 printk("<1>...") 这种老格式 */
return 0;
}

static void __exit demo_exit(void)
{
pr_info("demo: unloaded\n");
}

module_init(demo_init);
module_exit(demo_exit);

MODULE_LICENSE("GPL"); /* 缺了会导致内核 tainted,部分符号不可用 */
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;
};

/* open:从 inode 反查我们自己定义的设备结构 */
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;

/* 没有数据就睡,别用 while 空转 */
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); /* 唤醒阻塞在 read 上的进程 */
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;
}

/* 关键:函数名是 unlocked_ioctl,签名不含 struct inode,返回 long */
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;

/* 先校验命令码,防止拿到别的设备的 ioctl */
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; /* 约定:不认识的命令返回 -ENOTTY */
}
}

#ifdef CONFIG_COMPAT
/* 32 位程序跑在 64 位内核上时走这里 */
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

/* 4.16+ 返回值类型是 __poll_t;更早的内核用 unsigned int */
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
/* demo_ioctl.h —— 驱动和用户态程序共用这一份 */
#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

/* 结构体必须定义在 _IOR/_IOW 之前 */
struct demo_info {
__u32 version;
__u32 bufsize;
};

#define DEMO_IOC_MAGIC 'D' /* 8 位魔法数,避免与其他驱动冲突 */
#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 /* _DEMO_IOCTL_H */

四个宏怎么选

宏数据方向用途
_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);
/* 这里可以调用 kmalloc(GFP_KERNEL)、copy_to_user 等可能睡眠的函数 */
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); /* 保存并关中断 */
/* 绝对不能睡眠:不能 mutex_lock、不能 copy_to_user、不能 kmalloc(GFP_KERNEL) */
spin_unlock_irqrestore(&demo_lock, flags);

/* ---- 等待队列:阻塞式 read 的核心 ---- */
struct demo_dev {
wait_queue_head_t rq;
bool data_ready;
};

init_waitqueue_head(&dev->rq); /* probe 里初始化 */

/* 等待方(进程上下文) */
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; /* 不是自己的中断就返回 IRQ_NONE */
}

/* 注册:4.19+ 推荐用 devm_ 版本,remove 时自动释放 */
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), /* /proc/interrupts 里显示的名字 */
dev); /* 传给 handler 的 dev_id */
if (ret)
return ret;
return 0;
}

/* 共享中断:多个设备共用一根线,必须传非 NULL 的 dev_id 并能判断是否自己的中断 */
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 */
/* 这里可以 i2c_transfer、msleep、copy_to_user */
mutex_unlock(&dev->lock);

return IRQ_HANDLED;
}

ret = devm_request_threaded_irq(&pdev->dev, irq,
demo_irq_hard, /* 可为 NULL,直接进线程 */
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;
};

/* ---- 定时器(4.15+):回调参数是 struct timer_list * ---- */
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); /* 替代 init_timer */
mod_timer(&dev->timer, jiffies + HZ); /* 1 秒后触发,并启动 */
return 0;
}

static int demo_remove(struct platform_device *pdev)
{
del_timer_sync(&dev->timer); /* 卸载时必须调用,否则 UAF */
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); /* 挂到系统默认队列 */

/* ---- 延迟工作:比"定时器 + 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); /* 0 = 默认并发度 */
queue_work(dev->wq, &dev->work);
destroy_workqueue(dev->wq);

/* ---- 简单延时 ---- */
msleep(10); /* 进程上下文,可被信号打断用 msleep_interruptible */
udelay(5); /* 忙等,仅用于 <10us 的硬件时序 */
fsleep(1000); /* 自动在 usleep/msleep 之间选择 */

定时器 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;

/* 全部用 devm_:probe 失败或 remove 时内核自动释放,不用写 goto 清理链 */
dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;

/* 5.1+ 一行搞定 platform_get_resource + devm_ioremap_resource */
dev->regs = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(dev->regs))
return PTR_ERR(dev->regs);

/* 4.19 ~ 5.0 的老写法,仍能编译 */
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); /* 之后用 platform_get_drvdata 取回 */

/* 4.19 ~ 6.3:class_create 需要 owner 参数 */
my_class = class_create(THIS_MODULE, "demo");
/* 6.4+:owner 参数被移除 */
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>

/* show:把值格式化进 buf,返回写入的字节数 */
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); /* 5.8+,自带长度保护 */
/* 4.19 ~ 5.7 用:return sprintf(buf, "%d\n", d->value); */
}

/* store:buf 里是用户写进来的字符串,count 是长度(通常含 \n) */
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); /* 不要用 simple_strtoul,没有错误检查 */
if (ret)
return ret;

if (val < 0 || val > 100)
return -EINVAL;

d->value = val;
return count; /* 成功必须返回 count,否则用户态会重试 */
}

static DEVICE_ATTR_RW(value); /* 4.18+,等价于 DEVICE_ATTR(value, 0644, ...) */
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
/* 方式 1:挂到 class 上(6.x 推荐,所有同类设备共享) */
my_class = class_create("demo");
my_class->dev_groups = demo_groups;
device_create(my_class, NULL, devno, dev, "demo%d", 0);

/* 方式 2:创建设备时直接带属性 */
device_create_with_groups(my_class, NULL, devno, dev, demo_groups, "demo%d", 0);

/* 方式 3:手动逐个创建(老代码常见,容易漏删) */
device_create_file(dev, &dev_attr_value);
device_remove_file(dev, &dev_attr_value);

对应的用户态访问:

1
2
echo 42 > /sys/class/demo/demo0/value    # 触发 value_store
cat /sys/class/demo/demo0/value # 触发 value_show

规则:一个属性文件对应一个值,不要在 show 里做耗时操作——用户态 cat 时会被阻塞在 read 上。


platform 驱动与设备树

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>

/* 匹配表:compatible 必须和 .dts 里的字符串完全一致 */
static const struct of_device_id demo_of_match[] = {
{ .compatible = "vendor,demo-device" },
{ .compatible = "vendor,demo-device-v2" },
{ /* sentinel,必须以空元素结尾 */ }
};
MODULE_DEVICE_TABLE(of, demo_of_match); /* 让 depmod 能识别,热插拔必需 */

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;

/* 从设备树读属性:兼容性最好的写法,也支持 ACPI */
ret = device_property_read_u32(&pdev->dev, "clock-frequency", &freq);
if (ret)
return ret;

/* 只在 OF 平台上用,语义相同 */
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)
{
/* devm_ 资源自动回收,这里只处理非 devm 的资源 */
return 0;
}

static struct platform_driver demo_driver = {
.probe = demo_probe,
.remove = demo_remove, /* 6.11+ 返回类型改为 void */
.driver = {
.name = "demo",
.of_match_table = demo_of_match,
.pm = &demo_pm_ops,
},
};
module_platform_driver(demo_driver); /* 替代 module_init/module_exit 手写注册 */

对应的设备树节点:

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;

/* 按名字取:设备树里写 reset-gpios = <&gpio1 5 GPIO_ACTIVE_LOW>; */
dev->reset_gpio = devm_gpiod_get(&pdev->dev, "reset", GPIOD_OUT_HIGH);
if (IS_ERR(dev->reset_gpio))
return PTR_ERR(dev->reset_gpio);

/* 可选 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); /* GPIO 挂在 I2C 扩展芯片上时用 */

/* 读输入 */
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>

/* ---- 小块内存:kmalloc,物理连续 ---- */
struct demo_dev *dev = kzalloc(sizeof(*dev), GFP_KERNEL); /* 零初始化 */
if (!dev)
return -ENOMEM;
kfree(dev);

/* 中断上下文只能用 GFP_ATOMIC(不能睡眠等待) */
buf = kmalloc(size, GFP_ATOMIC);

/* 指定上限,防止超大分配 */
buf = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);

/* ---- 大块内存:vmalloc,物理不连续,只在需要大缓冲区时用 ---- */
buf = vmalloc(4 * 1024 * 1024);
if (!buf)
return -ENOMEM;
vfree(buf);

/* ---- 寄存器:ioremap 后必须用 readl/writel,不能直接解引用 ---- */
struct demo_dev {
void __iomem *regs; /* 必须标 __iomem,编译器会检查误用 */
};

dev->regs = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(dev->regs))
return PTR_ERR(dev->regs);

writel(0x1, dev->regs + REG_CTRL); /* 32 位寄存器 */
u32 status = readl(dev->regs + REG_STATUS);

writew(0x1, dev->regs + REG_CFG); /* 16 位 */
writeb(0x1, dev->regs + REG_EN); /* 8 位 */

/* 读写后加屏障,保证顺序(部分设备需要) */
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;
}

/* ---- 遍历并删除:必须用 _safe 版本 ---- */
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);
}

/* ---- 只遍历不删除:用非 safe 版本,效率更高 ---- */
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);
}

/* ---- 由 node 反查宿主结构体 ---- */
static void demo_from_node(struct list_head *pos)
{
struct demo_item *item = list_entry(pos, struct demo_item, node);
/* 等价于 container_of(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
/* 1. 返回 int 的函数:0 表示成功,负值表示错误(-errno) */
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;
}

/* 2. 绝不返回正数当错误码 */
if (ret > 0)
return -EIO; /* 而不是 return ret; */

/* 3. 返回指针的函数:错误用 ERR_PTR 编码进指针 */
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); /* 取出原始错误码 */

/* 4. 释放后置空,防止 double free */
kfree(dev);
dev = NULL;

/* 5. 错误日志:用 dev_err,自动带设备名前缀 */
dev_err(&pdev->dev, "failed to get irq %d: %d\n", irq, ret);

最常用的 12 个错误码

错误码含义什么时候用
-ENOMEM内存不足kmalloc 返回 NULL
-EINVAL参数非法用户传入越界值
-EFAULT用户态指针错误copy_from_user 失败
-ENODEV设备不存在硬件未就绪
-EBUSY设备忙已被占用
-EIOI/O 错误硬件读写失败
-ENOTTY不支持的 ioctldefault 分支
-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_infolinux/printk.h
container_of / ARRAY_SIZElinux/kernel.h
kmalloc / kfreelinux/slab.h
vmalloc / vfreelinux/vmalloc.h
ioremap / readl / writellinux/io.h
copy_to_user / copy_from_userlinux/uaccess.h
list_add / list_for_each_entrylinux/list.h
mutex_lock / mutex_unlocklinux/mutex.h
spin_lock_irqsavelinux/spinlock.h
wait_event_interruptiblelinux/wait.h
complete / wait_for_completionlinux/completion.h
atomic_inc / atomic_readlinux/atomic.h
request_irq / free_irqlinux/interrupt.h
timer_setup / mod_timerlinux/timer.h
schedule_work / queue_worklinux/workqueue.h
msleep / udelaylinux/delay.h
msecs_to_jiffies / HZlinux/jiffies.h
class_create / device_createlinux/device.h
DEVICE_ATTR_RW / sysfs_emitlinux/sysfs.h
platform_driver_registerlinux/platform_device.h
of_property_read_u32linux/of.h
gpiod_get / gpiod_set_valuelinux/gpio/consumer.h
i2c_transferlinux/i2c.h
spi_synclinux/spi/spi.h
IS_ERR / PTR_ERRlinux/err.h
proc_createlinux/proc_fs.h
debugfs_create_filelinux/debugfs.h
WARN_ON / BUG_ONlinux/bug.h
request_firmwarelinux/firmware.h
get_random_byteslinux/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)   # Debian/Ubuntu
dnf install kernel-doc # Fedora/RHEL

附:常用宏速查

宏用途
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导出符号给其他模块