Device number
- C course
- Expert
- Lesson 10/47
- 5 min
Learn device numbers and registration.
dev_t: device number
On Linux every character or block device has a device number (dev_t). The number has two parts: major and minor.
The major number identifies the driver; the minor identifies a device under that driver. The dev_t type is defined in <linux/types.h>. MKDEV(major, minor) combines them; MAJOR(dev) and MINOR(dev) split them. ls -l /dev shows major and minor numbers. Driver authors request numbers with alloc_chrdev_region.
Number allocation
Driver authors get device numbers two ways: static register_chrdev_region or dynamic alloc_chrdev_region. The dynamic path lets the kernel pick a suitable major.
Dynamic allocation is preferred to avoid clashes. On success, the dev_t variable holds the major and minor. When the driver is removed, unregister_chrdev_region gives the number back. On the init error path the number must be released, or it leaks. The device cannot be registered before the number is allocated.
Practice Print device numbers
Define void print_dev(int major, int minor) with body printf("dev=%d:%d\n", major, minor);. In main call it for three devices: (10, 0), (1, 5), (254, 1).
Starter code
#include <stdio.h>
// Define print_dev function
// Call it for three (major, minor) pairs
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_dev(int major, int minor) {
printf("dev=%d:%d\n", major, minor);
}
int main(void) {
print_dev(10, 0);
print_dev(1, 5);
print_dev(254, 1);
return 0;
}Expected output
dev=10:0 dev=1:5 dev=254:1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the dev_t type hold?
- Only major
- Major and minor Correct answer
- The device name
- Only minor
Explanation: dev_t stores both major and minor together.
2 Match device number macros
| Term | Meaning |
|---|---|
dev_t |
Device number |
MKDEV |
Combine major and minor |
MAJOR |
Major number |
MINOR |
Minor number |
3 Complete the MKDEV call
dev_t dev = MKDEV(____, minor);
dev_t dev = MKDEV(major, minor);
Explanation: MKDEV takes major first, then minor.