The relationship between applications and hardware

As programmers, we rarely control the hardware directly. We usually control the hardware indirectly by writing programs in C, Java and other high-level languages. So we rarely direct contact with the hardware instructions, hardware control is solely responsible for the Windows operating system.

You must have guessed what I was going to say, yes, I will but there is no absoluteness in anything, and circumstances can skew the results. Although programmers have no direct control over the hardware, and Windows hides the details of controlling the hardware, Windows does open up system calls for you to control the hardware. In Windows, system calls are called apis, and apis are the functions called by applications. The entities of these functions are stored in DLL files.

Let’s look at an example of indirect hardware control through system calls

To display a string in a window, you can use the TextOut function in the Windows API. The syntax of the TextOut function (in C) is as follows

BOOL TextOut{
  HDC hdc,							// Handle to device description table
  int nXStart,					                // Displays the x coordinate of the string
  int nYStart,					                // Displays the y coordinate of the string
  LPCTSTR lpString,			                // A pointer to a string
  int cbString					                // The number of characters in the string
}
Copy the code

So what does Windows do with the contents of the TextOut function? As a result, Windows directly controls the display as hardware. But Windows itself is software, so Windows should be passing some instructions to the CPU to control the hardware through software.

Windows provides the TextOut function API to output characters to Windows and printers. C provides the printf function, which is used to display a string in a command prompt. You cannot print characters to the printer using the printf function.

Support hardware input and output IN instruction and OUT instruction

Windows control hardware relies on input and output instructions. Two representative input-output instructions are IN and OUT instructions. These instructions are also mnemonics of assembly language.

Data can be read and output using IN and OUT instructions, as shown IN the figure below

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

So what is this port number and port? Does it feel like a harbor to you? Which port is marked and then the goods are shipped and shipped out?

How do you define port numbers and ports

Remember the five components of a computer from the principle of computer composition? Let’s review them again: arithmetic unit, controller, memory, input device and output device. Instead of talking about the first three, let’s talk about the next two input and output devices, which are relevant to the topic of this section.

So how do IO devices implement input and output? In a mainframe computer, connectors are attached for connecting peripherals such as monitors and keyboards. And inside the connector, are connected to the IC used to exchange the current characteristics between the computer host and peripheral devices. If you don’t know what IC is, check out the author’s article on core knowledge programmers need to know. These ics are collectively referred to as IO controllers.

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 called a port. Port you can think of it as the port we said above. IO controller internal memory, also known as registers, do not panic, this register is not the same as the register in memory. Registers in CPU memory are used for data processing, while registers in IO are used for temporary storage of data.

In an IC inside an I/O device, there are multiple ports. Because there are so many peripherals connected to a computer, there are so many I/O controllers. Of course, there will be multiple ports, and one I/O controller can control multiple devices, not just one. Ports are distinguished by port numbers.

Port numbers are also known as I/O addresses. The IN and OUT instructions input and output data between the specified port number and the CPU. This is the same thing as reading or writing to memory by its address.

Test the input and output programs

First, let’s use IN instruction and OUT instruction to conduct a direct control hardware experiment. Suppose the purpose of the experiment is to make a sound from a computer built – in speaker (buzzer). The buzzer is enclosed inside the computer, but it is also a peripheral device.

Assembly language is more cumbersome, this time we use C language to achieve. In most C language processes (compiler types), you can write mnemonics in them by simply enclosing _asm{and}. In other words, this way you can use a mixture of C and assembly language source code.

In AT compatibles, the default buzzer port number is 61H, and the H AT the end indicates a hexadecimal number. Input data through the port number with the IN command, and set the lower two bits of the data to ON, and then output data through the port number with the OUT command, then the buzzer will sound. In the same way, the buzzer stops working when the lower two bits of data are set to OFF and output.

Bit setting to ON means setting the bit to 1, bit setting to OFF means setting the bit to 0. To set the bit to ON, simply set the bit you want to set to ON to 1 and the other bits to 0 to perform the OR operation. Since we need to set the lower 2 position to 1, we will perform OR operation with 03H. 03H in binary 8 is 00000011. Because even the high six has a specific meaning. And 0 will not change after OR operation, so the OR operation with 03H. To set the bit to OFF, simply set the bit you want to set to OFF to 0 AND the other bits to 1. Since we need to set the lower 2 bits to 0, we need to do AND with FCH. In the source code, FCH is described as 0FCH. The prefix 0 is an assembly language rule that indicates that hexadecimal numbers starting with characters a-f are numeric values. 0FCH in 8-bit binary form is 11111100. Even if the higher 6 bits have specific meaning, there will be no change after the operation of AND with 1, so it is the same as 0FCH to carry out OR operation.

void main(a){
  
  / / counter
  int i;
  
  // The buzzer sounds
  _asm{
    IN  EAX, 61H
    OR	EAX, 03H
    OUT	61H, EAX
  }
  
  // Wait a while
  for(i = 0; i <1000000; i++);// The buzzer stops happening
  _asm{
    IN  EAX, 61H
    AND EAX, 0FCH
    OUT 61H, EAX
  }
}
Copy the code

To illustrate the above code, main is a function of the starting position of a C program. In this function, there are two parts surrounded by _asm{}, and one of them uses an empty loop for the loop

First is the part of the buzzer sound, through IN EAX, 61H(mnemonic is case insensitive) instruction, the data of port 61H is stored IN the CPU’S EAX register. Next, the lower two bits of the EAX register are set to ON by the OR EAX, 03H instruction. Finally, through OUT 61H, EAX instruction, output the contents of EAX register to port 61. Start the buzzer. The length of the EAX register is 32 bits, but since the buzzer port is 8 bits, only the NEXT 8 bits of OR AND AND will work.

This is followed by an empty loop that repeats 100 times, mainly to add a little time between the buzzer’s start and stop. Because computing machines now run so fast that even a million cycles can be completed almost instantaneously.

Then there’s the part that controls the buzzer to stop the sound. First, through IN EAX, 61H instruction, the data of port 61H is stored IN the CPU’s EAX register. Next, set the lower two bits of the EAX register to OFF with the AND EAX, 0FCH instruction. Finally, through OUT 61H, EAX instruction, output the EAX content of the register to port 61, so that the buzzer stops articulation.

Interrupt request for peripheral device

IRQ(Interrupt Request) stands for Interrupt Request. IRQ is the mechanism necessary to suspend a currently running program and jump to another program. This mechanism is called handling interrupts. Interrupt handling plays an important role in hardware control. If there is no interrupt processing, processing may not be smooth.

Processing of the interrupted program (main program) stops from the beginning of the interrupt processing until the program requesting the interrupt (interrupt handler) finishes running. This situation is similar to a phone call in the middle of processing a document, which is equivalent to interrupting processing. If no interrupt processing occurs, you must wait until the document processing is complete before answering the call. Thus, interrupt processing is of great value. Just as the original document job is returned after the call is answered, the interrupt program is returned to the main program after processing.

The interrupt request is performed by the I/O controller connected to the peripheral device, and the CPU is responsible for the interrupt processing. The interrupt request of the peripheral device uses a different number than the I/O port, which is called the interrupt number. When viewing the properties of the floppy disk drive in the control panel, the actual value of IRQ is 06, indicating that the request made by the floppy disk drive is identified with 06. Also, the operating system and BIOS provide interrupt handlers that respond to interrupt numbers.

Basic Input Output System (BIOS): located in the BUILT-IN ROM on the computer mainboard or expansion card, the BIOS records the programs and data used to control peripheral devices.

If there are multiple peripherals for interrupt requests, the CPU needs to make a choice to process, so we can add an IC named interrupt controller between the I/O controller and the CPU to buffer. The interrupt controller passes interrupt requests from multiple peripherals to the CPU in an orderly fashion. The interrupt controller functions as a buffer. The following is a schematic of the interrupt controller function

After receiving the interrupt request, the CPU interrupts the current running task and switches to the interrupt handler. The first step of the interrupt handler is to store the values of all the CPU registers in the memory stack. After completing peripheral input and output in the interrupt handler, the values stored in the stack are restored to the CPU registers, and then processing of the main program continues.

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. This is because the main program in the process of running, will use the CPU register for processing, at this time if the sudden insertion of other programs running results, the CPU will be affected. Therefore, the value of each register must be restored after the interrupt request is processed. As long as the value of the register remains unchanged, the main program can continue processing as if nothing had happened.

Use interrupts for real-time processing

Interrupt refers to the process of computer operation, when some unexpected situation needs the host intervention, the machine can automatically stop the program that is running and turn into the program to deal with the new situation, and then return to the original suspended program to continue to run.

Interrupts occur almost all the time in the process of running the program. The reason for this is to process external input data in real time. Although the program can also process external data without interruption, the main program will frequently check the peripheral device for data input. Since there will be many peripherals, it is necessary to investigate them in order. Checking the state of multiple peripherals in order is called polling. For computers, this method of polling is not very reasonable. If you are checking for mouse input, what happens when keyboard input occurs? The result is bound to be real-time processing efficiency for text. So the immediate interruption can improve the efficiency of the program.

This is just one of the benefits of interrupts. Here are some of the positive effects of using interrupts

  • Improve the efficiency of computer systems. The speed of the processor in the computer system is much higher than that of the peripheral devices. Interrupts can coordinate their work. 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 deals with it accordingly. When no information is exchanged, the processor and peripherals work independently in parallel.
  • Maintain reliable and normal operation of the system. In modern computers, programmers can not directly intervene and manipulate the machine, must interrupt the system to the operating system issued a request, by the operating system to achieve human intervention. There are often multiple programs and separate storage Spaces in main memory. In the process of program running, such as the occurrence of out-of-bounds access, may cause program confusion or mutual destruction of information. In order to avoid the occurrence of this kind of event, the storage management unit monitors the access and sends interrupt request to the processor, and the processor immediately takes protection measures.
  • Meet the requirements of real-time processing. In a real-time system, various monitoring and control devices randomly send interrupt requests to the processor, which the processor responds to and processes at any time.
  • Provide onsite troubleshooting methods. The processor is equipped with a variety of fault detection and error diagnosis components, once the fault or error is found, immediately send out interrupt request, fault site record and isolation, to provide necessary basis for further processing.

Use DMA to transfer large amounts of data in a short time

Now that we have seen the relationship between I/O processing and interrupts, let’s look at another mechanism, Direct Memory Access (DMA). DMA refers to data transfer between peripheral devices and main memory without passing through the CPU. Hard disks and other hardware devices use DMA mechanism, through DMA, a large amount of data can be transferred in a short time, so fast because the CPU as the intermediary time is saved, the following is the DMA transfer process

I/O port number, IRQ, DMA channel is a three-point combination for identifying peripherals. However, IRQ, DMA channels are not available on all peripherals. The minimum amount of information a computer host needs to control hardware through software is the I/O port number of the peripheral device. IRQ is only required for peripherals that require interrupt processing, DMA channels are only required for peripherals that require DMA mechanisms. If multiple peripherals are configured with the same port number, IRQ, and DMA channels, the computer will not work properly, prompting device conflicts.

Text and picture display mechanism

Do you know how words and pictures appear? In fact, a simple summary of this mechanism would be that the information displayed on the display is always stored in some memory. This memory is called VRAM(Video RAM). In a program, whenever data is written to the VRAM, the data is displayed on the monitor. The program that implements this function is provided by the operating system or BIOS and is processed with interrupts.

In the days of MS-DOS, VRAM was part of the main memory for most computers. In modern computers, special hardware such as Graphics cards are generally configured with VRAM and Graphics Processing Unit (GPU) independent of the main memory, also known as Graphics processor or Graphics chip. This is because hundreds of megabytes of VRAM are necessary for Windows, which often draws graphics.

Using software to control hardware sounds difficult, but it’s really just input and output with peripheral devices. Interrupt handling is a functional option that can be used on demand. DMA is handed directly to the corresponding peripheral.

Although the new technology in the field of computer is constantly emerging, but all the computer can do is always to calculate the input data, and output the results, this point will never change.

Article Reference:

How programs Run

baike.baidu.com/item/ Interrupt controller /…

Baike.baidu.com/item/ interrupt / 393…

How does the program run