avasin
avasin

Reputation: 9736

Dynamic major number allocation - how to get it in ioctl application?

I want to follow best-practices and use dynamic major number allocation for my driver when registering kernel module.

I can output this number with printk and see it with dmesg. But is it possible to retrieve such number using ioctl application, that is used to talk with driver?

Or perhaphs it is possible to write some shell script, that will perform insmod, mknod & also retrieve given major number?

Upvotes: 2

Views: 2436

Answers (3)

Algoman
Algoman

Reputation: 2027

You need to use the function alloc_chrdev_region.

See https://www.kernel.org/doc/htmldocs/kernel-api/API-alloc-chrdev-region.html

Upvotes: 0

Ian Abbott
Ian Abbott

Reputation: 17503

I'm assuming you have a static /dev directory, otherwise you could just let the device files be created dynamically with the correct major and minor device numbers and be done with it.

If you have sysfs mounted on /sys, you could add a read-only module parameter to indicate the major device number registered to your devices. (If you load your driver as a module, you could also use the same module parameter to set a specific major device number when loading the module, defaulting to a dynamically allocated major device number. To add such a module parameter to your driver, you can do something like this:

#define MYDRIVER_MAJOR_DEF 0  /* Default major is dynamic */

unsigned int major = MYDRIVER_MAJOR_DEF;

module_param(major, uint, 0444);
MODULE_PARM_DESC(major,
                 "Major device number; set to 0 to assign dynamically;"
                 " (default="__MODULE_STRING(MYDRIVER_MAJOR_DEF)")");

Then use the value of major when registering your devices with register_chrdev or whatever. After registering your devices, if major was 0, set it to the actual, dynamically allocated major device number so that you can read it back via the sysfs module parameter file.

From user-space, the module parameter file will be something like /sys/module/mydriver/parameters/major and will contain the major device number as a string of decimal characters. You can read that in a script and use it with the mknod program to create the device files.

It's easier to use a dynamic /dev though!

Upvotes: 0

Jeyaram
Jeyaram

Reputation: 9494

Usually by reading /proc/devices we can get dynamically allocated Major number.

awk '$2=="misc" {print $1}' /proc/devices

Here "misc" is the driver name.

There is no harm in writing a extra function which returns major number.

Upvotes: 1

Related Questions