Reputation: 25
Is there a way to get a struct file
pointer for a device file inside linux kernel? I am writing a kernel module. I want to access file *
for a scsi device (e.g. /dev/sg1). Can I access it from the kernel without having to open the device in user space?
Alternatively, if I open the said device in user space and pass the fd to my kernel module, is there a way to convert the fd to a file *
?
Upvotes: 1
Views: 3238
Reputation:
By calling anon_inode_getfile() you can create an anonymous file instance that has the file operations of your choice bound to it. In some situations you can use it to do what you want to do by using the device file operations.
dev_filp = anon_inode_getfile("[/dev/foo]", &foo_fops, NULL, O_RDWR);
if (IS_ERR(dev_filp))
return PTR_ERR(dev_filp);
Upvotes: 0
Reputation: 66288
Can I access it from the kernel without having to open the device in user space?
No, struct file
object is created by the kernel only for opened file.
if I open the said device in user space and pass the fd to my kernel module, is there a way to convert the fd to 'file *'?
Just use fdget
function:
// 'fd' variable contains file descriptor, passed from the user.
struct fd f; // NOTE: 'struct fd' has nothing common with 'fd' variable.
f = fdget(fd);
if(!f.file) { /*process error*/ }
... // Use f.file object
fdput(f);
This is common scenario for use by both the kernel core and drivers(modules). struct fd
is defined in include/linux/file.h
.
Upvotes: 2