Device driver – as the name suggests – it controls a device. It could a physical resource or a non-physical resource. In the following articles, we will ook through some device
The character device driver is the most basic device driver that an interested developer will see and needs to learn in the Linux kernel. It is a streams driver and handles data as a stream of bytes.
The character device driver operates on a character device file in the Linux kernel. all the file operations that can be performed on a typical file such as open, close, write, read, lseek can be be performed on the character device file.
The below code provides a sample implementation for a character device driver on linux. There are many articles on the Web explaining a character device driver. This specific articles intends to provide an overview via a code snippet.
In this example, the following callbacks have been initialised. At the most, these four callbacks need to be present. The structure file_operations can be referred at the location- /linux/fs.h
- open – open an instance of the device driver. Multiple instances can be opened up-till 256
- close an instance of the device driver
- write to the device driver
- read from the device driver
In the example two APIs are also observed.
- register_chrdev – register a character device driver to the kernel
- unregister_chrdev – un-register a character device driver from the kernel
Each character device driver has a Major number and a Minor number. The The Major number is the same for all instances of the character device and the Minor number varies according to different instances.
In the code snippet above,
Majornumber = register_chrdev(0, DEVICE_NAME, &fileops) – do note that the major number passed as a parameter to register_chrdev is ‘0’. When ‘0’ is passed, the kernel assigns a valid free Major number. This process is easier than defining a major number on our own accord and the possibility that the major number chosen is already in use by the kernel.
An interesting point to note and observe is that, what has been registered is a device driver to access a character device. However, there is no code snippet which actually creates the character device on which the character device driver will be perform actions upon.
Also, note that for the above code, the “mknod command” needs to be called from the terminal before this device driver is used for the device.
Now the character driver is ready for operation. In the next article, we will look at a sample code that opens the character device file instance created and the operation of the character driver
Pingback: Kernel Thread Code example | Hitch Hiker's Guide to Learning
Pingback: Character device driver sample user spacecode | Hitch Hiker's Guide to Learning
Pingback: Character Device driver – creating device file instance in code | Hitch Hiker's Guide to Learning