Zeng Zi said, “The superior man makes friends with his literature, and with his friends he supports his benevolence.” The Analects of Confucius: Yan Yuan
A hundred blog series. This is:
V67. Xx HongMeng kernel source code analysis (character device) | bytes read/write device for the unit
File system related sections are as follows:
- V62. Xx HongMeng kernel source code analysis concept (file) | why everything is the file
- V63. Xx HongMeng kernel source code analysis (file system) | said in books management file system
- V64. Xx HongMeng kernel source code analysis (inode) | who is the most important concept of file system
- V65. Xx HongMeng kernel source code analysis (mount directory) | why need to mount the file system
- V66. Xx HongMeng kernel source code analysis (the root file system) | on first
/
File system on - V67. Xx HongMeng kernel source code analysis (character device) | bytes read/write device for the unit
- V68. Xx HongMeng kernel source code analysis file system (VFS) | the foundation of the harmonious coexistence
- V69. Xx HongMeng kernel source code analysis (file handle) | why do you call a handle?
- V70. Xx HongMeng kernel source code analysis (pipe file) | how to reduce the data flow cost
What is equipment
Device: A device that provides input or output functions. It includes a physical device (an abstraction of actual physical hardware). For example, a keyboard is an input device and a hard disk is an input and output device. Also includes virtual appliances (not dependent on specific physical hardware, but only emulation/virtual functionality provided by the kernel itself). For example, the virtual console is an input and output device. Each device corresponds to a file (device file), which is managed in a common location /dev. Device files (or device nodes) are used to operate devices using drivers.
According to different access modes, devices are divided into two types:
-
Character devices: Character devices are handled by character. The most obvious example is the keyboard, where each key generates a character on the device. And the mouse, which sends a character to the /dev/mouse device for every action or button click. Character equipment can be understood as a commodity retailer, can sell one by one, sell fine nature will sell less.
-
Block devices: Storage devices that read data in larger chunks, such as IDE disks (also called mechanical disks (/dev/ hd), SCSI disks (also called solid-state disks (/dev/ SD), and CD-ROM (/dev/cdrom). I/O interaction with block devices processes blocks of data, allowing large amounts of data to be moved back and forth to improve efficiency. Block equipment can be understood as a commodity wholesaler, must sell a box by box, sell coarse but large throughput.
-
The definition of a character device versus a block device belongs to the kernel device access layer and is not necessarily related to the characteristics of the actual physical device. Below the device access layer is the driver, which can be accessed depending on whether the driver supports it or not, and can also support both ways of accessing the physical device, block or character, depending on the consumer (often the kernel).
Common character devices in the Hongmeng system are as follows:
Mem | memory devices
/dev/mem a full mirror of the physical memory. Can be used for direct access to physical memory. The /dev/kmem kernel sees a full mirror of virtual memory. It accesses virtual memory instead of physical memory. /dev/null Indicates an empty device. Also called black hole devices, any writes are discarded (but return "success "); Any read will get an EOF(end-of-file flag). /dev/port Access I/O port /dev/zero Zero flow source. Any writes are discarded (but return "success "); Any read will result in an infinite number of binary zero streams. /dev/full Full device. Any writes will fail, and errno is set to ENOSPC(no space left); Any read will result in an infinite number of binary zero streams. This device is often used to test the behavior of a program when it encounters a disk free error. /dev/random True random number generator. With background noise data or hardware random number generator as entropy pool, random bytes less than the total entropy pool noise are returned when reading. If the entropy pool is empty, the read operation will be blocked until enough ambient noise is collected. It is recommended to generate high-strength keys. [Note] Attempts to "prestore" random numbers by writing to this file are futile, although writes are allowed, because the data being written has no effect on the output. /dev/urandom pseudo-random number generator. Faster, but not as safe. Only applicable to scenarios with low requirements on security. Even if the entropy pool is empty, the read operation will not be blocked, but will seed the generated random number to generate a new random number. [Note] Attempts to "prestore" random numbers by writing to this file are futile, although writes are allowed, because the data being written has no effect on the output. /dev/aio asynchronous I/O notification interface /dev/kmsg Any write to this file will be taken as printk output; Reading results in the output buffer contents of printk.Copy the code
- In HongMeng,
/dev/mem
Is a character device, the source file is a kernel/drivers/char/mem/SRC/mem. C, this device file is dedicated to reading and writing physical address. The contents are the addresses and contents of all physical memory. Generally, only the root user has the read and write permission. usingmmap
and/dev/mem
Establish direct access to the system’s physical memory. using/dev/mem
andmmap
Exporting system physical addresses eliminates the cumbersome copying of user virtual addresses to kernel logical addresses, improving efficiency.Static ssize_t MemMap(struct file *filep, LosVmMapRegion *region) { #ifdef LOSCFG_KERNEL_VM size_t size = region->range.size; PADDR_T paddr = region->pgOff << PAGE_SHIFT; VADDR_T vaddr = region->range.base; LosVmSpace *space = LOS_SpaceGet(vaddr); if ((paddr >= SYS_MEM_BASE) && (paddr < SYS_MEM_END)) { return -EINVAL; } /* Peripheral register memory adds strongly ordered attributes */ region->regionFlags |= VM_MAP_REGION_FLAG_STRONGLY_ORDERED; if (space == NULL) { return -EAGAIN; }// map if (LOS_ArchMmuMap(&space->archMmu, vaddr, paddr, size >> PAGE_SHIFT, region->regionFlags) <= 0) {return -EAGAIN; } #else UNUSED(filep); UNUSED(region); #endif return 0; Static const struct file_operations_vfs g_memDevOps = {MemOpen, /* open */ MemClose, /* close */ MemRead, /* read */ MemWrite, /* write */ NULL, /* seek */ NULL, /* ioctl */ MemMap, /* mmap */ #ifndef CONFIG_DISABLE_POLL NULL, /* poll */ #endif NULL, /* unlink */ }; // register /dev/mem driver int DevMemRegister(void) {return register_driver("/dev/mem", &g_memdevops, 0666, 0); /* 0666: file mode */ }Copy the code
Tty | terminal equipment
TTY is short for Teletype or Teletypewriter, a device that was gradually replaced by a keyboard and monitor. Both teletypewriters and keyboard monitors are used as terminal devices of a computer, so TTY also refers to the terminal devices of a computer, generally divided into the following categories
- Serial port terminal (/dev/ttySn)
- Pseudo terminal (/dev/pty/)
- Control terminal (/dev/tty)
- The console terminal (/dev/ttyn, /dev/console), will be explained in more detail in a future console chapter
RTC | clock equipment
/dev/rTC Real Time ClockCopy the code
- Real-time clock (RTC) is a real-time clock device in an operating system. It provides accurate real-time time and timing alarm functions for the operating system. After the device is powered off and powered by an external battery, the RTC records the operating system time. After the device is powered on, the RTC provides a real-time clock for the operating system to ensure system time continuity after a power failure
- RTC it can be used to generate information such as year, month, day, hour, minute, and second. At present, most real-time clock chips use crystal oscillators with high precision as clock sources. Some clock chips add battery power to keep time information active even if the main power supply fails.
- Hongmeng RTC DEVICE API function description
RtcOpen Obtain the RTC device driver handle RtcClose Release the RTC device driver handle RtcReadTime Time to read RTC information, including year, month, week, day, hour, minute, second, and millisecond RtcWriteTime Time to write RTC information. Includes year, month, week, day, hour, minute, second, and millisecond RtcReadAlarm Time to read RTC alarm RtcWriteAlarm Time to write RTC alarm RtcRegisterAlarmCallback Registers the alarm timeout callback function RtcAlarmInterruptEnable RtcGetFreq RtcSetFreq RtcReset RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcReadReg RtcWriteReg writes user - defined registersCopy the code
I2C bus equipment |
/dev/i2c-0 first i2C adapter... /dev/i2c-n Indicates the n-1st I2C adapterCopy the code
- I2C(Inter Integrated Circuit) bus is a simple bidirectional two-wire synchronous serial bus developed by Philips Company.
- I2C works in master/slave mode. Usually, there is one master device and one or more slave devices. The master and slave devices are connected by two cables, namely the SerialData cable (SDA) and the SerialClock cable (SCL), as shown in the following figure.
- I2C data transmission must start with a start signal and stop with an end signal. Data transmission is carried out in the unit of bytes, with the highest order, bit by bit.
- Each device on the I2C bus can be as the main equipment or from the device, and each device will correspond to a unique address, when the main equipment are in need and a communication from the device, through the way of radio, will from device address to the bus, if someone from the equipment up to the address, will signal response, transmission is established.
- The I2C interface defines a general set of methods for completing I2C transport, including:
- I2C controller management: Enable or disable the I2C controller
- I2C message transport: Custom transport through an array of message transport structures
- Hongmeng I2C driver API function description
I2cOpen Enables I2C controller I2cClose Disables I2C controller I2cTransfer user-defined transmission and I2C message transfer interfaceCopy the code
SPI serial peripheral equipment |
- SPI stands for Serial Peripheral Interface and is a high-speed, full-duplex, synchronous communication bus.
- SPI was developed by Motorola for communication between master and slave devices, often with flash memory, real-time clocks, sensors, and analog-to-digital converters.
- Spis work in master-slave mode, usually with one master device and one or more slave devices. The master device and the slave device are generally connected by four wires, which are as follows:
- SCLK – Clock signal, generated by the master device; (Serial Clock)
- MOSI – Master device data output, slave device data input; (SPI Bus Master Output/Slave Input)
- MISO – Master device data input, slave device data output; (SPI Bus Master Input/Slave Output)
- CS – Chip selection, slave device enable signal, controlled by the master device. (Chip select)
- SPI master/slave device connection diagram
- SPI communication is usually initiated by the master device and a communication is completed through the following steps:
- Select the slave device to communicate through CS. At any time, only one slave device can be selected on a master device.
- Provides clock signals to selected slave devices through SCLK.
- Based on SCLK clock signal, data from the master device is sent to the slave device through MOSI, and data from the slave device is received through MISO to complete communication.
- Based on the different combinations of SCLK Clock signals’ CPOL (Clock Polarity) and CPHA (Clock Phase), SPI has the following four working modes:
- CPOL=0, CPHA=0 Clock signal idle state is low level, the first clock edge sampling data.
- CPOL=0, CPHA=1 Clock signal idle state is low level, the second clock edge sampling data.
- CPOL=1, CPHA=0 Clock signal idle state is high level, the first clock edge sampling data.
- CPOL=1, CPHA=1 Clock signal idle state is high level, the second clock edge sampling data.
- The SPI interface defines a common set of methods for manipulating SPI devices, including:
- SPI device handle gets and releases.
- SPI read and write: Reads or writes data of a specified length from an SPI device.
- SPI custom transport: Performs any combination of reads and writes through the message transport structure.
- SPI device Configuration: Gets and sets SPI device properties.
- Hongmeng SPI driver API function description
SpiRead Reads data of a specified length SpiWrite writes data of a specified length SpiTransfer SPI data transmission interface SpiSetCfg According to the specified parameters, SpiGetCfg Obtain SPI device configuration parametersCopy the code
UART | serial port devices
/dev/ttys0 UART Serial port (Serial port)... /dev/ttys200 199th UART serial portCopy the code
- A serial port device is a terminal device. The serial port device is /dev/ttysn or /dev/tts/n, which corresponds to COM1 and COM2 in Windows respectively. To send data to a port, you can redirect standard output to these special file names on the command line. For example, typing echo test > /dev/ttys1 at the command line prompt will send the word “test” to a device connected to port ttyS1(COM2).
- Universal Asynchronous Receiver/Transmitter (UART), as an Asynchronous serial communication protocol, works by transmitting each character of data one by one. It is the most frequently used data bus in application development.
- UART is widely used to output printed information, and can also be connected to various external modules, such as GPS and Bluetooth.
- The UART serial port is characterized by sequential transmission of data bit by bit. As long as there are two transmission lines, two-way communication can be realized. One line sends data while the other line receives data. The UART serial port communication has several important parameters, including baud rate, start bit, data bit, stop bit, and parity check bit. For two ports using the UART serial port communication, these parameters must match; otherwise, the communication will fail. The data format of UART serial port transmission is shown as follows:
-
Start bit: indicates the start of data transmission. The level logic is 0.
-
Data bits: The possible values are 5, 6, 7, 8, and 9, indicating the transmission of these bits of data. The value is usually 8, because an ASCII character is 8 bits.
-
Parity bit: Used by the receiver to verify the received data. The bits of “1” are even (parity check) or odd (parity check) to verify the correctness of data transmission. This bit is not required.
-
Stop bit: Indicates the end of a frame. The level logic is 1.
-
Baud rate: The rate of serial communication, expressed in the number of significant bits of binary code transmitted per unit of time, expressed in bits per second (BPS). Common baud rate values include 4800, 9600, 14400, 38400, and 115200. A higher baud rate means that 115,200 bits of data are transmitted per second.
-
The UART interface defines a set of common methods for operating the UART port, including obtaining and releasing device handles, reading and writing data, obtaining and setting baud rates, and obtaining and setting device properties.
-
Hongmeng UART driver API function description
UartOpen UART Obtains the device handle UartClose UART Releases the device handle UartRead reads the specified length of data from the UART device UartWrite writes the specified length of data to the UART device UartGetBaud UART Obtains the baud rate UartSetBaud UART Sets the baud rate. UartGetAttribute UART Obtains device attributes. UartSetAttribute UART Sets device attributesCopy the code
LCD | screen equipment
/dev/lcd LCD displayCopy the code
- Liquid Crystal Display (LCD) driver: Powers on the LCD and initializes the INTERNAL register of the LCD through the interface to make the LCD work normally. The Display Driver model is developed based on the Hardware Driver Foundation (HDF) Driver framework. It is cross-os and cross-platform, provides power-on and power-off functions for LCD Hardware, sends initialization sequence functions, and makes LCD enter normal working mode to Display image data on chip platform side.
- Display driver model based on HDF driver framework
Touchscreen | touch device
-
Touch (Touch chip) is an important part of human-computer interaction in UI design. A complete UI design should include input information and output information. LCD and other screen devices are responsible for displaying output, so Touch devices are responsible for collecting contact information as information input.
-
The Touch device generally uses the I2C bus protocol to communicate with the host for data interaction, so a Touch device is a standard I2C slave device, and in order to improve the real-time reception of Touch data, the Touch chip will provide interruption support, when there is a Touch event (lift, press, When move occurs, an interrupt is triggered to notify MCU of a touch event. The host can interrupt the callback function to read the touch point information.
-
Touchscreen devices hardware interface is relatively simple, according to the PIN feet attributes, can be divided into the following three categories: simple
- The power interface
- IO control interface
- Communication interface
-
Touchscreen drivers are used to drive the Touchscreen for normal operation, such as powering on the Touchscreen driver IC, configuring hardware pins and initializing its state, registering interrupts, configuring communication interfaces (I2C or SPI), setting input related configurations, downloading and updating firmware, etc.
-
Touchscreen drivers are developed based on the INPUT driver model. The Input drive model is developed on the basis of HDF drive framework, PLATFORM Interface, and OSAL, and connects to the normalized Hardware Driver Interface (HDI) layer to provide Hardware capabilities. That is, the upper input service can access the corresponding driver capabilities through the HDI interface layer, thus controlling the input devices such as touchscreen.
-
Input driver model based on HDF driver framework
Sensor | sensing devices
/ dev/biometric sensor0 / fingerprint of the first equipment 1 / dev/biometric fingerprint sensor/sensor0 / iris 1 first iris sensor devices / dev/biometric sensor0 / retina first equipment first retinal sensor/dev/biometric sensor0 / voiceprint 1 first acoustic sensor devices / dev/biometric sensor0 / differentiated bi-facial first equipment first facial sensor/dev/biometric sensor0 / hand first first hand the sensor of the equipment / dev/biometric sensor1 / fingerprint 1 second device/dev/biometric fingerprint sensor/sensor2 / fingerprint third equipment first fingerprint sensorCopy the code
-
Sensor is an important part of the Internet of Things. Sensor to the Internet of Things is just like “eyes to human beings”. The same is true for the Internet of things.
-
Nowadays, with the development of the Internet of Things, a large number of sensors have been developed for developers to choose, such as: Accelerometer, Magnetometer, Gyroscope, Barometer/pressure, Humidometer, etc. These sensors, manufactured by the world’s major semiconductor manufacturers, increase the market’s selectivity, but also the difficulty of application development. Because different sensor manufacturers, different sensors need to support their own unique driver to run, so in the development of applications need to adapt to different sensors, naturally increased the difficulty of development.
-
In order to reduce the difficulty of application development and increase the reusability of Sensor driver, Hongmeng Sensor driver module provides stable Sensor basic capability API for the upper Sensor service system, including Sensor list query, Sensor start and stop, Sensor subscription and desubscription. Sensor parameter configuration and other functions; The Sensor Driver model developed based on the Hardware Driver Foundation (HDF) Driver framework realizes cross-operating system migration, device differential configuration and other functions.
-
Hongmeng Sensor driver model diagram
The watchdog | watchdog
/dev/watchdogs (CONFIG_WATCHDOG) /dev/watchdogs/0 first watchdog... /dev/watchdogs/n Specifies the n-1 watchdogCopy the code
-
A watchdog timer is a timer whose timing output is connected to the reset end of the circuit. In a productized embedded system, it is generally necessary to introduce a watchdog in order to enable the system to reset automatically under abnormal circumstances.
-
When the watchdog starts, the counter starts counting automatically. If it is not reset before the counter overflows, it will send a reset signal to the CPU to restart the system (commonly known as “bitten by the dog”). When the system is running normally, it is necessary to clear the watchdog counter (commonly known as “feeding the dog”) within the time interval allowed by the watchdog to prevent the reset signal from being generated. If the system doesn’t break down, the program can “feed the dog” on time. Once the program runs away, there is no “feed the dog” and the system “gets bitten” reset.
-
This section describes the HONGmeng Watchdog API function
WatchdogOpen Opens the watchdog WatchdogClose closes the watchdog WatchdogStart Starts the watchdog WatchdogStop Stops the watchdog WatchdogSetTimeout Sets the watchdog timeout period WatchdogGetTimeout Specifies the watchdog timeout period. WatchdogGetStatus Specifies the watchdog status. WatchdogFeed Specifies the watchdog timeout period.Copy the code
WLAN | wireless network equipment
- WLAN is a module developed based on the Hardware Driver Foundation (HDF) Driver framework. The module supports cross-operating system migration, adaptive component differences, and modular assembly and compilation. WLAN driver developers can adapt their own driver codes based on the unified downward interface provided by the WLAN module to achieve the following capabilities: Creating, disabling, scanning, and associating WLAN hotspots. The HDI layer provides the following capabilities: Setting the MAC address, transmitting power, and obtaining the MAC address of a device.
- WLAN framework
- The WLAN module provides three open apis
- Capability interface to the HDI layer.
- The driver directly invokes the WLAN module capability interface.
- Capability interfaces for vendors to implement.
Intensive reading of the kernel source code
Four code stores synchronous annotation kernel source code, >> view the Gitee repository
Analysis of 100 blogs. Dig deep into the core
Add comments to hongmeng kernel source code process, sort out the following article. Content based on the source code, often in life scene analogy as much as possible into the kernel knowledge of a scene, with a pictorial sense, easy to understand memory. It’s important to speak in a way that others can understand! The 100 blogs are by no means a bunch of ridiculously difficult concepts being put forward by Baidu. That’s not interesting. More hope to make the kernel become lifelike, feel more intimate. It’s hard, it’s hard, but there’s no turning back. 😛 and code bugs need to be constantly debug, there will be many mistakes and omissions in the article and annotation content, please forgive, but will be repeatedly amended, continuous update. Xx represents the number of modifications, refined, concise and comprehensive, and strive to create high-quality content.
Compile build | The fundamental tools | Loading operation | Process management |
---|---|---|---|
Compile environment The build process Environment script Build tools Designed.the gn application Ninja ninja |
Two-way linked list Bitmap management In the stack way The timer Atomic operation Time management |
The ELF format The ELF parsing Static link relocation Process image |
Process management Process concept Fork Special process Process recycling Signal production Signal consumption Shell editor Shell parsing |
Process of communication | Memory management | Ins and outs | Task management |
spinlocks The mutex Process of communication A semaphore Incident control The message queue |
Memory allocation Memory management Memory assembly The memory mapping Rules of memory Physical memory |
Total directory Scheduling the story Main memory slave The source code comments Source structure Static site |
The clock task Task scheduling Task management The scheduling queue Scheduling mechanism Thread concept Concurrent parallel The system calls Task switching |
The file system | Hardware architecture | ||
File concept The file system The index node Mount the directory Root file system Character device VFS File handle Pipeline file |
Compilation basis Assembly and the cords Working mode register Anomaly over Assembly summary Interrupt switch Interrupt concept Interrupt management |
HongMeng station | into a little bit every day, the original is not easy, welcome to reprint, please indicate the source.