Character Device Control
First, the equipment control theory
1.1 Effects
Most drivers require the ability to control equipment in addition to the ability to provide read and write equipment. For example: Change the baud rate.
1.2 Device Control-application functions
In user space, using the IOCTL system call to control the device, the prototype is as follows:
int ioctl (int fd,unsigned long cmd,...)
FD: Device file descriptor to control
CMD: control commands sent to the device
...: the 3rd parameter is an optional parameter, whether the presence or absence is dependent on the control command (the 2nd parameter).
1.3 Device driver functions
When an application uses the IOCTL system call, the driver is
The following function responds to:
The kernel before 1:2.6.36
Long (*ioctl) (struct inode* node,struct file* filp, unsigned int cmd,unsigned long arg)
The kernel after 2:2.6.36
Long (*unlocked_ioctl) (struct file *filp, unsigned int cmd, unsigned long arg)
Parameter cmd: command passed down by the application function ioctl
Second, the realization of equipment control
2.1 Defining commands
The command is an integer in its essence, but to make the integer more readable, we usually divide the integer into several segments: type (8-bit), ordinal, direction of parameter transfer, parameter length.
Type (Types/magic number): Indicates which device the command belongs to.
Number (ordinal) to distinguish different commands from the same device
Direction: Direction of parameter transfer, possible value _ioc_none (no data transfer), _ioc_read, _ioc_write (write parameter to device)
Size: Parameter length
The Linux system provides the following macros to help define the command:
_io (TYPE,NR): command with no parameters
_ior (type,nr,datatype): command to read parameters from the device
_iow (type,nr,datatype): command to write parameters to the device
Cases:
#define Mem_magic ' m '//define magic number
#define Mem_set _iow (mem_magic, 0, int)
2.2 Implementing the Operation
The implementation of the UNLOCKED_IOCTL function is usually a switch statement executed according to the command. However, when the command number does not match the command supported by any one device, the-einval is returned.
Programming Model:
Switch cmd
Case command A:
Perform a corresponding operation
Case Command B:
Perform a corresponding operation of B
Default:
Return-einval
Character Device Control Learning