ChatGPT解决这个技术问题 Extra ChatGPT

What is the difference between Trap and Interrupt?

What is the difference between Trap and Interrupt?

If the terminology is different for different systems, then what do they mean on x86?


A
Aaron Digulla

A trap is an exception in a user process. It's caused by division by zero or invalid memory access. It's also the usual way to invoke a kernel routine (a system call) because those run with a higher priority than user code. Handling is synchronous (so the user code is suspended and continues afterwards). In a sense they are "active" - most of the time, the code expects the trap to happen and relies on this fact.

An interrupt is something generated by the hardware (devices like the hard disk, graphics card, I/O ports, etc). These are asynchronous (i.e. they don't happen at predictable places in the user code) or "passive" since the interrupt handler has to wait for them to happen eventually.

You can also see a trap as a kind of CPU-internal interrupt since the handler for trap handler looks like an interrupt handler (registers and stack pointers are saved, there is a context switch, execution can resume in some cases where it left off).


It's interesting that lxr.free-electrons.com/source/arch/x86/kernel/… divide by zero is initialized as a hardware interrupt, why is that so?
Because it's really an interrupt which the CPU sends when the ALU finds this problem. Just like a segmentation fault. Not all math errors cause interrupts (overflow doesn't), though.
That makes sense. But then, what's a bit confusing is that why in earlier Linux kernels it was initialized as a software trap: set_trap_gate(0,÷_error);
What do you mean, "a bit confusing"? It's very confusing :-) The problem here is that divide by zero is a hardware interrupt (IRQ/vector 0) but the kernel developers have several choices how to handle it. So from a user process, it's a trap but from the CPU side, it's an interrupt. Who is right? None? Both?
Of course, this is only true for x86 CPUs. Other CPUs work differently.
P
Peter Cordes

Traps and interrupts are closely related. Traps are a type of exception, and exceptions are similar to interrupts.

Intel x86 defines two overlapping categories, vectored events (interrupts vs exceptions), and exception classes (faults vs traps vs aborts).

All of the quotes in this post are from the April 2016 version of the Intel Software Developer Manual. For the (definitive and complex) x86 perspective, I recommend reading the SDM's chapter on Interrupt and Exception handling.

Vectored Events

Vectored Events (interrupts and exceptions) cause the processor to jump into an interrupt handler after saving much of the processor's state (enough such that execution can continue from that point later).

Exceptions and interrupts have an ID, called a vector, that determines which interrupt handler the processor jumps to. Interrupt handlers are described within the Interrupt Descriptor Table.

Interrupts

Interrupts occur at random times during the execution of a program, in response to signals from hardware. System hardware uses interrupts to handle events external to the processor, such as requests to service peripheral devices. Software can also generate interrupts by executing the INT n instruction.

Exceptions

Exceptions occur when the processor detects an error condition while executing an instruction, such as division by zero. The processor detects a variety of error conditions including protection violations, page faults, and internal machine faults.

Exception Classifications

Exceptions are classified as faults, traps, or aborts depending on the way they are reported and whether the instruction that caused the exception can be restarted without loss of program or task continuity.

Summary: traps increment the instruction pointer, faults do not, and aborts 'explode'.

Trap

A trap is an exception that is reported immediately following the execution of the trapping instruction. Traps allow execution of a program or task to be continued without loss of program continuity. The return address for the trap handler points to the instruction to be executed after the trapping instruction.

Fault

A fault is an exception that can generally be corrected and that, once corrected, allows the program to be restarted with no loss of continuity. When a fault is reported, the processor restores the machine state to the state prior to the beginning of execution of the faulting instruction. The return address (saved contents of the CS and EIP registers) for the fault handler points to the faulting instruction, rather than to the instruction following the faulting instruction.

Example: A page fault is often recoverable. A piece of an application's address space may have been swapped out to disk from ram. The application will trigger a page fault when it tries to access memory that was swapped out. The kernel can pull that memory from disk to ram, and hand control back to the application. The application will continue where it left off (at the faulting instruction that was accessing swapped out memory), but this time the memory access should succeed without faulting.

An illegal-instruction fault handler that emulates floating-point or other missing instructions would have to manually increment the return address to get the trap-like behaviour it needs, after seeing if the faulting instruction was one it could handle. x86 #UD is a "fault", not a "trap". (The handler would need a pointer to the faulting instruction to figure out which instruction it was.)

Abort

An abort is an exception that does not always report the precise location of the instruction causing the exception and does not allow a restart of the program or task that caused the exception. Aborts are used to report severe errors, such as hardware errors and inconsistent or illegal values in system tables.

Edge Cases

Software invoked interrupts (triggered by the INT instruction) behave in a trap-like manner. The instruction completes before the processor saves its state and jumps to the interrupt handler.


This is such a good answer I was positive the "Late Answer from a New User" review queue was giving me a test to make sure I was paying attention.
Thanks! That means a lot to me :)
Skimmed the PPC aarchitecture book, and it looks like their definitions are largely overlapping. They have new names for edge cases, and treat exceptions like a subtype of interrupts, rather than part of a distinct category.
I think this answer describes it best. It discusses the blurry line that can exist between the two. And mentions that page faults result in the CPU reattempting a instruction a trap skips over the instruction and moves on.
In Alpha Architecture Reference Manual, they write: "There are 3 types of exceptions: 1. A fault is an exception condition that occurs during an instruction ... such that elimination of the fault condition and subsequent re-execution of the instruction will give correct results. ..." 2. An arithmetic trap [with no re-execution of the trapping instruction]. 3. A synchronous trap (divided into data alignment traps and other, e.g., BreakPoint Trap, Illegal Instruction Trap, Generate Software Trap, Change Mode To Kernel Trap etc.)
C
Cheshar

Generally speaking, terms like exceptions, faults, aborts, Traps, and Interrupts all mean the same thing and are called "Interrupts".

Coming to the difference between Trap and Interrupt:

Trap: Is a programmer initiated and expected transfer of control to a special handler routine. (For ex: 80x86 INT instruction is a good example)

Where as

Interrupt(Hardware): Is a program control interruption based on an external hardware event external to the CPU (For ex: Pressing a key on the keyboard or a time out on a timer chip)


Good definitions. Source?
P
Paul R

A trap is a special kind of interrupt which is commonly referred to as a software interrupt. An interrupt is a more general term which covers both hardware interrupts (interrupts from hardware devices) and software interrupts (interrupts from software, such as traps).


It confuses matters even more that some authors (Tanenbaum) refer to "hardware traps." If we can have hardware traps and software interrupts, clearly the definitions are fairly muddy and can go either way, always requiring the word hardware or software.
F
Frank

A trap is called by code like programs and used e. g. to call OS routines (i. e. normally synchronous). An interrupt is called by events (many times hardware, like the network card having received data, or the CPU timer), and - as the name suggests - interrupts the normal control flow, as the CPU has to switch to the driver routine to handle the event.


c
chetan pawar

I think Traps are caused by the execution of current instruction and thus they are called as synchronous events. where as interrupts are caused by an independent instruction that is running in the processor which are related to external events and thus are known as asynchronous ones.


A
Anamik Sarvaiya

Interrupts are hardware interrupts, while traps are software-invoked interrupts. Occurrences of hardware interrupts usually disable other hardware interrupts, but this is not true for traps. If you need to disallow hardware interrupts until a trap is served, you need to explicitly clear the interrupt flag. And usually the interrupt flag on the computer affects (hardware) interrupts as opposed to traps. This means that clearing this flag will not prevent traps. Unlike traps, interrupts should preserve the previous state of the CPU.


D
Dinesh Reddy

An interrupt is a hardware-generated change-of-flow within the system. An interrupt handler is summoned to deal with the cause of the interrupt; control is then returned to the interrupted context and instruction. A trap is a software-generated interrupt. An interrupt can be used to signal the completion of an I/O to obviate the need for device polling. A trap can be used to call operating system routines or to catch arithmetic errors.


S
Sanketssj5

A trap is a software interrupt.If you write a program in which you declare a variable having divide by zero value then it is treated as a trap.Whenever you run this program it will throw same error at the same time.System call is a special version of trap in which a program asks os for its required service. In case of interrupt(a general word for hardware interrupts)like an i/o error,the cpu is interrupted at random time and off course it is not the fault of our programmers.It is the hardware that brings them up.


Can you explain how system call is a trap ?
A system call requires a switch from user mode to kernel mode. The library call that wraps the system call traps to signal the kernel for this switch, and so it may look in the registers where user space will pass the data for the syscall.
E
Exploring Bits

A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap. Trap Vs Interrupt


Terminology can differ on that. e.g. gcc -ftrapping-math tells it to (try unsuccessfully to) optimize such that results match the C abstract machine even if things like divide-by-0 run a signal handler. (i.e. trap on FP exception). But terminology depends on the vendor's documentation. Still, on Intel, int 0x?? isn't the only way to trap. Difference between TRAP , software interrupts and hardware interrupts? says that things like div by zero (#DE exception) is also a trap. The accepted answer on this question also says that.
Do you have a source in Intel's manuals for that claim that a trap is always "intentional", i.e. from an instruction that always traps instead of being data-dependent? Or I guess you're not making a strong claim there, just saying "some may argue". BTW, I'm not sure if Andy Glew (one of the architects of Intel's P6) is using Intel-specific terminology or more general terminology in his answer on When an interrupt occurs, what happens to instructions in the pipeline? where he uses both terms "trap" and "exception" to have specific meanings.