Hello! Welcome to Embedic!
This website uses cookies. By using this site, you consent to the use of cookies. For more information, please take a look at our Privacy Policy.
Home > Embedded Events > From serial port driver to Linux driver model, embedded will surely!

From serial port driver to Linux driver model, embedded will surely!

Date: 16-11-2020 ClickCount: 533

This article analyzes the serial port driver under Linux. From the top C library. Encapsulation to the operating system system call layer. Then to the core of the tty subsystem. And then to a series of wiring regulations. Then to the lowest level hardware operation.

A brief description of the tty subsystem in Linux. From theory to practice. So that readers can have a deeper understanding and more specific grasp of OS principles.

Before specific analysis. We must be on the serial port. drive. Have a certain understanding of Linux operating system. At this stage we have three problems to be solved:

1. What is the Linux operating system.

1. What is the Linux operating system.

2. What is a Linux device driver.

3. All kinds of serial ports.

To understand these concepts. Below I introduce a little bit of this knowledge. Unfortunately, there are unavoidable forward references to some concepts.

In this process, I will try to ignore secondary factors. Take the main purpose of this survey as the main line. If the reader has a deep understanding of these concepts. You can directly read the following code analysis:

1. What is the Linux operating system?

Linux is a free-to-use and freely disseminated Unix-like operating system. It is a multi-user, multi-task, multi-thread and multi-CPU operating system based on POSIX and UNIX.

It can run major UNIX tools, applications, and network protocols. It supports 32-bit and 64-bit hardware. Linux inherits Unix's network-centric design philosophy and is a multi-user network operating system with stable performance.

The Linux operating system was born on October 5, 1991 (this is the first time it was officially announced). There are many different Linux versions of Linux, but they all use the Linux kernel.

Linux has amazing portability. It can be installed in various computer hardware devices, such as mobile phones, tablets, routers, video game consoles, desktop computers, mainframes, and supercomputers.

Strictly speaking, the word Linux itself only refers to the Linux kernel, but in fact, people are used to using Linux to describe the entire operating system based on the Linux kernel and using various tools and databases from the GNU project.

In these brief paragraphs. Many new terms have been introduced. Below I describe a few important concepts.

A. About UNIX-like systems

Unix-like systems (English: Unix-like) refer to various traditional Unix systems (such as FreeBSD, OpenBSD, Sun's Solaris) and various systems similar to traditional Unix (such as Minix, Linux, QNX, etc.).

Although some of them are free software and some are commercial software, they all inherit the characteristics of the original UNIX to a certain extent, have many similarities, and all comply with the POSIX specification to a certain extent.

This has been explained in some classic operating system textbooks. We just need to know. It is the same as the well-known Windows operating system. Both are a modern operating system. Abstract the underlying computer resources. Provide a calling interface for upper-level users. Complete the functions that the computer should perform.

B. About portability

Portability refers to how easy it is to transfer software from one environment to another. In order to obtain higher portability, a common programming language and operating support environment are often used in the design process. Try not to use languages ​​that are strongly related to the underlying system.

Portability is one of software quality, and good portability can improve the life cycle of software. The subject of code portability is software; portability is a capability attribute of software products whose behavior is expressed as a degree, and the degree of manifestation is closely related to the environment.

The portability of an operating system is often manifested in its ability to run on different architectures. Perceptual understanding is that there are many devices that can be supported. For example, as mentioned above, Linux can run on large servers. On various tablets.

Some time ago, a hacker successfully ported Linux to a Canon camera. And some mainstream software is running on this camera. It can be said. As long as there are enough hardware resources available. You can port Linux to this hardware platform. The minimum requirements for this resource are often very low. This can be in sharp contrast with Windows, which requires high hardware resources. For example. When the Windows 10 upgrade prompt pops up from the lower right corner of your computer.

Can you click "Upgrade Now" without thinking? I think most people's answer to this question is no. why? Because in most cases. After the upgrade, it will become more card. The delay is greater. Some useless and huge software crazily occupy your limited computer resources. And if you choose Linux. You can install software on your computer almost arbitrarily. Run the program (if your memory is not too small. And the hard disk swap partition is enough).

The Linux kernel has maximized the limited hardware resources. The good modular design of open source software makes full use of the principle of program locality at all levels. (Of course this is under the premise of losing a certain ease of use.). I'm sorry I'm pulling away. These are not the focus of this article. .

Because the author is not rich enough to have many computers. So I chose a cheaper ARM9 development board as the development platform. Its CPU is S3C2440 produced by Samsung. The core is ARM920T.

C. Basic ideas about Linux

The basic idea of ​​Linux has two points:

the first. Everything is a file. Everything in the system boils down to one file, including commands, hardware and software devices, operating systems, processes, etc. For the operating system kernel, they are all regarded as files with their own characteristics or types. As for Linux is based on Unix, it is largely because the basic ideas of the two are very similar.

second. Each software has a certain purpose. .

D. About the characteristics of Linux

Completely free

Linux is a free operating system, users can obtain it for free through the Internet or other channels, and can modify its source code at will. This is something other operating systems cannot do.

It is precisely because of this that countless programmers from all over the world have participated in the modification and writing of Linux, and programmers can change it according to their own interests and inspiration. This allows Linux to absorb the essence of countless programmers and continue to grow.

Fully compatible with POSIX1.0 standard

This makes it possible to run common DOS and Windows programs through the corresponding simulator under Linux. This laid the foundation for users to switch from Windows to Linux.

When many users consider using Linux, they think about whether the programs that were previously common under Windows can run normally, which eliminates their doubts.

Multi-user, multi-task

Linux supports multiple users, each user has his own special rights to his own file device, ensuring that each user does not affect each other. Multitasking is one of the most important features of current computers. Linux can make multiple programs run simultaneously and independently.

Good interface

Linux has both a character interface and a graphical interface. In the character interface, users can input corresponding instructions through the keyboard to operate. It also provides an X-Window system similar to a Windows graphical interface, and users can use the mouse to operate it. In the X-Window environment, it is similar to Windows, and it can be said to be a Linux version of Windows.

Support multiple platforms

Linux can run on a variety of hardware platforms, such as platforms with x86, 680x0, SPARC, Alpha and other processors. In addition, Linux is also an embedded operating system that can run on handheld computers, set-top boxes, or game consoles. The Linux 2.4 kernel released in January 2001 has been able to fully support the Intel 64-bit chip architecture. At the same time, Linux also supports multi-processor technology. Multiple processors work simultaneously, greatly improving system performance.

file type

Regular file: It is a file that is generally accessed. Among the attributes displayed by ls-al, the first attribute is [-], such as [-rwxrwxrwx]. In addition, according to the content of the file, it can be roughly divided into:

1. Plain text file (ASCII): This is the most common type of file in Unix systems. It is called a plain text file because the content can be directly read data, such as numbers, letters, etc. Almost all settings files belong to this file type. For example, use the command "cat ~/.bashrc" to see the contents of the file (cat reads the contents of the file).

2. Binary: The system actually only recognizes and can execute binary files. Executable files in Linux (scripts, batch files in text mode are not counted) are in this format. For example, the command cat is a binary file.

3. Data format file (data): Some programs will read files in certain specific formats during the running process, and those files in specific formats can be called data files. For example, when a user logs in, Linux will record the login data in the /var/log/wtmp file. This file is a data file that can be read out through the last command. But when using cat, garbled characters will be read. Because it belongs to a special format file.

4. Directory: it is a directory, the first attribute is [d], such as [drwxrwxrwx].

Link file (link): similar to the shortcut under Windows. The first attribute is [l], such as [lrwxrwxrwx].

5. Device and device files (device): Some files related to system peripherals and storage are usually concentrated in the /dev directory. Usually divided into two types:

Block device file: It is the interface device that stores data for system access, in short, it is the hard disk. For example, the code of hard disk No. 1 is /dev/hda1 and other files. The first attribute is [b].

Character device file: the interface device of the serial port, such as keyboard, mouse, etc. The first attribute is [c].

6. Sockets: This type of file is usually used in network data connections. You can start a program to listen to the client's request, and the client can communicate data through the socket. The first attribute is [s], this file type is most commonly seen in the /var/run directory.

7. Pipe (FIFO, pipe): FIFO is also a special file type. Its main purpose is to solve errors caused by multiple programs accessing a file at the same time. FIFO is an abbreviation of first-in-first-out. The first attribute is [p]

File structure

/: The root directory, all directories, files, and devices are under /. / is the organizer of the Linux file system and the top leader.

/bin: bin is the abbreviation of binary. In general systems, you can find commonly used Linux commands in this directory. The commands needed by the system are located in this directory.

/boot: Linux kernel and file directories needed to boot system programs, such as vmlinuz initrd.img files are located in this directory. In general, the GRUB or LILO system boot manager is also located in this directory.

/cdrom: This directory was empty when the system was just installed. You can mount the CD-ROM file system in this directory. For example: mount /dev/cdrom /cdrom

/dev: dev is the English abbreviation for device. This directory is very important to all users. Because this directory contains all the external devices used in the Linux system. But here is not the driver of the external device. This is different from the commonly used windows and dos operating systems. It is actually a port to access these external devices. It is very convenient to access these external devices, and there is no difference between accessing a file or a directory.

/etc: The etc directory is one of the most important directories in the Linux system. Various configuration files and subdirectories used in system management are stored in this directory. The network configuration files, file systems, x system configuration files, device configuration information, and user information to be used are all in this directory.

/home: If you create a user, the user name is "xx", then there is a corresponding /home/xx path in the /home directory to store the user's home directory.

/lib: lib is the English abbreviation of library. This directory is used to store system dynamic link shared libraries. Almost all applications will use the shared library in this directory. Therefore, do not easily perform any operations on this directory. Once a problem occurs, the system will not work.

/lost+found: In the ext2 or ext3 file system, when the system crashes unexpectedly or the machine shuts down unexpectedly, some file fragments are placed here. When the system starts, the fsck tool will check this and repair the damaged file system. Sometimes a problem occurs in the system, and many files are moved to this directory, which may be repaired manually, or moved to the original location.

/mnt: This directory is generally used to store the mount directory of the mounted storage device, such as cdrom and other directories. See the definition of /etc/fstab.

/media: Some Linux distributions use this directory to mount mobile hard drives (including U disks), CD/DVD drives, etc. with USB interfaces.

/opt: The optional programs are mainly stored here.

/proc: You can get system information in this directory. This information is in memory and is generated by the system itself.

/root: The home directory of Linux super user root.

/sbin: This directory is used to store the system management program of the system administrator. Most of the commands related to system management are stored, where the executable commands of the super-privileged user root are stored. Ordinary users have no permission to execute commands in this directory. This directory and /usr/sbin; /usr/X11R6/sbin or /usr The /local/sbin directory is similar, all directories contained in sbin can only be executed with root privileges. 

/selinux: For some configuration file directories of SElinux, SElinux can make Linux more secure.

After the /srv service is started, the data directory that needs to be accessed, for example, the web page data read by the www service can be placed in /srv/www

/tmp: Temporary file directory, used to store temporary files generated during the execution of different programs. Sometimes when a user runs a program, a temporary file is generated. /tmp is used to store temporary files. The /var/tmp directory is similar to this directory.

/usr: This is the directory that occupies the largest hard disk space in the Linux system. Many user applications and files are stored in this directory. In this directory, you can find additional tools that are not suitable for being placed in the /bin or /etc directory

/usr/local: This is mainly to store manually installed software, that is, software not installed through "Synaptic" or apt-get. It has a similar directory structure to the /usr directory. Let the package manager manage the /usr directory, and put custom scripts (scripts) under the /usr/local directory.

/usr/share: The storage location for things shared by the system, for example, /usr/share/fonts is the font directory, and /usr/share/doc and /usr/share/man help files.

/var: The content of this directory changes frequently, just look at the name. It can be understood as the abbreviation of vary. There is /var/log under /var which is the directory used to store system logs. The /var/www directory defines the storage directory of the Apache server site; /var/lib is used to store some library files, such as MySQL and the storage location of the MySQL database.

As above. I believe readers have an overview of the Linux operating system. For some specific commands. I will explain when I decide to use it. Now let’s look at the second concept:

2. What is a Linux device driver

The most popular explanation for device drivers is to drive hardware devices to act. The driver directly interacts with the underlying hardware. According to the specific working mode of the hardware device, it reads and writes device registers, completes device polling, interrupt processing, DMA communication, and performs physical memory to virtual memory mapping, etc., so that the communication device can send and receive data. , So that the display device can display text and pictures, and the storage device can record files and data.

The Linux device driver is an abstraction of the underlying hardware resources. Provide a good interface to other services of the upper operating system. Allow other services to put a specific hardware. Or a mechanism to use as a file. Use general system calls to call.

3. All kinds of serial ports

Well known. There are many interfaces on our current computer. Such as USB. Network port. Parallel etc. The serial bus is one of them. Serial interface is abbreviated as serial port, also called serial communication interface or serial communication interface (usually referred to as COM interface), which is an extended interface using serial communication.

Serial Interface (Serial Interface) refers to the sequential transmission of data bit by bit. Its characteristic is that the communication line is simple, and two-way communication can be realized as long as a pair of transmission lines (the telephone line can be used directly as the transmission line), which greatly reduces the cost. Especially suitable for long-distance communication, but the transmission speed is slow. The communication method in which the data of each bit of a message is transmitted bit by bit in sequence is called serial communication.

The characteristics of serial communication are: the transmission of data bits is carried out in bit sequence, at least one transmission line is required to complete; the cost is low but the transmission speed is slow. The distance of serial communication can range from several meters to several kilometers; according to the direction of information transmission, serial communication can be further divided into three types: simplex, half-duplex and full-duplex.

The two most basic ways of serial communication: synchronous serial communication and asynchronous serial communication.

Synchronous serial refers to the abbreviation of SPI (SerialPeripheral interface), as the name implies, it is the serial peripheral interface. The SPI bus system is a synchronous serial peripheral interface, which enables the MCU to communicate with various peripheral devices in a serial manner to exchange information. TRM450 is an SPI interface.

Asynchronous serial refers to UART (UniversalAsynchronous Receiver/Transmitter), Universal Asynchronous Receiver/Transmitter. UART is a chip whose parallel input becomes serial output, usually integrated on the motherboard. UART includes TTL level serial port and RS232 level serial port.

TTL level is 3.3V, while RS232 is negative logic level. It defines +5~+12V as low level and -12~-5V as high level. MDS2710, MDS SD4, EL805, etc. are RS232 interfaces. EL806 has a TTL interface.

The serial interface includes RS-232-C, RS-422, RS485, etc. according to electrical standards and protocols.

RS-232

Also called standard serial port, the most commonly used serial communication interface. It is a standard for serial communication formulated by the Electronic Industries Association (EIA) of the United States in conjunction with Bell Systems, modem manufacturers and computer terminal manufacturers in 1970.

Its full name is "Technical Standard for Serial Binary Data Exchange Interface Between Data Terminal Equipment (DTE) and Data Communication Equipment (DCE)". The traditional RS-232-C interface standard has 22 wires, using a standard 25-pin D-type plug socket (DB25), and later simplified to a 9-pin D-type socket (DB9), now 25-pin plug sockets are rarely used in applications .

RS-232 adopts unbalanced transmission mode, the so-called single-ended communication. Since the difference between the sending level and the receiving level is only about 2V to 3V, its common mode rejection capability is poor. Coupled with the distributed capacitance on the twisted pair, the maximum transmission distance is about 15 meters, and the maximum rate is 20kb /s. RS-232 is designed for point-to-point (that is, only a pair of receiving and sending equipment) communication, and its driver load is 3-7kΩ. So RS-232 is suitable for communication between local devices.

RS-422

The full name of the standard is "Electrical Characteristics of Balanced Voltage Digital Interface Circuit", which defines the characteristics of the interface circuit. The typical RS-422 is a four-wire interface. There is actually a signal ground wire, a total of 5 wires. Its DB9 connector pin definition. Because the receiver adopts high input impedance and the transmission driver has stronger driving ability than RS232, it is allowed to connect multiple receiving nodes on the same transmission line, up to 10 nodes can be connected.

That is, a master device (Master), and the rest are slave devices (Slave). The slave devices cannot communicate, so RS-422 supports point-to-many two-way communication. The receiver input impedance is 4k, so the maximum load capacity of the transmitter is 10×4k+100Ω (terminating resistance).

The RS-422 four-wire interface adopts separate sending and receiving channels, so there is no need to control the data direction. Any necessary signal exchange between the devices can be done in software (XON/XOFF handshake) or hardware (a pair of separate double Stranded wire) to achieve.

The maximum transmission distance of RS-422 is 1219 meters, and the maximum transmission rate is 10Mb/s. The length of the balanced twisted pair is inversely proportional to the transmission rate, and the maximum transmission distance is only possible when the rate is below 100kb/s. Only in a short distance can the highest rate of transmission be obtained. Generally, the maximum transmission rate that can be obtained on a 100-meter-long twisted pair cable is only 1Mb/s.

RS-485

It is developed on the basis of RS-422, so many electrical regulations of RS-485 are similar to RS-422. For example, balanced transmission methods are used, and terminating resistors need to be connected to the transmission line. RS-485 can adopt two-wire and four-wire methods. The two-wire system can realize true multi-point two-way communication. When four-wire connection is adopted, it can only realize point-to-many communication like RS-422, that is, there can only be one master ( Master) device, the rest are slave devices, but it is an improvement over RS-422, no matter the four-wire or two-wire connection mode, 32 devices can be connected to the bus.

The difference between RS-485 and RS-422 is that its common-mode output voltage is different. RS-485 is between -7V and +12V, while RS-422 is between -7V and +7V. RS-485 receiver The minimum input impedance is 12kΩ and RS-422 is 4kΩ; because RS-485 meets all RS-422 specifications, RS-485 drivers can be used in RS-422 networks.

RS-485 is the same as RS-422, its maximum transmission distance is about 1219 meters, and the maximum transmission rate is 10Mb/s. The length of the balanced twisted pair is inversely proportional to the transmission rate, and the longest cable length may be used when the rate is below 100kb/s. Only in a short distance can the highest rate of transmission be obtained. Generally, the maximum transmission rate of a 100-meter-long twisted pair is only 1Mb/s.

The RS-232 serial communication protocol used by the author. The following is a brief description of its communication wiring method. At present, the more commonly used serial ports are 9-pin serial (DB9) and 25-pin serial (DB25). When the communication distance is short (<12m), you can directly connect the standard RS232 port (RS422, RS485) with a cable. Remote, need to attach a modem (MODEM) or other related equipment. The simplest and most commonly used method is the three-wire connection, that is, the ground, receiving data and sending data are connected by three pins. This is the most basic connection, and it is connected directly by RS232.

The above is for the standard serial port of the microcomputer. There are many non-standard devices, so I won’t explain it.

All right. So far we have solved the three initial problems. Let's get into the actual code. The actual hardware is used for analysis.

On a hardware platform. The hardware is available. We must burn the appropriate software to the RAM of the platform. So that the CPU can jump to the first instruction. Then slowly load various resources. In order to complete the bootstrapping of the system.

Generally, we use BootLoader to initialize the hardware. And boot to the operating system core.

The BootLoader used by the author is u-Boot-1.1.16. Uboot is a well-known open source software. The reader only needs to understand that it plays the role of BootLoader. Not much explanation here. Only a brief description of serial port connection and program download:

Linux

Download u-boot.bin in the UBOOT directory to the development platform. Open the Device Manager in Windows. Select the port. To find the correct com slogan. Before that, make sure that the serial port of the development board is connected to the USB port of the notebook. (Because there are no parallel ports in notebooks now. So you can only use USB to serial cable. Use the level conversion chip on the development board to complete the serial connection.)

Linux

Then we use another tool. Namely SecureCRT. Find the corresponding com number. Complete the quick link. The baud rate is 115200. Cancel flow control.

If everything goes well. You can see the output of the serial port similar to the following on the laptop. This is the legendary serial console.

Linux

The command function of this serial port is completed by Uboot itself. It is not a serial port driver under linux.

The purpose of introducing this picture is to make readers perceptually realize what the function of the serial console is.

Now start to open the serial port. send. Analysis of the receiver function. Here is a forward reference to a function. It is the serial port sending function s3c24xx_serial_start_tx common to several 2440 chips in the linux kernel. The function is declared as static voids3c24xx_serial_start_tx(struct uart_port *port): the function is defined in ./linux/driver/tty/serial/samsung.c.

All right. We start with this directory structure. Explain the approximate tty subsystem driver model.

First of all. The first linux is the root directory of the kernel code. as the picture shows.

Linux

So far. We are facing a problem. What is the linux kernel.

What is the Linux kernel?

Linux is an open source computer operating system kernel. It is a Unix-like operating system written in C language and conforming to the POSIX standard.

Linux was first developed by Finnish hacker Linus Torvalds to try to provide a free and free Unix-like operating system on Intel's x86 architecture. The project started in 1991. In the early days of the project, some Minix hackers provided assistance, and today countless programmers around the world are helping the project free of charge.

Linux is a monolithickernel system. "Kernel" refers to a system software that provides hardware abstraction layer, disk and file system control, and multitasking. A kernel is not a complete operating system.

A complete operating system based on the Linux kernel is called the Linux operating system, or GNU/Linux. The device driver has full access to the hardware. The device driver in Linux can be conveniently set in a modularized form, and can be directly loaded or unloaded during system operation.

The operating system is a low-level support software used to deal with hardware and provide a limited set of services for user programs. A computer system is a symbiosis of hardware and software, they are mutually dependent and indivisible. Computer hardware, including peripherals, processors, memory, hard disks, and other electronic devices, constitute the engine of the computer. But without software to operate and control it, it cannot work by itself.

The software that completes this control is called the operating system, which is called the "kernel" in Linux terminology, and can also be called the "core". The main modules (or components) of the Linux kernel are divided into the following parts: storage management, CPU and process management, file system, device management and driver, network communication, and system initialization (boot), system calls, etc.

System call interface

The SCI layer provides some mechanisms to execute function calls from user space to the kernel. As discussed earlier, this interface depends on the architecture, even within the same processor family. SCI is actually a very useful function call multiplexing and demultiplexing service. You can find the implementation of SCI in ./linux/kernel and the architecture-dependent parts in ./linux/arch.

Process management

The focus of process management is the execution of the process. In the kernel, these processes are called threads, which represent individual processor virtualization (thread code, data, stack, and CPU registers). In user space, the term process is usually used, but the Linux implementation does not distinguish between these two concepts (process and thread).

The kernel provides an application programming interface (API) through SCI to create a new process (fork, exec or Portable Operating System Interface [POSⅨ] function), stop the process (kill, exit), and communicate and synchronize between them (Signal or POSⅨ mechanism).

Process management also includes handling the demand for sharing CPU between active processes. The kernel implements a new type of scheduling algorithm, which can operate in a fixed time no matter how many threads are competing for the CPU. This algorithm is called O⑴ scheduler, this name means that the time it uses to schedule multiple threads is the same as the time used to schedule one thread.

O⑴ The scheduler can also support multi-processors (called symmetric multi-processors or SMP). You can find the source code for process management in ./linux/kernel and the source code that depends on the architecture in ./linux/arch.

Memory management

Another important resource managed by the kernel is memory. In order to improve efficiency, if virtual memory is managed hard, the memory is managed in the so-called memory page mode (4KB for most architectures). Linux includes ways to manage available memory, as well as the hardware mechanisms used by physical and virtual mapping.

However, memory management needs to manage more than 4KB buffers. Linux provides an abstraction to the 4KB buffer, such as the slab allocator. This memory management mode uses a 4KB buffer as the base, and then allocates structures from it, and tracks memory page usage, such as which memory pages are full, which pages are not fully used, and which pages are empty. This allows the mode to dynamically adjust memory usage based on system needs.

In order to support the use of memory by multiple users, sometimes the available memory is consumed. For this reason, pages can be moved out of memory and placed on disk. This process is called swapping, because pages are swapped from memory to hard disk. The source code for memory management can be found in ./linux/mm.

Virtual file system

The virtual file system (VFS) is a very useful aspect of the Linux kernel because it provides a common interface abstraction for the file system. VFS provides an exchange layer between the SCI and the file system supported by the kernel.

VFS provides an exchange layer between the user and the file system

On VFS, it is a general API abstraction for functions such as open, close, read, and write. Below the VFS is the abstraction of the file system, which defines the implementation of upper-level functions. They are plugins for a given file system (more than 50). The source code of the file system can be found in ./linux/fs.

Below the file system layer is the buffer cache, which provides a set of general functions for the file system layer (independent of the specific file system). This caching layer optimizes access to physical devices by keeping the data for a period of time (or then reading the data in advance so that it is available when needed). Below the buffer cache is the device driver, which implements the interface of a specific physical device.

All right. I believe that readers have an overview of linuxkernel. Let's continue to analyze the model structure behind this path. (./Linux/driver/tty/serial/samsung.c)

driver is the directory of the driver. as the picture shows:

linux

The previous article has a general description of the linux device driver. Let's take a look at the driver under Linux in detail.

Looking at the linux/drivers directory, there are probably more than 35 subdirectories. Each subdirectory basically represents a device driver, including atm, block, char, misc, input, net, usb, sound, video, etc. Here only describe the three most widely used devices in embedded systems.

1. Char device

The character device is the simplest device in Linux and can be accessed like a file. When initializing a character device, its device driver registers with Linux and adds a device_struct data structure entry in the character device vector table. The main device identifier of this device is used as the index of this vector table.

The main device identifier of a device is fixed. Each entry in the chrdevs vector table, a device_struct data structure, includes two elements: a pointer to register the name of the device driver and a pointer to a set of file operations. The code you can refer to is include/linux/ major.h.

Generally speaking, devices such as mice, serial ports, and keyboards are all character devices.

2. Block device

The block device is the material basis of the file system, and it can also be accessed like a file. Linux uses the blkdevs vector table to maintain the registered block device files. It is like the chrdevs vector table, using the major device number of the device as an index. Its entry is also the device_struct data structure. Unlike character devices, block devices are divided into SCSI and IDE types.

Register with the Linux kernel and provide file operations to the kernel. A device driver of a block device class provides class-related interfaces to this class. The reference code is fs/devices.c.

Each block device driver must provide a common file operation interface and an interface to the buffer cache. Each block device driver fills the blk_dev_struct data structure in the blk_dev vector table. The index of this vector table is the major number of the device. The blk_dev_struct data structure includes the address of a request routine and a pointer, pointing to a list of request data structures, each of which expresses a request for the buffer cache to read/write a piece of data to the device.

The source code you can refer to is drivers/block/ll_rw_blk.c and include/linux/blkdev.h.

When the buffer cache reads/writes a piece of data from a registered device, or wants to read or write a piece of data to other locations, it adds a request data structure to blk_dev_struct. Each request data structure has a pointer to one or more buffer_head data structures, each of which is a request to read/write a piece of data.

If the buffer_head data structure is locked (buffer_cache), there may be a process waiting for the blocking process of this buffer to complete. Each request data structure is allocated from the all_request table. If the request is added to the empty request list, the driver's request function is called to process the request queue, otherwise the driver simply processes each request in the request queue.

The main difference between a block device driver and a character device driver is: when a read or write request is issued to a character device, the actual hardware I/O usually happens immediately, but the block device is not. It uses a block of system memory as a buffer Area, when the user process can meet the user's requirements for the device request, it will return the requested data, if not, call the request function to perform the actual I/O operation. Block devices are mainly for slow devices such as disks, so as not to consume too much CPU time to wait.

Block devices mainly include hard disks, optical drives, etc. You can check the file /proc/devices.

3. Network device (net device)

The role of a network device in the system is similar to a mounted block device. Block devices register themselves to blk_dev data and other kernel structures, and then use their request function to transmit and receive data blocks when a request occurs. Similarly, network devices must also register themselves in a specific data structure in order to exchange data packets with the outside world Is called when. Network equipment is handled specially in Linux. The Linux network system is mainly based on the Socket mechanism of BSD UNIX. A special data structure (sk_buff) is defined for data transfer between the system and the driver. The system supports buffering of sent data and received data, provides a flow control mechanism, and provides support for multiple protocols.

4. Misc device

Miscellaneous devices are also a device driver that is more commonly used in embedded systems. The sub LCD chord chips introduced in Chapter 11 are all driven by misc device. There is a Miscdevice.h file in the include\linux directory of the Linux kernel, and the misc device defined by yourself should be defined here. In fact, because these character devices do not meet the pre-determined character device category, all these devices use the major number 10, and they are all classified as misc devices. In fact, misc_register calls register_chrdev() with the major number 10.

This is the category under the driver directory. The serial port driver we mainly investigated. Belongs to the TTY subsystem. So we cd to the tty directory. ls displays the files inside. as the picture shows:

linux

The following is a brief description of the Linux kernel tty device.

The word tty is derived from Teletypes, or Teletypewriters. It is the earliest terminal device that appears similar to a teletypewriter and is produced by Teletype. Initially tty refers to the physical or virtual terminal connected to the Unix system. The terminal is a character type device, and tty is usually used to collectively refer to various types of terminal devices. Over time, when a terminal connection can be established through the serial port, the name is also used to refer to any serial device.

It also has many types, such as serial ports (ttySn, ttySACn, ttyOn), USB to serial converters (ttyUSBn), and modems that require special processing to work normally (such as traditional WinModem devices). The tty virtual device supports a virtual console, which can log in to the computer through a keyboard and network connection or through an xterm session.

In fact, at first, neither the terminal nor the console was a concept of a personal computer, but a concept on a small, medium-sized, large-scale computer shared by multiple people. The terminal provides a man-machine interface for the host, and everyone uses the host's resources through the terminal. There are two types of terminals: character terminals and graphic terminals. One host can connect to many terminals. The console is a special man-machine interface, which is the first man-machine interface of the human control host.

The host trusts the console higher than other terminals. This can also be combined with the init process in the kernel startup code to open /dev/console and execute sys_dup (0) twice, as well as standard input, standard output, standard error, and the copy of the standard input and output after the process fork. understanding. The personal computer only has a console and no terminal. Of course, if you like, you can connect one or two character dumb terminals to the serial port.

However, Linux uses the personal computer as a minicomputer according to the POSIX standard. On the console, a six-character dumb terminal (or virtual console terminal tty1-tty6) is virtualized through the getty software (the number can be adjusted in /etc/inittab. ) And a graphic terminal. In the virtual graphic terminal, you can use software (such as rxvt) to virtualize unlimited multiple pseudo terminals (pts/0, etc.).

But this is all virtual. Although it is used the same, there is no physical entity. Therefore, on a personal computer, there is only an actual console and no terminal. All terminals are simulated by software on the console. If you want to use a personal computer as a host, you can connect a real physical terminal through a serial port or a network card. On the cost, hehe. Who would do it.

 

 

 

 

 

 

 

 

  • Why does NXP have broad prospects in the automotive industry?
  • The development stage of embedded microprocessor

Hot Products

  • TMS320DM6467TZUTD1

    Manufacturer: Texas Instruments

    IC DIGITAL MEDIA SOC 529FCBGA

    Product Categories: SOC

    Lifecycle:

    RoHS:

  • TMS320DM648ZUTA6

    Manufacturer: Texas Instruments

    IC DGTL MEDIA PROC 529FCBGA

    Product Categories: DSP

    Lifecycle:

    RoHS:

  • TMS320VC5441ZGUR

    Manufacturer: Texas Instruments

    IC DSP FIXED POINT 169BGA

    Product Categories: DSP

    Lifecycle:

    RoHS:

Customer Comments

  • Looking forward to your comment

  • Comment

    Verification Code * 

Compare products

Compare Empty