目前,我正在学习 Linux 设备驱动程序。并且对打开设备文件的工作方式感到困惑?
到目前为止我得到了什么......考虑一个打开普通文件的简单代码......
#incldue<stdio.h>
int main() {
FILE fp;
char buffer[20];
fp = fopen(/home/yoggi/foo.txt, "r");
fread(buffer, 5, 1, fp);
}
在上面的程序中,c-library 函数 fopen() 是系统调用open()的包装函数,它在 VFS 层函数中调用sys_open() 或 file_open() 。由于 linux 支持许多文件系统,虚拟文件系统然后将控制权转移到实际文件系统处理程序以打开该文件。
1) How does virtual file system(VFS) get to know on which file system the
underline file resides?
2) How does it then calls the file_open or open function of that particular
filesystem to open file.
如果设备驱动程序发生类似的事情。假设一个简单的设备驱动程序。
#include <linux/module.h>
// othher includes...
static dev_t first; // Global variable for the first device number
static struct cdev c_dev; // Global variable for the character device structure
static struct class *cl; // Global variable for the device class
static int my_open(struct inode *i, struct file *f)
{
printk(KERN_INFO "Driver: open()\n");
return 0;
}
static ssize_t my_read(struct file *f, char __user *buf, size_t len, loff_t *off)
{
printk(KERN_INFO "Driver: read()\n");
return 0;
}
struct file_operations pugs_fops =
{
.owner = THIS_MODULE,
.open = my_open,
.read = my_read,
};
static int __init ofcd_init(void) /* Constructor */
{
printk(KERN_INFO "Namaskar: ofcd registered");
if (alloc_chrdev_region(&first, 0, 1, "Shweta") < 0)
{
return -1;
}
if ((cl = class_create(THIS_MODULE, "chardrv")) == NULL)
{
unregister_chrdev_region(first, 1);
return -1;
}
if (device_create(cl, NULL, first, NULL, "mynull") == NULL)
{
class_destroy(cl);
unregister_chrdev_region(first, 1);
return -1;
}
cdev_init(&c_dev, &pugs_fops);
if (cdev_add(&c_dev, first, 1) == -1)
{
device_destroy(cl, first);
class_destroy(cl);
unregister_chrdev_region(first, 1);
return -1;
}
return 0;
}
static void __exit ofcd_exit(void) /* Destructor */
{
cdev_del(&c_dev);
device_destroy(cl, first);
class_destroy(cl);
unregister_chrdev_region(first, 1);
printk(KERN_INFO "Alvida: ofcd unregistered");
}
module_init(ofcd_init);
module_exit(ofcd_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Anil Kumar Pugalia <email_at_sarika-pugs_dot_com>");
MODULE_DESCRIPTION("Our First Character Driver");
首先,我们为设备分配主要次要编号。注册设备文件的范围并将设备文件操作链接到设备驱动程序函数。
我没有得到的一些术语是..
1) What does actually cdev_add() do? in terms of registering a device to the
kernel.
2) Registering a device to the kernel means?
3) How does a open(/dev/mynull, O_RONLY); called on a device file actually calls
the open function of driver which is mapped while initializing the device
by calling routine cdev_init(&c_dev, &pugs_fops); ?