r/AskComputerScience • • Aug 02 '19

How does a computer receive and then process data from an input, and output data?

Say if I have a keyboard connected via USB to my PC, a key press will send the binary version of the ASCII character to the computer, an application and the operating system will incorporate it into a program - but how does it get sent to main memory, as instructions can only be executed from there - if there was no program, would it simply be sent to main memory and then be executed?

And secondly, how would a CPU output something i.e. a monitor? Are there specific instructions in it's instruction set to output to a specific connection?

30 Upvotes

12 comments sorted by

16

u/kedde1x Aug 02 '19

It happens via hardware interrupts. In short, when you press a key, an electronic alert signal is sent to the processor, called an interrupt, which then handles the keystroke.

6

u/not-just-yeti Aug 02 '19 edited Aug 02 '19

To add to this a bit:

A naive idea (that I used to have) is that the CPU runs (say) 10 instructions, and then it checks to see if there is a value on the keyboard-wire that needs taking care of. This would be called "polling the keyboard", but it's not what the main CPU actually does. Instead:

  • The CPU has an Instruction Pointer ("IP"), which is where the address of the instruction-to-execute-next.

  • As a program runs, the IP is typically incremented by 1 (and that's done by the hardware).

  • but sometimes the program wants to jump to a different part of the code, so current instruction is something like 0110 0001 where the 0110 indicates "change the IP" and 0001 is the new value of the IP (which will be padded with leading 0s).

  • Putting the above two together: the hardware that updates the IP is really: "If the current instruction starts with 0110, then the new value is the rest of the instruction; otherwise it is the current-instruction-plus-one." (We call a "multiplexor" -- a circuit which chooses one of several available inputs, depending on a switch/condition -- same circuit you'll find in your TV to choose which of its inputs to display (cable or xbox or dvd-player).)

  • Now for the keyboard / interrupt part: really there is another multiplexor on top of the above: "if the wires from the keyboard are all 0 then select the next-IP-value as above, BUT if any of the keyboard wires aren't all 0 then instead use (say) 1111 1100 as the next IP value" -- that's the memory-address where the keyboard-event-handler is. (Btw, the first thing(*) the code at that location will do is stash away the current instruction-pointer, so it knows where to resume the program when it's done handling the keypress!) So that's how the CPU can respond to a keypress, w/o having to spend lots of its time checking the keyboard explicitly.

  • I'm still simplifying -- the keyboard isn't something the chip-designer hardcodes these days; instead any I/O device can "raise an interrupt" (that is, apply voltage to a wire indicating it wants the CPU's attention), and include (on further wires) other bits which indicate which type of interrupt it is, as defined by the operating-system-manual. The IP is then set to the address of the appropriate "event handler" (as found in the "interrupt table", blah blah blah).

  • Btw, interrupts/events encompass more than you might thing of input -- things like the memory-cache has finished reading from main-memory, or a certain amount of time has passed.

(*) Okay it can't quite be true that the first thing an interrupt-handler does is stash the existing IP -- because by the time the interrupt handler is running the IP necessarily holds the handler's location, not the code-that-was-interrupted! So the interrupt-circuitry stashes the IP somewhere before updating the IP to the handler. This is the sort of thing the chip-designers think about.

DISCLAIMER: this is greatly simplified and technically wrong in places -- but I hope it gives a gist of how the CPU can actually do this, given just the notion of 'multiplex' and 'add 1'.


Output, btw, is easier. Consider drawing to the screen: from the program's perspective, your 800x600 screen is just 800*600 bytes in a row. But those memory addresses aren't hooked up to the wires to a memory-chip -- instead they're hooked up to the wires leading to the screen. [Again, lots of simplification here.]

And output to a disk or a printer is similar, except that it "streams" the data, moving it in chunks ("blocks"): the CPU writes just one block of the output to memory, and then goes on to other programs. The receiving-device will process (print) send an interrupt when it has finished reading that block and is ready to receive the next block.

3

u/claytonkb Aug 03 '19

There are a few mistakes in here but you have captured some essential details. Interrupts do not interact with the instruction pointer. Instead, there is an interrupt controller (on PCs, it was originally the Intel 8259 which could assert a pin on the CPU called #INT). The interrupt controller has a variety of interrupt request lines (IRQ's) that can be hard-wired to various hardware devices in the system. Generally, the motheboard's BIOS will know which IRQs are wired to which system devices, so it knows how to configure the interrupt controller's settings.

Nowadays, most of what I just said is not true. The legacy interrupt controller has been superseded by the APIC (also on-die). The APIC is much more flexible than the old 8259 and it is able to handle a larger number of interrupt lines. Its external-facing pins are exposed on the CPU's package and are available for direct use as CPU interrupts. PCI MSI messages offer additional advantages due to their greater flexibility/modularity.

Let's trace a physical interrupt. Let's say a board temperature sensor has tripped. It asserts an electrical line that is connected to a system chip that, in turn, asserts the #SMI (system management interrupt) line to the APIC. This is a physical line that has an actual pin on the CPU. When this line is asserted, the APIC circuitry in the CPU recognizes that the motherboard has signaled a system interrupt. The APIC places a message on the on-die bus (to which the CPU and memory controller and other on-die devices are all connected) that informs the on-chip devices that an SMI interrupt has been received. Typically, OS software will have already configured one CPU core (assuming there are more than one) to act as the SMI handler. This CPU's bus circuitry will see the SMI message and recognize that it must handle an SMI.

I'm skipping over a lot of book-keeping details but the CPU has some configured registers that tell it where in main memory is the entry-point to the SMI-handler. The CPU's internal core raises an interrupt signal to the CPU pipeline which causes the flow of execution on the current thread to cease (stop fetching) and some data is saved off by the CPU's microcode to allow it to resume the interrupted thread at its next instruction. The CPU then begins fetching code at the entry-point to the SMI-handler and these instructions begin issuing into the CPU's pipeline. This is the point at which the PC (or IP) has been altered. Now that the SMI-handler is running, it can perform whatever operations it needs to perform to figure out why it was invoked. It might issue some reads to the chipset registers or send read messages to a system I/O device to get status info. When it reads the status of the system, it will find that an error has been signaled due to a temperature sensor. The SMI handler might do nothing about this, or it might send a message to the OS or it might cause an immediate system halt (for example, in the case of a CATERR, or "catastrophic error"). If the SMI handler reaches an IRET instruction (for "Return From Interrupt"), this will cause the CPU pipeline to restore the information it stashed earlier regarding where to resume the interrupted thread.

A typical USB keyboard will be configured as part of the USB sub-system. This makes tracing the sequence of events that occurs from a key-press to the point where there is an actual change of execution-flow in the CPU pipeline very difficult to explain (read: I don't know all the details because the USB spec is a beast). Since the keyboard will be configured as a USB serial device, it has a serial communication channel to the USB controller in the system. I think the communication protocol used is more like packets than like interrupts. In any case, once the USB controller has received a keystroke message from the keyboard, it will notify the I/O controller (or the I/O controller already has a USB hub within it) which, in turn, has several ways to notify the CPU that there is an I/O interrupt available.

At some point, the CPU will receive the interrupt from its on-die interrupt-controller and it will initiate control-flow transfer to the appropriate address in main memory where the OS keystroke interrupt handler resides. Depending on your OS and the specific I/O sub-system that is currently handling the keyboard, this handler will put the keystroke in a pipe or some application memory area.

2

u/Bottled_Void Aug 02 '19

Just tagging on to this that the interrupt will be handled by a driver. The operating system usually takes care of all the needed drivers and the mapping of the interupt to the right bit of software.

2

u/Lofter1 Aug 02 '19

The CPU doesn't care for the output or output-method. It just sends and receives data from/to a controller, for example, an USB controller. This controller then converts the data so that it can send it, and the received data so that the CPU understands it. And with graphics output, the CPU usually doesn't do much, this is done by the GPU on your graphics-card. Sometimes a CPU has a GPU build into it (ie Intel Integrated Graphics). It sends instruction to the GPU to process something, the GPU sends it, just like the CPU, to a controller for a specific connection to convert it into the right signal (HDMI, DisplayPorrt, VGA,...).

And no, if there is no program for the CPU to execute, it wouldn't even receive anything, as you never told it to receive data. And the program doesn't get the keystrokes, either, this is all done by your OS which will then send the key to the program that awaits input right now. The keystroke will not magically just go into memory, and it will not execute a program through it, as it executes binary CPU instructions, not characters or strings. For example, the Assembler Instruction ADD could be compiled into 0bx01000010. The CPU doesn't understand "ADD", 0bx01000010 the CPU understands and knows "I need to perform an addition now".

1

u/smm_h Aug 02 '19

how would a CPU output something i.e. a monitor?

This is done by specific library calls such as OpenGL by the OS, passed onto the appropriate accelerator e.g. GPU and written unto a graphics buffer. Displaying that buffer is also done by the OS and your device drivers.

I understand your general confusion. Most gigantic tasks in computer science, such as the entire infrastructure of the internet, how operating systems work, how a gaming console works, how a 3D computer aided design application works, etc., they all follow the layered structure.

Layers are pieces of software that are built on top of each other and cooperate with each other. Each layer offers services to its upper layers and uses services provided by layers below it.

This may seem unclear so I will use an analogy. You're using the layered structure everyday without knowing it. For example, when you order a pizza, you use a service provided by the pizza place. They on the other hand, use services provided by a butcher (meat) and a farmer (flour, tomatoes).

Now you, don't ever have to directly deal with the butcher and farmer. Not that you can't, you just don't have to. They themselves use services provided by others and you yourself provide some services to others. Maybe your friend asked you to order the pizza, that means they're using a service you're providing.

Same goes with computers. Apps use services of the OS, OS uses various low level libraries of itself or third parties, and they all use the different pieces of hardware you have.

1

u/claytonkb Aug 02 '19

Say if I have a keyboard connected via USB to my PC, a key press will send the binary version of the ASCII character to the computer, an application and the operating system will incorporate it into a program - but how does it get sent to main memory, as instructions can only be executed from there - if there was no program, would it simply be sent to main memory and then be executed?

You will benefit from reviewing computer architecture (this is the term you're looking for). The CPU, memory and I/O (the three main components of a computer system) are connected together by a common communication channel referred to as the system bus. These days, there are a lot more details, but that's the general overview. When the CPU wants to talk to an I/O device, it sends a message over the system bus to the device. There are special helper devices (called controller hubs) that help the CPU talk to I/O. The reason we have controller hubs is that the CPU core operates thousands or millions of times faster than I/O devices in the system, so the communication between them has to be buffered (a buffer is just a small scratchpad memory for storing a tiny amount of data until it is needed, usually in a communication channel).

And secondly, how would a CPU output something i.e. a monitor? Are there specific instructions in it's instruction set to output to a specific connection?

Both monitors and keyboards (and mice and USB and so on and so forth) are I/O devices and are treated more or less the same. The monitor is usually connected to a graphics device which sits on the system bus so the CPU (or system controller) usually doesn't directly speak to the display, it speaks to the graphics device which, in turn, speaks to the display.

1

u/khedoros Aug 03 '19

Say if I have a keyboard connected via USB to my PC, a key press will send the binary version of the ASCII character to the computer

The keyboard produces a scancode, along with some button state info, packages it in a USB data packet, and transmits it as a serial stream of bits over the cable. It enters the USB controller, which raises an interrupt* for the CPU to handle the data. It might be that the data is transferred by "Direct Memory Access" directly into some standardized/specified area of memory, or stored in some data buffer in the USB controller; honestly I don't remember the specifics there. The interrupt is handled by the OS kernel's drivers, which interpret the packet and forward it along in a way that may vary a bit between OSes.

Are there specific instructions in it's instruction set to output to a specific connection?

Depends on the device and the CPU. X86 definitely has port-based I/O, with instructions called "IN" and "OUT". I know that they were used in older machines to communicate with a lot of hardware, things like the keyboard controller and portions of the various sound adapters (like Adlib synthesizers were configured for port 0x338, and were completely controlled through that).

Two other methods are memory-mapped I/O, where specific memory locations are routed over the system bus to memory or registers in external hardware, and DMA (which I already mentioned), where a chunk of memory might be pushed directly into a known location in memory, or pulled from a known location in memory, to a device.

A chunk of audio might be transferred to your sound card via DMA. The state of your graphics hardware might be some mix of memory-mapping, port-based I/O, and DMA. That's some driver-level kind of stuff, that I don't have much exposure to, outside of the context of DOS (because we had to configure some of that stuff by hand, back in the day). So I'm not 100% on how a modern machine would do it, but it would be a combination of the methods I've described.

* Interrupts are typically meant to signal something like "a transfer has completed, and data is available to be processed". In a CPU, there's a register that tracks the address of the next instruction to fetch. An interrupt basically says "No matter what you're doing, push the address of the instruction after the currently executing one to the stack, switch into an interrupt-handling mode (maybe, depending on CPU type), and run the code that's registered as the interrupt handler".

1

u/uber1337h4xx0r Aug 03 '19

Just a heads up: I'm pretty sure keyboards don't actually receive the ASCII code from the keyboard. They most likely get a code between like 1 and 200 and then the software decides what that code means.

1

u/terriblestraitjacket Aug 03 '19

For security reasons, you actually don't want keyboards to send pure ASCII, a raw number, or the like.

Generally you want to send encrypted packets that can be verified as coming from the keyboard. This prevents an eavesdropper from firstly, knowing what you typed and secondly, sending whatever commands they wanted on the same channel.

The one we use is https://www.microsoft.com/accessories/en-au/aes-encryption

1

u/uber1337h4xx0r Aug 03 '19

Nice. I think I used one of these years ago, but it caused too many issues with either my games or entering passwords into web sign ins (I can't remember which. It was like 10 years ago).

But I do recall it messed up keyloggers somehow.