Allocate a dynamic major number with alloc_chrdev_region
Let the kernel pick a free major number with alloc_chrdev_region on Linux 6.12, then read it back with MAJOR and find it in /proc/devices.
Hard-coding a major number works until another driver uses it. alloc_chrdev_region asks the kernel for a free device number and returns it through the first argument.
static dev_t demo_devt;
static struct cdev demo_cdev;
static int __init demo_init(void)
{
int ret = alloc_chrdev_region(&demo_devt, 0, 1, "demo");
if (ret)
return ret;
cdev_init(&demo_cdev, &demo_fops);
demo_cdev.owner = THIS_MODULE;
ret = cdev_add(&demo_cdev, demo_devt, 1);
if (ret)
unregister_chrdev_region(demo_devt, 1);
pr_info("demo: major %d\n", MAJOR(demo_devt));
return ret;
}demo: major 236Your number will differ. The arguments are the output, the first minor, the count of minors and the name shown in /proc/devices. The kernel hands out majors from the top of the dynamic range downwards, so a freshly booted machine gets high ones.
You still have to create the /dev node, with device_create or by hand, because registering a number does not make a file. Always call unregister_chrdev_region in your exit function and on every error path after the allocation. The interface is declared in fs.h, and the character device chapter shows the same pattern.