在内核空间获取文件描述符和细节而不使用open()函数

6

有人能提供代码来解决这个问题吗?

在内核级别,我们如何有效地获得与文件/dev/driver1相关的struct inode*

在用户空间中给定:

int fd;
fd = open("/dev/driver1", O_RDWR | O_SYNC);

在内核空间:

static long dev_ioctl(struct file *file, unsigned cmd, unsigned long arg)
struct dev_handle *handle;
handle = file->private_data;    

假设我们不走这条路,那么我们如何在内核本身中获取file->private_data的处理方式?

2
为什么需要文件描述符号?这不是你的文件系统代码需要知道的东西。 - tangrs
1
我知道,但是有个高层人士指定了要求。没有人能改变它。 - Moirisa Dikaiosýni
1
这些要求是什么?这听起来像是一个 XY 问题。 - tangrs
7
让那个高层领导被解雇。他不应该接近Linux内核。他的“要求”完全与Linux内核的工作方式相反。驱动程序接口是基于用户空间指针工作的,而无法使用内核指针;你需要构建或模拟用户空间进程才能调用这些函数。显然的意图,考虑到这种方法的明显愚蠢,是为了避免GPLv2的执行,对吧?但是这样行不通:内核-用户空间边界不是版权法律边界,它只是技术细节。让你的律师来解决吧,好吗? - Nominal Animal
5
以上话并不是说这是不可能的,只是愚蠢和错误的。如果你真的需要这样做,请记住你只需要一个用户空间上下文(包括栈、一点内存来保存数据等)。你可以使用类似于usermodehelper方法的代码来创建一个进程,在kernel/kmod.c中可以找到相关内容。 - Nominal Animal
显示剩余3条评论
2个回答

2

你正在寻找 filp_open 函数。该函数位于文件 include/linux/fs.h 中:

struct file *filp_open(const char *filename, int flags, umode_t mode);

这里有一个函数源代码和文档的链接:http://lxr.free-electrons.com/source/fs/open.c#L937 如果你确实需要FD,可以使用sys_open(在较新的内核中未导出):
long sys_open(const char __user *filename, int flags, int mode);

您可以在类似问题上找到非常好的答案: 如何在Linux内核模块中读写文件? 编辑(如何获取inode):
您可以从struct file中获取缓存的inode
struct file *file = ...;
struct inode *inode = file->inode;

如果您需要带锁定的话,这里有一个背景:Documentation/filesystems/path-lookup.txt 遍历的起点是current->fs->root。内核中已经有许多函数可以完成此工作,您可以在fs/namei.c源文件中找到它们。
有一个函数:kern_path:
int error;
struct inode *inode;
struct path path;

error = kern_path(pathname, LOOKUP_FOLLOW, &path);
if (error) ...;

inode = path.dentry->d_inode;

1
这似乎会产生一个 struct file* 或者一个 fd,而不是 OP 想要的 struct inode * - abligh
2
我们如何获取 struct inode* - Moirisa Dikaiosýni

1
你的代码位于dev_ioctl函数中吗? 如果是的话,那么
static long dev_ioctl(struct file *file, unsigned cmd, unsigned long arg)
    struct dev_handle *handle;
    struct inode *inode;
    handle = file->private_data;    
    inode = file->f_inode;

似乎没有关于锁定需求的合理文档,因此您应该尝试查找类似的代码并查看它如何在f_inode成员上运作。


1
不,_ioctl 不会被调用。 - Moirisa Dikaiosýni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接