Understanding Major and Minor Numbers in Linux

In Linux, major and minor numbers are used to identify and manage devices through device files located in the /dev directory. These numbers serve as identifiers for the kernel to communicate with the appropriate device driver.

Major Number

  • The major number identifies the device driver that handles a specific device.
  • It serves as a key for the kernel to map a device file to the corresponding device driver.
  • Example: A major number of “8” might be associated with the SCSI disk driver.

Minor Number

  • The minor number identifies a specific device or sub-device that the driver manages.
  • It is used in conjunction with the major number to differentiate between multiple devices handled by the same driver.
  • Example: For a hard disk with major number “8”, minor numbers 0, 1, 2, etc., may refer to partitions or different disks.

Examples in /dev Directory

ls -l /dev/sda


Output:

brw-rw---- 1 root disk 8, 0 Dec 9 10:30 /dev/sda


In the output:

- `8` is the major number, which indicates the SCSI disk driver.
- `0` is the minor number, which indicates the first disk or partition.

When a device file is accessed (for example, `/dev/sda`):

1.  The kernel looks at the major number to locate the corresponding device driver.
2.  The device driver then uses the minor number to interact with the specific device or sub-device.

## Allocation of Numbers: Static vs Dynamic

Linux represents devices as a pair of numbers `<major>:<minor>`.

Some functions used to assign and de-assign the major and minor numbers are as follows:

```c
int register_chrdev_region(dev_t first, unsigned int count, char *name); // Static allocation
int alloc_chrdev_region(dev_t *dev, unsigned int first_minor, unsigned int count, char *name); // Dynamic allocation
void unregister_chrdev_region(dev_t first, unsigned int count);  // Deregister major and minor numbers
MKDEV(major, minor) // function to initialize dev_t dev variable
MAJOR( dev_t dev) // to access major number
MINOR(dev_t dev) // to access minor number

Command to Create Device File

mknod –m <permissions> <name> <device type> <major> <minor>

// Manual creation

  • -m <permissions>: Sets the permission bits of the new device file to permissions.
  • <name>: Your device name with the full path (/dev/name).
  • <Major>: Major number of your device.
  • <Minor>: Minor number of your device.
  • <device type>: c - character device, b - block device.

Commands to View Major and Minor Numbers

  • ls -l: Shows the major and minor numbers for a device file.
  • cat /proc/devices: Lists major numbers associated with different drivers.
  • dmesg: Displays kernel messages, which may include major and minor numbers during device initialization.