Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i know the minor on Linux module initialisation

Tags:

linux-kernel

I am writing a linux kernel module.

Here is what i've done in module's init function:

register_chrdev(300 /* major */, "mydev", &fops);

It works fine. But i need to know the minor number.

I have read we cannot set this minor number. It is the kernel which gives us this number. If so, how can i know it in module's init function ?

Thanks

like image 257
Bob5421 Avatar asked Sep 11 '25 21:09

Bob5421


1 Answers

register_chrdev calls __register_chrdev internally.

static inline int register_chrdev(unsigned int major, const char *name,
                  const struct file_operations *fops)
{
    return __register_chrdev(major, 0, 256, name, fops);
}

If you will see __register_chrdev function signature, it is

int __register_chrdev(unsigned int major, unsigned int baseminor,
              unsigned int count, const char *name,
              const struct file_operations *fops)

register_chrdev will pass your major number(300) and a base minor number 0 with a count of 256. So, it will reserve 0-255 minor number range for your device.

Also, in the definition of __register_chrdev, dev_t structure is created (contains major & minor number) for your device.

err = cdev_add(cdev, MKDEV(cd->major, baseminor), count);

MKDEV(cd->major, baseminor) creates it. So, the first device number(dev_t) will have 0 as its minor number. Besides, count(256) is the consecutive minor numbers that can be further used.

You can also dynamically get the major & minor number if you use alloc_chrdev_region. All you have to do is pass a dev_t struct to alloc_chrdev_region. It will dynamically allocate a major and minor number to your device. To get the major and minor number in your module, you can use

major = MAJOR(dev);
minor = MINOR(dev);
like image 128
bornfree Avatar answered Sep 13 '25 18:09

bornfree