VinK VinK - 1 month ago 11
Linux Question

linux kernel: how to get 'struct file' pointer inside kernel for a device file?

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 *
?

Answer Source

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.