Skip to content
systemcoding.dev
Kernels

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.

1 min read
Summarize in AI

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.

c
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;
}
Text
demo: major 236

Your 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.

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.