这是Linux device driver edition 3的第一个设备驱动,是字符设备驱动.想必大家也知道了在Linux中有3大类设备驱动:字符设备驱动,块设备驱动和网络设备驱动.
这一章我看了很多遍,但最终还没有完成,究其原因:
第一,自己没有毅力
第二,觉得有点难,算了,不去coding了
第三,总有其它的诱惑让我放弃coding
最后,也就是现在,又开始去想把这个驱动自己一行行的实现。之前一小时,还在看投资理财的书,这里插点题外话,技术固然是让人尊敬的,但是懂点金融也没有坏处。
好了,没打算开始写,先把整个章节review一下,看看这个章节包含了哪些内容。
1. major and minor number
这里面要注意几个点
(1) char devices are accessed through names in the filesystem,为什么说这个呢,你要让这个设备运作,你的application自然是要有控制这个设备的接口,这个接口就是这个文件
(2) 通过几个宏获得major & minor number
MAJOR(dev_t dev);
MINOR(dev_t dev);
还可以用major & minor number组合为dev_t
MKDEV(int major, int minor);
2. Allocating and Freeig device numbers
这一节里第一句话很重要:One of the first things your driver will need to do when setting up a char device is to obtain one or more device numbers to work with.
直接介绍函数:
int register_chrdev_region(dev_t first, unsigned int count,char *name);
这个函数需要你实现知道设备的major & minor number,对于各个参数的解释,参见LLD3原书。书里有详细解释和相关的优缺点
下面这个函数是重点,是书里极力推荐的
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor,
unsigned int count, char *name);
动态分配major & minor number的函数
最后是释放函数:
void unregister_chrdev_region(dev_t first, unsigned int count);
再看下红色的字体部分.
3. Some Important Data Structures
(1) File operations
(2) The file Structure
(3) The inode Structure
这几个解释在原书里解释的很清楚,在我眼里我是这么想的。application想要控制这个设备吧,首先得获得这个设备,怎么获得呢?
openfile,这个openfile自然是打开这个设备文件,然后获得了返回值,返回值就是这个file structure,然后又有很多程序也想获得,那么就
有很多这个The file structure,但是这个设备文件只有一个,对不对,这个设备文件就是有inode,你既然获得这个设备,总想干点什么吧.
是吧,那么File operations就起作用了。
4. Char Device Registeion
The kernel uses structures of type struct cdev to represent char devices internally.
分配:
struct cdev * my_cdev = cdev_alloc();
初始化:
void cdev_init(struct cdev *cdev, struct file_operations *fops);
添加到系统:
int cdev_add(struct cdev *dev, dev_t num, unsigned int count);
移除:
void cdev_del(struct cdev *dev);
4. Device Registration in scull
struct scull_dev {
struct scull_qset *data; /* Pointer to first quantum set */
int quantum; /* the current quantum size */
int qset; /* the current array size */
unsigned long size; /* amount of data stored here */
unsigned int access_key; /* used by sculluid and scullpriv */
struct semaphore sem; /* mutual exclusion semaphore */
struct cdev cdev; /* Char device structure */
};