“Linux 驱动如何兼容”这个问题可以从多个层面来理解。下面我按常见场景给你一个系统性的说明,你可以对照自己的实际需求。
include/linux/ 中标注为稳定)EXPORT_SYMBOL_GPL 之外的内部函数)#include <linux/version.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 10, 0)
// 新接口
#else
// 旧接口
#endif
https://backports.wiki.kernel.org
id_table 匹配设备static const struct pci_device_id my_pci_ids[] = {
{ PCI_DEVICE(0x1234, 0x5678) },
{ PCI_DEVICE(0x1234, 0x5679) },
{ }
};
MODULE_DEVICE_TABLE(pci, my_pci_ids);
static const struct usb_device_id my_usb_ids[] = {
{ USB_DEVICE(0x1234, 0x5678) },
{ }
};
MODULE_DEVICE_TABLE(usb, my_usb_ids);
device tree(ARM /嵌入式)mydev: mydev@0 {
compatible = "vendor,mydev";
reg = <0x0 0x1000>;
};
驱动中:
static const struct of_device_id my_of_ids[] = {
{ .compatible = "vendor,mydev" },
{ }
};
u32 / u64cpu_to_le32() / le32_to_cpu()_IOWR 宏定义命令#ifdef CONFIG_COMPAT
static long my_compat_ioctl(struct file *f, unsigned cmd, unsigned long arg)
#endif
Kbuildobj-m += mydriver.o
make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
make KDIR=/path/to/kernel
✅ 优先 upstream(合入主线内核)
✅ 一个驱动支持多设备,而不是多份代码
✅ 尽量不修改内核,只写可加载模块(.ko)
❌ 避免拷贝整个内核代码改接口
你可以告诉我:
我可以直接给你示例驱动代码或补丁。