The hard core knowledge that programmers need to know about the control hardware

e104655f9c63b18a3751574908bdd589.png

The relationship between application and hardware

As programmers, we rarely directly control the hardware. We generally use programs written in high-level languages ​​such as C and Java to indirectly control the hardware. Therefore, people rarely have direct access to hardware instructions, and hardware control is Windows 操作系统solely responsible.

You must have guessed what I am going to say, yes, I will say it, but nothing is absolute, and the difference in the environment will cause deviations in the results. Although the programmer cannot directly control the hardware, and Windows shields the details of controlling the hardware, Windows opens up 系统调用functions to control the hardware. In Windows, system calls are called API, APIs are functions called by applications, and the entities of these functions are stored in DLLfiles .

f27dd8902149d78e5d32e0f4182c5763.png

Let's take a look at an example of indirectly controlling hardware through system calls

If you want to display a string in a window, you can use the TextOutfunction . The syntax of the TextOut function (in C language) is as follows

BOOL TextOut{
   HDC hdc,					// 设备描述表的句柄
  int nXStart,					// 显示字符串的 x 坐标
  int nYStart,				        // 显示字符串的 y 坐标
   LPCTSTR lpString,			// 指向字符串的指针
  int cbString					// 字符串的文字数
}

So what does Windows do when processing the contents of the TextOut function? From the results, Windows directly controls the display as hardware. But Windows itself is also software, so it can be seen that Windows should pass some kind of instruction to the CPU, thereby controlling the hardware through software.

The TextOut function API provided by Windows can output characters to the window and the printer. The printf function provided by the C language is a function used to display strings in the command prompt. It is not possible to output characters to the printer using the printf function.

Supports IN and OUT commands for hardware input and output

Windows controls hardware by means of input and output instructions. The two representative input and output instructions are the INand OUTinstructions. These instructions are also assembly language mnemonics.

The reading and output of data can be realized through IN and OUT instructions, as shown in the following figure

40628fe6db2a0f98db19cffcdf6282f9.png

That is to say, the IN instruction inputs data through the specified port number, and the OUT instruction outputs the data stored in the CPU register to the port with the specified port number.

So what are端口号 this and ? 端口Does it feel like a port to you? By marking which port is the cargo then shipped and shipped out?

Let's take a look at how the official defines the port number and port

Remember the five components of a computer in the principle of computer composition, let's review it again: arithmetic unit, controller, memory, input device and output device . Today, instead of talking about the first three, we will talk about the last two input devices and output devices, which are closely related to our topic in this section.

So the question is, how do IO devices implement input and output? The computer mainframe is equipped with peripheral devices such as monitors and keyboards 连接器. The inside of the connector is connected with an IC used to exchange the current characteristics between the computer host and the peripheral equipment. If you don't understand what IC is, you can refer to the author's article The memory of hard core knowledge that programmers need to know. These ICs are collectively referred to as IO 控制器.

IO is short for Input/Output. Peripherals such as monitors and keyboards have their own dedicated I/O controllers. The I/O controller has memory for temporarily storing input and output data. This memory is 端口(port). You can understand it as the port we mentioned above. The memory inside the IO controller, also known as 寄存器, don't panic, this register is not the same as the register in the memory. The registers of CPU memory are used for data operation processing, while the registers in IO are used to temporarily store data.

In an IC inside an I/O device, there are multiple ports. Since there are many peripheral devices connected to a computer, there are also many I/O controllers. Of course there will be multiple ports, and an I/O controller can control multiple devices, not just one. Different ports 端口号are .

The port number is also called I/O地址. The IN instruction and the OUT instruction perform data input and output between the port specified by the port number and the CPU. This is the same as reading and writing memory through memory addresses.

1236b00bb6f04217964c855eec7af024.png

Test input and output programs

First let's use the IN and OUT instructions to conduct an experiment that directly controls the hardware. Suppose the purpose of the test is to make a computer built-in horn (buzzer) sound. The buzzer is encapsulated inside the computer, but it is also a type of peripheral.

It is more complicated to use assembly language, this time we use C language to implement. In most C language processing (types of compilers), mnemonics can be described in them as long as they are _asm{ 和 }enclosed in brackets. That is, in this way, it is possible to use a mix of C language and assembly language source code.

In an AT compatible machine, the default port number of the buzzer is 61H, and the H at the end means a hexadecimal number. Use the IN command to input data through the port number, set the lower 2 bits of the data to ON, and then use the OUT command to output the data through the port number, then the buzzer will sound. In the same way, after setting the lower 2 bits of the data to OFF and outputting, the buzzer stops working.

Setting a bit to ON means setting the bit to 1, and setting a bit to OFF means setting the bit to 0. To set a bit to ON, you only need to set the bit you want to be ON to 1, and set the other bits to 0 and then perform an OR operation. Since the lower 2 bits need to be set to 1, the OR operation is performed with 03H. 03H is 00000011 when represented by 8 in binary. Because even the upper 6 bits have specific meanings. The OR operation with 0 will not change, so the OR operation is performed with 03H. To set a bit to OFF, you only need to set the bit you want to be OFF to 0, and set the other bits to 1 and then perform an AND operation. Since the lower 2 bits need to be set to 0 here, it is necessary to perform AND operation with FCH. In the source code, FCH is described by 0FCH. Adding 0 in front of it is the regulation of assembly language, which means that the hexadecimal numbers starting with these characters A - F are numerical values. 0FCH is 11111100 if it is represented by an 8-bit binary number. Even if the upper 6 bits have specific meanings, there will be no change after AND operation with 1, so OR operation is performed with 0FCH.

void main(){
  
  // 计数器
  int i;
  
  // 蜂鸣器发声
  _asm{
    IN  EAX, 61H
    OR	EAX, 03H
    OUT	61H, EAX
  }
  
  // 等待一段时间
  for(i = 0;i < 1000000;i++);
  
  // 蜂鸣器停止发生
  _asm{
    IN  EAX, 61H
    AND EAX, 0FCH
    OUT 61H, EAX
  }
}

We explain the above code, main is the function of the starting position of the C language program. In the function, there are two sections _asm{}enclosed by and between them an empty loop using a for loop

The first part is the sounding part of the buzzer. The data of port 61H is stored in the EAX register of the CPU through the IN EAX, 61H (mnemonic insensitive) instruction. Next, set the lower 2 bits of the EAX register to ON by the OR EAX, 03H instruction. Finally, through the OUT 61H, EAX instruction, the contents of the EAX register are output to port 61. Make the buzzer sound. Although the length of the EAX register is 32 bits, since the buzzer port is 8 bits, it only needs to perform OR operation and AND operation on the lower 8 bits to work normally.

This is followed by an empty loop that repeats 100 times, mostly to add a little bit of time between when the buzzer starts and stops. Because today's computing machines run so fast, even 1 million cycles are almost instantaneous.

Then there is the part that controls the buzzer to stop sounding. First, store the data of port 61H into the EAX register of the CPU through the IN EAX, 61H instruction. Next, set the lower 2 bits of the EAX register to OFF by the AND EAX, 0FCH instruction. Finally, through the OUT 61H, EAX instruction, the EAX content of the register is output to port 61, so that the buzzer stops sounding.

Interrupt requests from peripheral devices

IRQ(Interrupt Request)Represents an interrupt request. IRQ is used to suspend the currently running program and jump to the necessary mechanism for other programs to run. The mechanism is called 处理中断. Interrupt handling plays an important role in hardware control. Because if there is no interrupt processing, there may be cases where processing cannot be performed smoothly.

The processing of the interrupted program (main program) is stopped from the start of interrupt processing until the execution of the program (interrupt handler) requesting the interrupt is completed. This situation is similar to a phone call in the process of processing the document, and the phone call is equivalent to interrupting the processing. If no interrupt processing occurs, you must wait until the document processing is complete before you can answer the call. It can be seen that interrupt processing has great value, just like returning to the original document job after answering the phone, after the interrupt program is processed, it will return to the main program to continue.

aec18dab165ecfe4decdcda05397ba48.png

It is the I/O controller connected to the peripheral device that implements the interrupt request, and the CPU is responsible for implementing the interrupt processing. The interrupt request of the peripheral device will use a different number from the I/O port, which is called 中断编号. When viewing the properties of the floppy disk drive in the control panel, the actual value at the IRQ is 06, which means that 06 is used to identify the request issued by the floppy disk drive. Then there is the operating system and the interrupt handler that BIOSwill provide the response interrupt number.

BIOS (Basic Input Output System): Located in the built-in ROM on the computer motherboard or expansion card, it records the programs and data used to control peripheral devices.

If there are multiple peripheral devices for interrupt requests, the CPU needs to make a choice for processing. To this end, we can add a named 中断控制器IC between the I/O controller and the CPU for buffering. The interrupt controller transmits interrupt requests from multiple peripheral devices to the CPU in an orderly manner. The function of the interrupt controller is equivalent to buffering. Below is a schematic diagram of the interrupt controller function

07efac0785d685357e740fd4c942e594.png

After the CPU receives the interrupt request, it will interrupt the currently running task and switch to the interrupt handler. The first step of the interrupt handler is to save the values ​​of all CPU registers to the memory stack. After completing the input and output of peripheral devices in the interrupt handler, restore the value stored in the stack to the CPU register, and then continue processing the main program.

If the CPU register value has not been restored, it will affect the operation of the main program, and may even cause the program to stop unexpectedly or run-time exceptions occur. This is because the main program will use the CPU registers for processing during the running process. If the running results of other programs are suddenly inserted at this time, the CPU will inevitably be affected. Therefore, after processing the interrupt request, the value of each register must be restored. As long as the value of the register remains the same, the main program can continue processing as if nothing had happened.

e6769c3d0ccae4fb3f97c5e067c7c52e.png

Real-time processing with interrupts

Interruption refers to the process of computer operation, when some unexpected situations require the intervention of the host computer, the machine can automatically stop the running program and transfer to the program that handles the new situation, and returns to the original suspended program after the processing is completed.

During the running process of the program, interruption occurs almost all the time. The reason is to process the external input data in real time. Although the program can also process the external data without interruption, in that case, the main program will frequently The check if the peripheral device will have data input. Since there will be many peripheral devices, it is necessary to investigate in order. Checking the status of multiple peripherals in sequence is called 轮询. For computers, this polling method is not very reasonable. If you are checking whether there is mouse input, what should you do if keyboard input occurs? The result is bound to lead to real-time processing efficiency of text. Therefore, immediate interruption can improve the running efficiency of the program.

The above is just one benefit of interruption, the following summarizes the positive effects that interruption can bring

  • Improve computer system efficiency. The operating speed of the processor in a computer system is much higher than that of the peripheral devices. Interruptions can coordinate work between them. When the peripheral device needs to exchange information with the processor, the peripheral device sends an interrupt request to the processor, and the processor responds in time and handles accordingly. When not exchanging information, the processor and peripheral devices are in independent parallel working state.

  • Maintain the reliable and normal operation of the system. In modern computers, programmers cannot directly intervene and manipulate the machine, but must issue a request to the operating system through the interrupt system, and the operating system can achieve human intervention. There are often multiple programs and their own storage space in main memory. In the process of program running, if there is out-of-bounds access, it may cause program confusion or mutual destruction of information. In order to avoid the occurrence of such events, the storage management component monitors, and once an out-of-bounds access occurs, an interrupt request is sent to the processor, and the processor immediately takes protective measures.

  • Meet real-time processing requirements. In a real-time system, various monitoring and control devices randomly send interrupt requests to the processor, and the processor responds and processes at any time.

  • Provide on-site troubleshooting methods. There are various components for fault detection and error diagnosis in the processor. Once a fault or error is found, an interrupt request is immediately issued to record and isolate the fault on-site, so as to provide the necessary basis for further processing.

Use DMA to realize large data transfer in a short time

Above we have introduced the relationship between I/O processing and interrupt, let's introduce another mechanism, this mechanism is DMA(Direct Memory Access). DMA refers to data transfer between peripheral devices and main memory directly without going through the CPU. Hardware devices such as disks use the DMA mechanism. Through DMA, a large amount of data can be transferred in a short time. The reason why it is so fast is because the time of the CPU as an intermediary is saved. The following is the transfer process of DMA

bd5c83f36f1e07e2511fd2fd02b50e39.png

I/O port number, IRQ, DMA channel can be said to be a 3-point combination to identify peripheral devices. However, IRQ and DMA channels are not available for all peripheral devices. The minimum information required by the host computer to control the hardware through software is the I/O port number of the peripheral device. IRQs are only necessary for peripherals that require interrupt handling, and DMA channels are only necessary for peripherals that require DMA mechanisms. If multiple peripheral devices are set to the same port number, IRQ and DMA channel, the computer will not work properly and will prompt 设备冲突.

Display mechanism for text and pictures

Do you know how text and pictures are displayed? In fact, if I could briefly summarize the mechanism in one sentence, it would be that the information displayed on the display is always stored in some memory. This memory is called VRAM(Video RAM). In the program, as long as data is written to VRAM, the data will be displayed on the display. The program to realize this function is provided by the operating system or BIOS, and is processed by means of interrupts.

In the MS-DOSera , for most computers, VRAM was part of the main memory. In modern computers, 显卡VRAM and GPU (Graphics Processing Unit), also known as graphics processors or graphics chips, are generally equipped with VRAM and GPU (Graphics Processing Unit) independent of the main memory. This is because hundreds of megabytes of VRAM are necessary for Windows, which often draw graphics.

fea71ccdc35cf82c2777e1054cc020c8.png

Using software to control hardware sounds difficult, but in fact it is just using input and output commands to input and output with peripheral devices. Interrupt handling is a functional option to be used as needed. DMA can be directly handed over to the corresponding peripheral device.

Although new technologies in the computer field are constantly emerging, what the computer can handle is always to perform operations on the input data and output the results, which will never change.

Article reference:

"How the Program Works"

https://baike.baidu.com/item/interrupt-controller/15732992?fr=aladdin

https://baike.baidu.com/item/break/3933007#viewPageContent

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324066585&siteId=291194637