1.标准字符设备驱动
a.注册设备号 如
if(key_major) /*静态注册*/
err = register_chrdev_region(devno, 1, DEVICE_NAME);
else
{ /*动态注册*/
err = alloc_chrdev_region(&devno, 0, 1, DEVICE_NAME);
key_major = MAJOR(devno);
}
b.内存申请给cdev(当cdev定义为指针时)然后调用以下函数进行设备初始化并添加该设备
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
c.如需在/dev下自动创建设备,需调用如下函数
struct class *key_class = class_create(THIS_MODULE, name);
struct device *device_create(struct class *class, struct device *parent,dev_t devt, void *drvdata, const char *fmt, ...)
*classs 就是class_create返回的key_class;parent如没有就设为NULL;devt设备号;drvdata 如无就为NULL,后面的就是设备名称。也可调用mknod 手动创建设备节点。
自此设备已经成功添加,一下的工作就时完成file_operations中相应函数就好了。
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
int (*readdir) (struct file *, void *, filldir_t);
unsigned int (*poll) (struct file *, struct poll_table_struct *);
int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, struct dentry *, int datasync);
int (*aio_fsync) (struct kiocb *, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
int (*check_flags)(int);
int (*flock) (struct file *, int, struct file_lock *);
ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
int (*setlease)(struct file *, long, struct file_lock **);
};
早期解决的办法
不使用cdev接口
int register_chrdev(unsigned int major, const char *name,struct file_operations * fops);
注册主设备号
result = register_chrdev(sculll_major,"scull",&scull_fops);
if () {
printk();
return result;
}
if (scull_major == 0) scull_major =result;