A)2.4之前的驱动:
register_chrdev()
对设备结点的创建可以手动:
mknod /dev/test 250 0
也可以用devfs程序自动创建:
devfs_register()
注销:
devfs_unregister()
unregister_chrdev()
B)后来进化到2.6的某些版本,引入了kobject,有了cdev结构,注册函数变了,devfs函数也做了改动:
注册用register_chrdev_region()先申请字符设备号
然后cdev_init()
cdev_add() 或者cdev_alloc()
devfs自动创建函数有所变动:
devfs_register() ->devfs_mk_cdev()
devfs_unregister()>devfs_remove()
注销:
devfs_remove()
cdev_del()
unregister_chrdev_region()
示例:
// 第1步:注册/分配主次设备号
mydev = MKDEV(MYMAJOR, 0);
retval = register_chrdev_region(mydev, MYCNT, MYNAME);
// 第2步:注册字符设备驱动
cdev_init(&test_cdev, &test_fops);
retval = cdev_add(&test_cdev, mydev, MYCNT);
B)后来进化又引入sysfs,sysfs通过class_create和device_create在设备树中创建相应的设备;以及udev代替devfs,由udev来检测class的变动接受device_create()发来的消息,自动创建设备结点:
alloc_chrdev_region或者register_chrdev_region()
cdev_init(&hello_cdev,&hello_fops);
//注册
cdev_add(&hello_cdev,devid,2);
//创建类
hello_class=class_create(THIS_MODULE,”hello”);
//自动创建设备
hello_class_dev[i]=class_device_create(hello_class,NULL,MKDEV(major,i),NULL,”
示例:
static int hello_open(struct inode *inode, struct file *filp)
{
printk(“hello_open\n”);
return 0;
}
//构建file_operations结构体
static struct file_operations hello_fops={
.owner=THIS_MODULE,
.open = hello_open,
};
static int major;
static struct cdev hello_cdev;
static struct class* hello_class;
static struct class_device* hello_class_dev[3];
static int hello_init(void)
{
dev_t devid;
if(major==0)
{
alloc_chrdev_region(&devid,0,2,”hello”);//主设备号为major,次设备号为0,1则对应该file_operations
major=MAJOR(devid);
}
else
{
devid=MKDEV(major,0);
register_chrdev_region(devid,2,”hello”);
}
cdev_init(&hello_cdev,&hello_fops);
//注册
cdev_add(&hello_cdev,devid,2);
//创建类
hello_class=class_create(THIS_MODULE,”hello”);
int i;
for(i=0;i<3;i++)
{ //自动创建设备
hello_class_dev[i]=class_device_create(hello_class,NULL,MKDEV(major,i),NULL,”hello%d”,i);
}
return 0;
}
static void hello_exit(void)
{
cdev_del(&hello_cdev);
unregister_chrdev_region(MKDEV(major,0),2);
int i;
for(i=0;i<3;i++)
{
class_device_destroy(hello_class, MKDEV(major, i));
}
class_destroy(hello_class);
}