Dynamic character-device number allocation

ID: dynamic-character-device-number-allocation

Dynamic character-device number allocation asks the Linux kernel to reserve a range of character-device numbers while choosing its major device number at runtime. The API is alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name). It returns zero on success or a negative error code; the first assigned combined device number is written through dev. The return status is not the allocated major number.[ref]
For an original request, suppose alloc_chrdev_region(&first, 5, 3, "sample") succeeds and the returned first has major . Its reserved identifiers are , and , not . If one illustrative successful run returned major 243, the caller would use 243; another allocation can return a different major. This is a hypothetical range example, not a kernel operation executed here.
Keep first and the successful reservation count for cleanup. If a later initialization step fails, unregister_chrdev_region(first, 3) releases this reservation; it must not be treated as ownership of every minor under the returned major. Unwinding a failed character-device registration releases only resources actually acquired.
Number reservation is separate from associating file operations with a live character-device object and from creating a device node. The related cdev_add operation makes a registered object live; its name or bookkeeping label does not itself establish a pathname under /dev.[ref]
Removal must also respect existing users. cdev_del prevents new opens, but already open file descriptors can still call device operations, so deleting the registration alone does not prove that backing state can be freed immediately.[ref] A dynamic number is a reserved interface identifier, not a persistent hardware identity or an inode number.

New to topics? Read the docs here!