Linux driver ___ advanced character driver ___ IOCTL method explanation

Source: Internet
Author: User

 

~
IOCTL Method

  • Overview

    • Objective: To implement various types of hardware control through the device driver
    • User space call prototype: int IOCTL (int fd, unsigned long cmd ,...);
      • FD refers to the file descriptor.
      • "... "Represents an optional parameter, use "... "You can disable the logic check during compilation.
      • Used to use char * argp;
      • Optional parameters can be null, integer, or pointer. When a pointer is used, any amount of data can be exchanged.
    • Prototype implementation of the driver: int (* IOCTL) (struct inode * inode, struct file * filp, unsigned int cmd, unsigned long Arg );
      • Inode and filp pointers correspond to the file descriptor FD of the user space.
      • CMD parameters are directly transmitted without any modification
      • Arg receives optional parameters, and the receiving type is always unsigned long. The parameter type check is disabled. If any error occurs, no report is made.
      • Most IOCTL operations are completed using the switch statement.
  • IOCTL command Selection
    • IOCTL command structure

      • Reference File

        • Include/ASM/IOCTL. h
        • Documentation/ ioctl-number.txt
      • Bit Segment Structure
        • Type

          • Phantom (type), defined mainly in documentation/ioctl-number.txt
          • Bit Width: 8 bits (_ ioc_typebits)
        • Number
          • Ordinal number)
          • Bit Width: 8 bits (_ ioc_nrbits)
        • Direction
          • A Data Transfer flag that defines the direction of data transmission. This field is a bit mask and can be separated by logical operations.
          • Available Value
            • No data transmission (_ ioc_none)

              • # Ifndef _ ioc_none

                # DEFINE _ ioc_none 0u

                # Endif

            • _ Ioc_read
              • # Ifndef _ ioc_read

                # DEFINE _ ioc_read 2u

                # Endif

            • _ Ioc_write
              • # Ifndef _ ioc_write

                # DEFINE _ ioc_write 1u

                # Endif

            • Bidirectional data transmission (_ ioc_read | _ ioc_write)
        • Size
          • Indicates the size of user data, which is related to the architecture, usually 13 or 14 bits.
          • Macro definition: _ ioc_sizebits
          • The system does not check fields. When user data is large, it can be omitted.
    • Construct the macro of the command number
      • Definition location: <ASM/IOCTL. h>; the type and number fields are passed in through the parameter, and the size field is obtained through the sizeof parameter of datatype.
      • _ IO (type, NR)
        • Used to construct a command number without Parameters
      • _ Ior (type, NR, datatype)
        • Command number used to construct a command to read data from the driver
      • _ Iow (type, NR, datatype)
        • Command Used to write data
      • _ IOWR (type, NR, datatype)
        • For bidirectional transmission
    • Unlock the macro of the bitwise Structure
      • Location defined <ASM/IOCTL. h>
      • _ Ioc_dir (NR)
      • _ Ioc_type (NR)
      • _ Ioc_nr (NR)
      • _ Ioc_size (NR)
  • Default return value that does not match the ioctl command number
    • Invalid parameter:-ENVAL
    • POSIX standard:-enotty
  • Predefined IOCTL commands
    • Some predefined commands can be identified by the kernel. These commands cannot reach the device during use and are run by the kernel. The results are unpredictable due to number conflicts.
    • Predefined command category
      • Commands that can be used for any file (common, device, FIFO, and socket)

        • Magic is "T"
      • Only applicable to commands of common files
      • File System-specific commands
        • It can only be executed on the host File System
    • Actual predefined commands
      • Fioclex

        • Sets the file IOCTL close on exec flag. After the setting, when the calling process executes a new program, the file descriptor is closed.
      • Fiounclex
        • The file IOCTL not close on exec flag is cleared during execution to restore common file behavior and cancel the fioclex operation.
      • Fioasync
        • Set or reset asynchronous notifications
        • The o_sync flag can be modified through fcntl. Therefore, fioasync is rarely used.
      • Fioqsize
        • The size of the returned file or directory.
        • Cannot be used for device files; otherwise, an enotty error occurs.
      • Fionbio
        • File IOCTL non-blocking I/O, that is, file IOCTL non-blocking I/O
        • This call modifies the o_nonblock flag in filp-> f_flags. The third parameter of the system call indicates whether to reset or set
        • The o_nonblock in filp-> f_flags is usually completed by the fcntl system calling the command f_setfl.
    • Use IOCTL Parameters
      • Some problems may occur when the third parameter of IOCTL is a pointer.
      • When the Pointer Points to the user space, the user space must be valid; otherwise, an error should be returned.
      • Address verification function access_ OK
        • Function declaration and prototype

          • <ASM/uaccess. h>
          • Int access_ OK (INT type, const void * ADDR, unsigned long size );
        • Parameter description
          • Type

            • Verify_read

              • Read data from user space
            • Verify_write
              • Write Data to user space
              • If you want to read and write data, use verify_write, which is a superset
          • ADDR
            • User space address
          • Size
            • The number of bytes of data. If it is int, It is sizeof (INT)
        • The returned value is the bool volume.
          • 1 is returned if the access is successful.
          • 0 is returned for access failure. In this case, the driver should return-efault to the caller.
        • Precautions
          • The verification of memory is not complete. Only the process verifies the access permission of the space, especially to ensure that the pointer does not point to the kernel space.
          • Most programs do not need to call this function directly. Most memory management functions process it.
      • Write/read data functions (limited to 1, 2, 4, and 8 bytes)
        • Write to user space

          • Put_user (datum, PTR );

            • Check the address. If the address is successful, 0 is returned. If the address fails,-efault is returned.
          • _ Put_user (datum, PTR );
            • No address check. You must call access_ OK for use.

          Read user space

          • Get_user (local, PTR)
          • _ Get_user (local, PTR)

          When the pointer type does not match the specified type, the compiler returns "conversion to non-scalar type requested"

          In this case, you must use copy_to_user or copy_from_user.

    • Capabilities and limited operations
      • Description of Power Check

        • Device Access is generally controlled by the permission of the device file, and the driver does not check
        • For some additional operations, the driver needs to perform additional checks to confirm whether the user has the right to perform
      • Capability)
        • Permission divides privileged operations into independent groups so that some specific users or programs can be authorized to perform specified operations without the permission to perform other operations.

          Related System Call functions: capget and capset. Therefore, you can manage functions in the user space.

      • Definition file
        • <Linux/capability. h>
      • Power of driver care
        • Cap_dac_override

          • Beyond the access permissions of files or directories, data access control or DAC)
        • Cap_net_admin
          • The ability to execute network management tasks, including tasks that affect network interfaces.
        • Cap_sys_module
          • Ability to load or delete Kernel Modules
        • Cap_sys_ramio
          • The ability to perform "Bare" I/O operations, such as accessing device ports or directly communicating with USB
        • Cap_sys_admin
          • It provides access to many system management operations.
        • Cap_sys_tty_config
          • Ability to execute tty Configuration Tasks
      • Capability check
        • When executing a special operation, the driver should check whether the calling process has the relevant capabilities
        • Function implementation
          • <Sys/sched. h>
          • Int capable (INT capability );
  • Implementation of IOCTL commands
    • Use switch statements for command control. For details, refer to scull source code.
    • Common Ways of passing parameters (6)
      • Int quantum;

         

        IOCTL (FD, scull_iocsquantum, & Quantum);/* set by pointer */

        IOCTL (FD, scull_ioctquantum, quantum);/* set by value */

         

        IOCTL (FD, scull_iocgquantum, & Quantum);/* Get by pointer */

        Quantum = IOCTL (FD, scull_iocqquantum);/* Get by return value */

         

        IOCTL (FD, scull_iocxquantum, & Quantum);/* Exchange by pointer */

        Quantum = IOCTL (FD, scull_iochquantum, quantum);/* Exchange by value *

         

  • Non-IOCTL Device Control-referral Sequence
    • Applicable to devices that only execute commands and do not need data transmission.
    • Misunderstanding may occur when a controller is used to write data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.