Thursday, September 1, 2022

[SOLVED] How to get the minor number of a file in a Linux driver?

Issue

Is there a better solution to get the minor number?

Can I avoid checking kernel version?

static long unlocked_ioctl(struct file *f, unsigned int o, unsigned long d)
{
#if KERNEL_VERSION(3, 18, 0) > LINUX_VERSION_CODE
    struct inode* inode = f->f_dentry->d_inode;
#else
    struct inode* inode = f->f_path.dentry->d_inode;
#endif

    int minor = iminor(inode);
}

Solution

Yes, there's a better way: don't bother looking at the dentry when what you want is right there as a field of struct file.

struct file {
    union {
        struct llist_node   fu_llist;
        struct rcu_head     fu_rcuhead;
    } f_u;
    struct path     f_path;
    struct inode    *f_inode; // <-- here's your inode
    // ...
}

You can either access f->f_inode directly or use the file_inode() function, this way you can also avoid kernel version checks.

static long unlocked_ioctl(struct file *f, unsigned int o, unsigned long d)
{
    int minor = iminor(file_inode(f));
    // ...
}


Answered By - Marco Bonelli
Answer Checked By - Dawn Plyler (WPSolving Volunteer)