contact@allblognow.comLogin
all blog now

May 29, 2024

What is a Misc Device?

A misc device is a small kernel driver that takes care of a single, simple device and allows the user module to register an entry point to take control of it. The misc device driver is a good choice for small hardware or software hacks that are not large enough to warrant the effort required to write a full character driver.

The misc device driver registers a node in /dev with a major number (10) reserved for misc devices and then allows the user space application to open(), read() and ioctl() on that device. This avoids the complexities involved in registering and unregistering a driver using cdev_init, cdev_add, device_create and class_create.

When a misc device is registered, the device file is created automatically for it in /dev. It also makes it easy to create a custom entry point for the device because it only needs to be aware of its minor number and no other information.

To register a misc device, the kernel provides a function named misc_register(). The structure passed to this function is linked into the kernel and must not be destroyed until it has been unregistered by misc_register(). This function is called in the driver's init function and returns a zero on success or a negative errno code on failure.

It is not recommended to hardwire the minor number for a misc device because the code in drivers/char/misc doesn't check for this and if you hardcode the minor number and it gets assigned to an official driver, you can end up with a dead lock in the system because the driver will refuse to open your device.

The example below is a very simple misc device that allows you to control the LEDs on the keyboard. It uses dynamic minor number allocation and accepts one byte commands, such as "N" to turn the Num-Lock LED on, "n" to turn it off and the digits from 0 to 7.

You can use this function in your own misc device to register your device. The /proc/misc file is then created automatically and you can call the open(), read() and ioctl() functions on this device with any POSIX-like program.