Microprocessors · Lecture Notes

Chapter 5.1: Interrupts

A processor that only ran its own program would know nothing of the outside world. A key is pressed, a timer produces a pulse, a disk drive has data ready; the processor must respond to these events in time. An interrupt lets the processor drop what it is doing at an instruction boundary, run a routine that belongs to the event, and then resume where it left off. These notes begin with what an interrupt is and how it differs from polling. They then cover the 8086 interrupt vector table and the effect of INT and IRET on the stack, followed by exceptions generated by the processor itself, hardware interrupts on the INTR and NMI pins, the 8259A interrupt controller, and interrupt latency. The last part writes an interrupt service routine from scratch, installs its vector, and restores the old vector when the program ends. Every piece of code is traced step by step together with the registers, flags, vector table and stack.

Learning outcomes

Explain the interrupt concept
Explain what an interrupt is, how it differs from polling, and where software, hardware and internal interrupts come from.
Compute a vector address
Use the interrupt vector table to find the vector address for type n (n × 4), then the ISR's CS:IP from the bytes stored there and its physical address.
Trace INT and IRET on the stack
Show step by step the order in which FLAGS, CS and IP are pushed during INT n and IRET, how SP changes, and why IF and TF are cleared.
Recognize exceptions
Explain the two causes of a divide error (INT 0), the condition under which INTO (INT 4) fires, and the single-step (INT 1) and breakpoint (INT 3) mechanisms.
Follow hardware interrupts
Follow INTR acknowledgment, interrupt priorities, the 8259A's IRR, IMR and ISR registers, and the masking of a single IRQ with the IMR; compute interrupt latency in clock cycles.
Write an interrupt service routine
Write your own ISR, install its vector safely, save and restore the old vector, and follow the rules for writing ISRs.

5.1.1The interrupt concept

5.1.1.1What is an interrupt?

While a program runs, the processor fetches, decodes and executes instructions in order. After each instruction IP points to the next one, and apart from jumps and calls this order is never disturbed. Yet events that have nothing to do with the program happen all around the computer. A user presses a key, the timer chip produces pulses at fixed intervals, a character arrives on the serial port. The processor must not miss these events and must respond to them quickly.

Definition 5.1.1

An interrupt is an event that makes the processor temporarily set aside its current work and run a special routine. This routine is called an interrupt service routine (ISR). When the ISR finishes, the processor resumes the program with the instruction after the one that was interrupted.

The last sentence of the definition is the important one. The interrupted program does not notice that it was interrupted. Its registers, flags and memory continue with the values they would have had without the interrupt. Guaranteeing this is the job of both the processor and the programmer who writes the ISR. The processor saves the return address and the flags on its own. The ISR saves the registers it uses and restores them on exit.

An everyday analogy captures the steps of an interrupt. You are reading a book when the phone rings. You first mark your page, then answer the phone and talk. When the call ends, you return to the marked page and carry on reading. Marking the page is saving the return address; the phone call is the ISR; returning to the marked page is the IRET instruction. If you forget to mark the page, you will not know where to continue. The processor would be in the same position if it entered an ISR without pushing the return address on the stack.

main programmain program (resumes)ISRINT / requestIRETreturn address on stack
Figure 5.1.1: The main program is interrupted by a request or an INT instruction, the ISR runs, and IRET returns to where it left off. The return address stays on the stack for the whole time.

Figure 5.1.1 shows this flow on a time axis. The main program stops at some point, control passes to the ISR, and the last instruction of the ISR, IRET, hands control back to the main program. An interrupt can be started in two ways: the program executes an INT instruction, or a request arrives from outside the processor. In both cases what the processor does afterwards is the same.

Interrupts have a second, more everyday use. On an 8086-based PC there are ready-made routines for writing a character to the screen, reading a key from the keyboard, accessing the disk, or ending a program. These are the routines of the BIOS, which sits in ROM on the motherboard, and of the operating system, DOS. A program calls them with an INT instruction, without knowing their addresses. To write a character to the screen, for example, it does not need dozens of instructions that drive the video hardware; INT 10h does the job. For this reason software interrupts are also seen as ready-made services that make programming easier. The details of the interrupt functions that work with hardware such as the screen, the keyboard, the disk drive and memory management are the subject of the notes of Chapter 5.2, Interrupt Functions. These notes cover the interrupt mechanism itself: how the processor accepts an interrupt and how it returns.

5.1.1.2Polling or interrupts?

A processor can learn the state of a device in two ways. The first is to keep asking the device, "Is the data ready?" This method is called polling. In a loop the processor reads the device's status port, checks the ready bit, and reads again if it is not set. The second is for the device to announce itself. When its data is ready, the device drives a pin of the processor; the processor finishes the current instruction and switches to the ISR. This is the interrupt method.

Pollingready?ready?ready?ready?ready?ready?ready?ready?ready?ready?The CPU keeps asking the device; most checks are wasted and data may be noticed late.Interruptmain programISRmain program (where it left off)device: “data ready”return with IRET
Figure 5.1.2: Top, polling: the processor keeps asking the device "ready?" and most queries are wasted. Bottom, interrupt: the processor runs the main program, the device signals when data is ready, the ISR runs, and IRET returns.

Figure 5.1.2 compares the two methods on the same time axis. The cost of polling can be seen in a single number. The shortest polling loop that asks for the keyboard's state has three instructions: an IN that reads the port, a TEST that checks the ready bit, and a conditional jump that goes back to the start if the device is not ready.

; polling loop (port number and bit are examples)
poll:  IN   AL, 64h      ; read the status port (10 clocks)
       TEST AL, 01h      ; data-ready bit (4 clocks)
       JZ   poll         ; not ready: ask again (16 clocks)

According to Intel's 8086 manual, an IN with a fixed port takes 10 clock cycles, a TEST of a register with an immediate takes 4, and a taken JZ takes 16. One pass of the loop is 30 clock cycles; on a 5 MHz 8086 a clock cycle is 200 ns, so the loop turns once every 6 µs. The processor asks the device about 166,000 times per second. A fast typist presses ten keys per second. Of those 166,000 queries only ten get a "yes" and the rest are wasted. Worse, the processor can do nothing else in the meantime.

Polling less often saves processor time, but then the event is noticed late. If the program asks every 10 ms, the response to a key press can be delayed by up to 10 ms. The longer the interval, the greater the risk of losing data. For example, characters arriving on a serial port at 9600 bit/s are about 1 ms apart. If the device has a one-character buffer, a character that is not read within 1 ms is overwritten by the next.

With interrupts this dilemma disappears. The processor runs the main program as long as there is no event; the moment an event occurs, at the latest when the current instruction finishes, it switches to the ISR. The price is the machinery. A routine must be written for each event, its address placed in a table, the stack used for the return address, and the hardware needs lines that carry the request to the processor. Table 5.1.1 compares the two methods.

Table 5.1.1: Comparison of polling and interrupts.
CriterionPollingInterrupt
Hardwaresimple; no extra line neededa request line and, if needed, an interrupt controller
Processor timewasted; most queries return "no"spent only when an event occurs
Response timedepends on the polling interval; an event may be noticed lateshort; at the latest when the running instruction finishes
Software structurea single loopvector table, stack and ISR
Suited tosingle-task, simple systems; very fast, continuous datarare events at unpredictable times; multitasking systems

Polling is not always bad. If a small microcontroller circuit is only waiting for one button, polling is the simplest solution. If a very fast device produces data every few microseconds, a tight polling loop can be faster than bearing the overhead of the interrupt machinery for every item. A general-purpose computer, on the other hand, has independent events at unpredictable times: keyboard, timer, disk and serial port. Polling all of them in one loop both keeps the processor busy and slows the response. This is why the PC architecture is built on interrupts.

Common mistake

Generalizing "with an interrupt the processor never waits for the device" to "an interrupt is always faster than polling." The interrupt mechanism itself takes time: on the 8086, accepting a hardware interrupt takes 61 clock cycles and IRET takes 24. For an event that arrives thousands of times per second, this overhead can exceed the cost of polling. The advantage of interrupts is that for rare events the processor does not wait in vain.

5.1.1.3Interrupt kinds and type numbers

The 8086 distinguishes up to 256 different interrupts. Each interrupt has a type number between 0 and 255 (00h–FFh). When the processor accepts an interrupt, the first thing it does is determine this number; it then reads from a table which routine to go to for that number. Interrupts fall into three groups, according to where the type number comes from and what starts the interrupt.

Definition 5.1.2

A software interrupt is one called deliberately by an INT n instruction in the program; the type number n is inside the instruction. A hardware interrupt is one started when an external device drives the processor's INTR or NMI pin. An internal interrupt, or exception, is one the processor generates itself while executing an instruction; division by zero is the best-known example.

Software interrupts. BIOS and DOS services are used this way: INT 10h is the screen, INT 16h the keyboard, INT 21h the DOS services. Two more special instructions belong to this group. INT 3 is the breakpoint instruction used by debuggers and is encoded in a single byte. INTO calls INT 4 when the overflow flag OF = 1 and does nothing when OF = 0. Because they serve debugging and error trapping, these two instructions are often mentioned together with exceptions.

Hardware interrupts. The 8086 has two input pins for interrupt requests. INTR (interrupt request) is the maskable input: while IF = 0 the processor ignores this pin. Requests from the keyboard, timer, disk and serial port arrive on it. NMI (non-maskable interrupt) is the non-maskable input; it is accepted whatever IF is. It is reserved for urgent events that a program cannot switch off and ignore, such as a memory parity error or loss of power.

Internal interrupts. The processor turns some conditions into interrupts by itself. When DIV or IDIV divides by zero, or the quotient does not fit in the destination register, INT 0 is generated. While the trap flag TF = 1, INT 1 is generated after every instruction; this lets debuggers run a program one step at a time.

Table 5.1.2 gives the role of the first five type numbers. The 8086 itself uses these five types; their numbers are fixed and a programmer must not use them for anything else.

Table 5.1.2: Reserved interrupt types of the 8086.
TypeSourceDescription
00hinternalDivide error: DIV/IDIV by zero, or the quotient does not fit
01hinternalSingle step (TF = 1); used by debuggers
02hhardwareNMI pin (non-maskable)
03hsoftwareBreakpoint; the one-byte INT 3 (CCh)
04hsoftwareINTO: overflow interrupt if OF = 1
05h–FFh—Intel reserved 05h–1Fh for later processors; on the PC the BIOS, DOS and user programs use them

Intel stated explicitly in its documentation that it was reserving the range 05h–1Fh for its future processors. The designers of the IBM PC did not heed this warning and placed BIOS services in the range 05h and 08h–1Fh. For example, the BIOS routine that prints the screen on the printer uses type 05h. With the 80186 and 80286, type 05h became the bound-range-exceeded interrupt of the BOUND instruction. The same number thus acquired two different meanings, and PC software wrestled with this collision for years. The story is a good illustration of why reserved numbers must stay reserved.

5.1.1.4Comparing the three sources

At first glance the three kinds of interrupt look very different: one is an instruction, one is a pin, one is an error condition. They differ in only two respects: where the type number comes from and when the interrupt occurs. Table 5.1.3 puts these differences side by side.

Table 5.1.3: Comparison of software, hardware and internal interrupts.
Software (INT n)Hardware (INTR / NMI)Internal (exception)
Triggered byan instruction in the programan external device, a pinthe processor itself
Timingsynchronous: always at the same placeasynchronous: after any instructionsynchronous: at the faulting instruction
Type numberinside the instructionINTR: from the 8259A, via INTA; NMI: always 2fixed: 0, 1
When IF = 0still runsINTR waits, NMI runsstill runs
Typical useBIOS/DOS service, INT 3, INTOkeyboard, timer, diskdivide error, single step

The words synchronous and asynchronous are used here with respect to the program flow. A software interrupt occurs at the same point of the program, in the same way, on every run. An exception is the same: the same DIV instruction with the same data gives the same error every time. A hardware interrupt, on the other hand, is an event whose instruction in the program cannot be known in advance. The user presses a key once at the start of a loop and once in the middle. For this reason the ISR of a hardware interrupt must be written as if it could run at any point of the program. This is where the obligation of ISRs to save registers comes from.

There is an important common point under the table. Once the type number is determined, all three kinds follow the same steps: FLAGS, CS and IP are pushed, IF and TF are cleared, and CS:IP is loaded from the vector table. In other words there is a single interrupt mechanism inside the processor; the sources only determine with which number and at what moment that mechanism is entered.

Common mistake

Assuming that the CLI instruction turns off all interrupts. CLI only clears IF and affects only the INTR input. Software interrupts such as INT 21h, exceptions such as division by zero, and NMI still run while IF = 0. When CLI is used to "protect a critical piece of code from interrupts", remember that NMI can still arrive.

5.1.2The interrupt vector table

5.1.2.1Structure of the table

After the processor learns the type number of an interrupt, it must find where the ISR for that interrupt is. On the 8086 this information is kept in a table at the very beginning of memory. The location of the table is fixed; on every interrupt the hardware looks at the same address.

Definition 5.1.3

An interrupt vector is the 4-byte far address of the service routine of an interrupt type: 2 bytes of IP (offset) and 2 bytes of CS (segment). The interrupt vector table (IVT) is the 1 KB table that holds the vectors of the 256 interrupt types in order and occupies physical addresses 00000h–003FFh.

The size of the table is easy to compute: 256 types × 4 bytes = 1024 bytes = 1 KB. The vector of type 0 starts at 00000h, that of type 1 at 00004h, that of type 2 at 00008h, and so on. The vector of the last type, FFh, is in bytes 003FCh–003FFh. The address at which the vector of type n starts is therefore a simple multiplication:

vector address = n × 4    (within segment 0000h)

The layout of the four bytes of a vector is also fixed. Figure 5.1.3 shows the table. The word at the lower address (n × 4 and n × 4 + 1) holds the IP value. The word at the higher address (n × 4 + 2 and n × 4 + 3) is the CS value. Both words are stored in little-endian order, like all words on the 8086: low byte first, then high byte.

address (0000:…)+0, +1+2, +30000hIPCSINT 00h0004hIPCSINT 01h0008hIPCSINT 02h000ChIPCSINT 03h⋮0040hIP = F065hCS = F000hINT 10h⋮0084hIPCSINT 21h⋮03FChIPCSINT FFh256 entries × 4 bytes = 1024 bytes (0000:0000 – 0000:03FF)
Figure 5.1.3: The interrupt vector table. Each row is the 4-byte vector of one interrupt type: IP first, then CS. The value F000:F065 in the INT 10h row is the address of the video routine in the original IBM PC BIOS and is given as an example.

The answer to why the table is at the very beginning of memory lies in the design of the 8086. The hardware does not have to look at any register to find the table; the address is produced from the type number alone. The operation n × 4 is a two-bit shift in the circuit. The 8 bits of the type number are placed on address lines A2–A9; A0, A1 and A10–A19 are zero. Reading a vector therefore needs no extra adder or register. The price is that the first 1 KB of memory must always be RAM. Programs have to be able to change the table; if it were in ROM, no program could install its own ISR.

The table is an ordinary region of memory with no special protection. Any program that sets a segment register to 0000h can read and write any byte of the table. This flexibility lets programs install their own ISRs; it also means that a faulty program can corrupt the table and crash the whole system. Later processors with protected mode solve this problem by moving the table into a protected structure. In the real mode of the 8086, the safety of the table is left entirely to the programmer.

Common mistake

Thinking of the four bytes of a vector in the order "CS first, then IP". The notation CS:IP writes the segment first and so invites this error. In memory the order is reversed: at address n × 4 is the low byte of IP, and at n × 4 + 2 is the low byte of CS.

5.1.2.2The vector address step by step

It helps to follow the rule in action on an example. Suppose the program is executing INT 10h. The processor finds the vector and switches to the ISR in four steps.

Example 5.1.1

Let us find the vector address for INT 10h, the ISR's CS:IP, and its physical address. Suppose the four bytes of the table starting at address 0000:0040h are, in order, 65 F0 00 F0.

  1. Type number. The second byte of the instruction is the type number: n = 10h = 16.
  2. Vector address. n × 4 = 10h × 4 = 40h (decimal: 16 × 4 = 64). The vector is in bytes 0000:0040h–0000:0043h. In binary, shifting 0001 0000b left by two bits gives 0100 0000b = 40h.
  3. Reading the bytes. At 0040h there is 65h and at 0041h F0h; the low word is IP = F065h. At 0042h there is 00h and at 0043h F0h; the high word is CS = F000h.
  4. Physical address. CS × 16 + IP = F0000h + F065h = FF065h. The ISR starts inside the BIOS ROM in the topmost 64 KB of memory.
0040h65h0041hF0h0042h00h0043hF0h} IP = F065h} CS = F000hphysical address = CS × 16 + IPF0000h + F065h = FF065h
Figure 5.1.4: Top, bytes 0040h–0043h: low word IP = F065h, high word CS = F000h. Bottom, the physical address calculation: F0000h + F065h = FF065h.

The bytes read in the example are shown in Figure 5.1.4. The processor fetches these two words with two separate memory reads. The 8086 reads a word at an even address in a single bus cycle. Because both n × 4 and n × 4 + 2 are even, each word arrives in one cycle. The 4-byte alignment of the vector table is also convenient in this respect.

The physical address calculation in the fourth step is the segmentation rule the 8086 uses for all memory accesses: the 16-bit segment value is shifted left by four bits (multiplied by 16) and the offset is added. The segment CS = F000h starts at F0000h. IP = F065h is a position inside this segment. The result is the 20-bit address FF065h.

There is an important detail about the order here. Before the processor reads the vector and loads CS:IP, it writes the return information to the stack. So while the first instruction of the ISR is fetched from FF065h, the old CS, IP and FLAGS are already on the stack. If this order were broken, that is, if CS:IP were loaded first, the return address would be lost. The exact order of the steps is in Table 5.1.5.

5.1.2.3From table to routine and back

Two-way calculations are done on the vector table. In the first direction one goes from a type number to the address of the vector; this is the multiplication n × 4. In the second direction one finds, from an address in the table, which type's vector it is; this is a division of the address by 4. The second direction is needed when looking at a byte sequence in a memory dump and working out what it is.

Example 5.1.2

In a memory dump the bytes 2E E8 00 F0 are seen starting at address 0000:0058h. a) Which interrupt's vector is it? b) What are the ISR's CS:IP and physical address? c) At which addresses is the vector of type 1Ch in the same table?

  1. a) 58h / 4 = 16h. Because the address is a multiple of 4, it is the start of a vector: type 16h, that is, the BIOS keyboard service INT 16h.
  2. b) Low word: 2Eh, E8h → IP = E82Eh. High word: 00h, F0h → CS = F000h. Physical address F0000h + E82Eh = FE82Eh.
  3. c) 1Ch × 4 = 70h. IP is in bytes 00070h–00071h and CS in bytes 00072h–00073h.

If the address were not exactly divisible by 4, for example 005Ah, it would not be the start of a vector but the CS half of the vector of type 16h (5Ah = 4 × 16h + 2).

The calculation is the same for all types: IP is at n × 4 and n × 4 + 1, CS at n × 4 + 2 and n × 4 + 3. For type 00h the address comes out as 0000h, for type FFh as 03FCh; all addresses in between are multiples of 4.

Common mistake

Mistaking the type number for the address directly (INT 21h → 00021h) or multiplying by 2 instead of 4 (INT 21h → 00042h). The correct value is 21h × 4 = 84h. To avoid slips in hexadecimal multiplication, one way is to convert to decimal first: 21h = 33, 33 × 4 = 132 = 84h.

5.1.2.4How the PC divides up the type numbers

The first five of the 256 type numbers belong to the 8086. The rest are left to the designers of the system that uses the processor. On the IBM PC and DOS the numbers are divided up roughly as follows (Table 5.1.4).

Table 5.1.4: Frequently used interrupt types on the IBM PC and DOS.
TypeVector addressRole
00h–04h000h–013hthe 8086's own types (divide error, single step, NMI, breakpoint, overflow)
05h014hBIOS: print the screen
08h–0Fh020h–03Fhhardware interrupts IRQ0–IRQ7 (08h timer, 09h keyboard)
10h040hBIOS: video / screen services
13h04ChBIOS: disk services
16h058hBIOS: keyboard services
1Ah068hBIOS: clock / date
20h080hDOS: terminate program
21h084hDOS: general services (selected with AH)
33h0CChmouse driver
60h–67h180h–19Fhreserved for user programs
70h–77h1C0h–1DFhIRQ8–IRQ15 of the second 8259A on the PC/AT

The practical conclusion from this table is that a program that installs its own ISR should choose an unused type. The range 60h–67h is set aside for this purpose. The examples in these notes that install their own ISR therefore use types 60h, 61h and 90h. A program that changes the vector of a type in use, for example INT 21h, redirects all DOS services to its own routine. This is sometimes done on purpose. For example, a program changes the vector of type 0 so that its own routine runs instead of DOS's divide error routine. In that case it is mandatory to restore the old vector when the program ends.

5.1.3INT and IRET

5.1.3.1The steps of INT n

The INT n instruction is two bytes: the opcode CDh and the type number n. For example INT 21h sits in memory as CD 21. While executing it the processor does a series of things the programmer cannot see. They resemble a procedure call but include more. Table 5.1.5 gives the steps in order.

Table 5.1.5: The steps of the INT n instruction and the effect of each on the stack, registers and bus.
StepOperationEffectBus cycle
1FLAGS is pushed on the stackSP ← SP − 2, [SS:SP] ← FLAGSmemory write
2IF and TF are clearedIF = 0, TF = 0—
3CS is pushed on the stackSP ← SP − 2, [SS:SP] ← CSmemory write
4IP is pushed on the stack (the address of the instruction after INT)SP ← SP − 2, [SS:SP] ← IPmemory write
5vector is readIP ← [0000:n×4], CS ← [0000:n×4+2]two memory reads
6the ISR runs and ends with IRETIP, CS, FLAGS are popped from the stack in that orderthree memory reads

Every row of the table has a reason. Step 1 saves the flags. The result of the interrupted program's last comparison, for example ZF, may change during the ISR. If the program is interrupted between a CMP and a JE and the flags are not saved, JE jumps the wrong way. Saving the flags automatically is therefore essential. The CALL instruction does not save the flags, because the program knows when a procedure will be called.

Step 2 clears IF and TF. IF = 0 prevents the ISR from being interrupted by another maskable interrupt at its very first instruction. TF = 0 prevents the ISR from being stopped step by step by the single-step interrupt. It matters that this clearing is done after FLAGS has been pushed. The copy on the stack carries the old IF and TF values. When IRET restores that copy, IF and TF return to their values from before the interrupt.

Steps 3 and 4 save the return address. Because the ISR may be in another segment, IP alone is not enough; CS is saved too. The IP written to the stack is not the address of the INT instruction itself but the address of the instruction after INT. The processor has already advanced IP by two bytes when fetching INT.

Step 5 reads the vector and loads it into CS:IP. From this moment the first instruction the processor fetches is the first instruction of the ISR. The BIU's prefetch queue is also flushed; the bytes in the queue belonged to the instructions after INT and are now invalid.

A total of 6 bytes, that is 3 words, is written to the stack. The whole of INT n takes 51 clock cycles on the 8086. A significant part of these cycles is spent on five memory accesses: three writes to the stack and two reads from the vector table. Flushing the queue and refetching the first bytes of the ISR also take time.

Definition 5.1.4

IRET (interrupt return) is the return instruction from an interrupt service routine. It pops IP, CS and FLAGS from the stack in that order; SP increases by 2 on each pop. It is a single byte (CFh) and takes 24 clock cycles on the 8086.

IRET reads back in reverse order what INT wrote to the stack. This is natural because the stack works last in, first out: the IP pushed last is popped first, and the FLAGS pushed first are popped last. When FLAGS comes back, IF and TF take their old values too. A program that had IF = 1 before the interrupt therefore continues with IF = 1 after IRET.

Table 5.1.6 gives the encoding and timing of the interrupt instructions that appear in these notes.

Table 5.1.6: Machine code, length and clock cycles of the 8086 interrupt instructions (8086 manual).
InstructionMachine codeLengthClock cycles
INT nCD n2 bytes51
INT 3CC1 byte52
INTOCE1 byte53 (OF = 1) / 4 (OF = 0)
IRETCF1 byte24
CLI / STIFA / FB1 byte2

5.1.3.2The stack step by step: INT 10h

Let us follow the effect of the steps on the stack with concrete numbers. Suppose the INT 10h instruction in a .COM program is at address 0700:0104. When emu8086 loads a .COM program, CS = DS = SS = 0700h and SP = FFFEh. Initially only IF = 1; because bit 1 and bits 12–15 of the 8086 FLAGS register always read as 1, FLAGS = F202h. Suppose the vector of INT 10h is F000:F065, as in Example 5.1.1.

Table 5.1.7: The stack and registers during INT 10h at 0700:0104 and the IRET at the end of the ISR (SS = 0700h).
StepOperationSP[FFF8h][FFFAh][FFFCh]CS:IPFLAGS
0startFFFEh———0700:0104F202h
1FLAGS pushedFFFCh——F202h0700:0104F202h
2IF = TF = 0FFFCh——F202h0700:0104F002h
3CS pushedFFFAh—0700hF202h0700:0104F002h
4IP pushedFFF8h0106h0700hF202h0700:0104F002h
5CS:IP ← vectorFFF8h0106h0700hF202hF000:F065F002h
6IRET: IP, CS poppedFFFCh0106h0700hF202h0700:0106F002h
7IRET: FLAGS poppedFFFEh0106h0700hF202h0700:0106F202h

The rows of Table 5.1.7 read as follows. In step 1 SP is first decreased by 2 and becomes FFFCh, and the current value of FLAGS, F202h, is written to this address. In step 2 IF and TF in the register are cleared; with bit 9 (IF) of F202h cleared, FLAGS = F002h. The copy on the stack stays F202h. In step 3 SP becomes FFFAh and CS = 0700h is written. In step 4 SP becomes FFF8h and the return address is written. Because INT 10h is two bytes, the return address is 0104h + 2 = 0106h. In step 5 CS:IP is loaded from the vector and the ISR starts running. In this example the ISR writes a character to the screen.

stack (SS = 0700h)FFF6hFFF8hFFFAhFFFChF202h← SPFFFEhCS0700hIP0104hSPFFFChFLAGSF202h stack (SS = 0700h)FFF6hFFF8h0106h← SPFFFAh0700hFFFChF202hFFFEhCS0700hIP0104hSPFFF8hFLAGSF002h
Figure 5.1.5: Left, after FLAGS is pushed (SP = FFFCh); right, after the return address 0106h is pushed (SP = FFF8h). Toward the top of the stack the three words are laid out as FLAGS, CS, IP.

When the ISR finishes and IRET runs, the stack empties in the opposite direction. In step 6 the 0106h at [FFF8h] is popped into IP, the 0700h at [FFFAh] into CS, and SP = FFFCh. In step 7 the F202h at [FFFCh] is popped into FLAGS and SP returns to FFFEh. IF is 1 again. The program continues from 0700:0106, that is, from the instruction after INT 10h.

stack (SS = 0700h)FFF6hFFF8h0106h← SPFFFAh0700hFFFChF202hFFFEhCSF000hIPF065hSPFFF8hFLAGSF002h stack (SS = 0700h)FFF6hFFF8h0106hFFFAh0700hFFFChF202hFFFEh← SPCS0700hIP0106hSPFFFEhFLAGSF202h
Figure 5.1.6: Left, while the ISR runs: CS:IP = F000:F065, FLAGS = F002h. Right, after IRET: CS:IP = 0700:0106, SP = FFFEh, FLAGS = F202h. The three words on the stack are not erased; only SP moves back.

A detail in the last row deserves attention: after IRET the three words on the stack remain in memory (Figure 5.1.6). POP and IRET do not erase memory; they only increase SP. The region above SP is now considered "free", and the next PUSH or interrupt overwrites these values. This is why old values are visible when you look at the stack window of a debugger.

Example 5.1.3

When the same program is run in emu8086 with its own ISR placed in the INT 10h vector, the words written to the stack can be read. The code is:

org 100h
mov ah, 0Eh      ; 0100h, 2 bytes
mov al, 'A'      ; 0102h, 2 bytes
int 10h         ; 0104h, 2 bytes (CD 10)
ret             ; 0106h: return address

Right after INT 10h executes, SP = FFF8h and the stack holds the words [FFF8h] = 0106h, [FFFAh] = 0700h, [FFFCh] = F202h. After IRET, SP = FFFEh. The values are exactly the same as in Table 5.1.7.

Common mistake

Taking the IP pushed on the stack to be the address of the INT instruction itself (0104h in this example). The value pushed is the address of the next instruction (0106h). Otherwise IRET would take the processor back to the INT and the program would enter an infinite loop.

5.1.3.3INT/IRET versus CALL/RET

The similarity between INT and a procedure call is obvious: both write the return address to the stack and jump elsewhere. The differences show why ISRs need a separate return instruction. Table 5.1.8 compares the two pairs.

Table 5.1.8: Comparison of CALL/RET and INT n/IRET.
CALL / RETINT n / IRET
Target addressin the instruction (a label)from the vector table (n × 4)
Pushed on the stackIP (near) or CS + IP (far)FLAGS + CS + IP (6 bytes)
FlagsunchangedIF = 0, TF = 0
ReturnRET: pops IP (and CS)IRET: pops IP, CS, FLAGS
Instruction length3 bytes (near CALL)2 bytes (INT 3: 1 byte)
Invoked byonly the programthe program, the processor (exception) or hardware

The most important row is the last. Only the program calls a procedure; at that point the program knows the state of the flags and, if necessary, saves them itself. An ISR, on the other hand, can be invoked by a hardware event without the program's knowledge. That is why the job of saving the flags is given to the processor.

The target address row also gives an important flexibility. The assembler writes the target of a CALL into the instruction, and this value does not change. The target of INT is read from the table at run time. Changing the vector redirects every INT call to another routine without changing any code. This is how DOS, drivers and resident programs can add their own functions to the BIOS services. The technique of interrupt chaining rests on this flexibility. The new routine does its own work and then jumps to the old vector, so that the old routine runs too.

In the instruction length row, INT being 2 bytes is also an advantage. A far CALL is 5 bytes; calling a BIOS routine with a far CALL means both longer code and a fixed address that depends on the BIOS version. INT 10h, by contrast, is the same two bytes on every BIOS.

5.1.3.4An ISR that ends with RET: code trace

To see the practical consequence of the difference in Table 5.1.8, we trace a deliberately faulty program. The program installs its own ISR on type 61h and calls it with INT 61h, but ends the ISR with a near RET instead of IRET.

org 100h
mov ax, 0
mov es, ax
mov word ptr es:[61h*4], offset isr
mov word ptr es:[61h*4+2], cs
int 61h
hlt              ; SP = ?
isr:
ret              ; BUG!

The code runs line by line as follows. mov ax, 0 and mov es, ax set ES to 0000h. Because an immediate value cannot be loaded directly into a segment register, 0 is put into AX first. From then on every address written with es:[…] is inside the vector table. The third line writes the offset of the isr label to the IP half of the vector of type 61h, at address 61h × 4 = 184h. The assembler computes the expression 61h*4 itself and puts 0184h in the instruction. The fourth line writes the value of CS to address 186h. CS and the ISR are in the same segment, so the vector points to 0700:0114.

Counting the bytes of the program makes the IP values in the trace table easier to understand. The lengths and addresses of the instructions are: mov ax, 0 3 bytes (0100h–0102h), mov es, ax 2 bytes (0103h–0104h), the word write with an ES prefix 7 bytes (0105h–010Bh), the CS write 5 bytes (010Ch–0110h), int 61h 2 bytes (0111h–0112h), hlt 1 byte (0113h) and ret 1 byte (0114h). So the isr label is 0114h and the return address of INT 61h is 0113h.

Table 5.1.9: Trace of the program whose ISR ends with RET (state after each line executes; SS = 0700h).
LineInstructionCS:IP (next)SPIFStack / memory
2mov ax, 00700:0103FFFEh1[FFFEh] = 0000h
3mov es, ax0700:0105FFFEh1ES = 0000h
4mov … [61h*4], offset isr0700:010CFFFEh1[0000:0184h] = 0114h
5mov … [61h*4+2], cs0700:0111FFFEh1[0000:0186h] = 0700h
6int 61h0700:0114FFF8h0[FFF8h] = 0113h, [FFFAh] = 0700h, [FFFCh] = F202h
9ret (wrong)0700:0113FFFAh0[FFFAh] = 0700h, [FFFCh] = F202h left on the stack
7hlt0700:0114FFFAh0processor halted, IF = 0

Two lines of the trace are critical (Table 5.1.9). In line 6, int 61h writes 6 bytes to the stack: FLAGS (F202h), CS (0700h) and the return IP (0113h). SP = FFF8h and IF = 0, and CS:IP is loaded from the vector as 0700:0114. In line 9, the near ret in the ISR pops only the word at the top of the stack: IP = 0113h. CS does not change; because the ISR and the program are in the same segment, this time we happen to return to the right segment. SP, however, increases by only 2 and becomes FFFAh. The expected value is FFFEh; the stack is off by 4 bytes. Because FLAGS was not popped from the stack, IF remains 0.

stack (SS = 0700h)FFF80113h← SPFFFA0700hFFFCF202hFFFE0000hCS:IP (next)0700:0114SPFFF8hIF = 0FLAGS = F002h stack (SS = 0700h)FFF8FFFA0700h← SPFFFCF202hFFFE0000hleftover data: CS, FLAGSCS:IP (next)0700:0113SPFFFAhIF = 0FLAGS = F002h
Figure 5.1.7: Left, after int 61h: three words on the stack, SP = FFF8h, IF = 0. Right, after the faulty ret: only IP has been popped; CS and FLAGS remain on the stack as leftover data, SP = FFFAh, IF is still 0.

When the program reaches hlt, there are two problems at once (Figure 5.1.7). First, interrupts are off. HLT stops the processor until an interrupt arrives. Because IF = 0, no request from INTR can wake the processor; only NMI or RESET can. In this small program the processor waits forever. Second, the stack is out of step. If there were a ret instead of HLT, it would take the 0700h at the top of the stack for the return address and jump to 0700:0700. There is no meaningful code to execute there.

Trying to fix the problem with RETF is not enough either. The far return instruction pops IP and CS and increases SP by 4. The 2 bytes of FLAGS still remain on the stack and IF does not return to its old state. The rule is therefore absolute: ISRs always end with IRET.

Common mistake

Writing an ISR inside PROC/ENDP and putting RET at the end out of habit. The assembler does not object, because RET is a valid instruction. The error shows up only at run time, often long after the ISR, as a wrong return address or as interrupts that never come again. The symptom being far from the cause makes this bug hard to find.

5.1.4Exceptions

Exceptions are the way the processor reports to the program the special situations it meets while executing an instruction. The 8086 has two true exceptions: divide error (INT 0) and single step (INT 1). The breakpoint (INT 3) and overflow interrupt (INT 4 via INTO) are really software interrupts called by an instruction. But because both are used for debugging and error trapping, they are treated together with exceptions. Intel's 8086 manual groups these four interrupts, together with INT n, under the heading "internal interrupts".

5.1.4.1Divide error (INT 0)

The DIV and IDIV instructions write the quotient to a fixed-size register. In an 8-bit division the dividend is in AX, the quotient is written to AL and the remainder to AH. In a 16-bit division the dividend is in DX:AX, the quotient goes to AX and the remainder to DX. If the quotient does not fit in the destination register, there is no way to produce a correct result. In this case the processor does not write the result and raises the type 0 interrupt.

Definition 5.1.5

A divide error is the type 0 interrupt that the processor raises when, in a DIV or IDIV instruction, the divisor is zero or the quotient does not fit in the destination register. The destination is AL in an 8-bit division and AX in a 16-bit division.

The second condition in the definition is often overlooked. A divide error can occur even without division by zero.

Example 5.1.4

DIV BL runs with AX = 1000 (03E8h) and BL = 2. What happens? How can the same division be done without an error?

  1. 8-bit division: AX / BL = 1000 / 2 = 500. The quotient is to be written to AL.
  2. AL can hold at most 255. Since 500 > 255, the quotient does not fit. Although the divisor is not zero, the processor raises INT 0.
  3. The solution is a 16-bit division: DX = 0, AX = 1000, BX = 2 and DIV BX. The dividend DX:AX = 0000:03E8h = 1000. The quotient 500 = 01F4h is written to AX and the remainder 0 to DX. AX can hold at most 65,535, and 500 fits easily.

A smaller borderline example: AX = 01FEh (510) / 2 = 255 = FFh fits; AX = 0200h (512) / 2 = 256 does not fit and raises INT 0. These values were verified by running them in emu8086.

The rule can be put briefly: in an 8-bit DIV, if AH ≥ BL, that is, if the high half of the dividend is not smaller than the divisor, the quotient exceeds 255 and the error occurs. In the example AH = 03h and BL = 02h, and since 03h ≥ 02h the error is unavoidable. For a 16-bit DIV the condition is DX ≥ divisor. This check can be made before the division with a CMP.

In the signed division IDIV the limits are the signed range. On the 8086 the quotient of an 8-bit IDIV must lie between −127 and +127; for a 16-bit IDIV the range is −32,767 to +32,767. This limit leaves out the smallest value possible in two's complement (−128 or −32,768). For example, with AX = −128 (FF80h) and BL = 1, IDIV BL finds the quotient −128 and on the 8086 still raises INT 0. Later processors accept this smallest value.

Return address. The IP that the 8086 pushes on a divide error is the address of the instruction after DIV. So IRET resumes the program by skipping the division. Execution continues as if the division had never been done; the destination registers keep their old values. On the 80286 and later processors this behavior was changed, and the address of the faulting instruction itself is pushed. The error routine can then remove the cause and retry the instruction. An error routine written for the 8086 does not have this option; it can only report to the program in some way that the result is invalid.

What does DOS do? When a program starts, the vector of INT 0 points to DOS's own routine. This routine prints "Divide overflow" on the screen and terminates the program. A program can change this behavior by installing its own routine. The simplest form of this is seen in the trace below.

Common mistake

Thinking of a divide error only as "division by zero" and checking only whether the divisor is zero. When the dividend is large and the divisor small, the quotient does not fit in the destination and the same interrupt occurs. Checking before the division both that the divisor is nonzero and that the quotient will fit (AH < divisor for 8 bits, DX < divisor for 16 bits) prevents INT 0 in the first place.

5.1.4.2Our own INT 0 handler: code trace

The following program redirects the vector of type 0 to its own routine and deliberately divides by zero. The routine leaves the program an "invalid result" marker by writing FFFFh to AX.

org 100h
mov ax, 0
mov es, ax           ; ES = 0: IVT
mov word ptr es:[0*4], offset div_err
mov word ptr es:[0*4+2], cs
mov ax, 100
mov bl, 0
div bl               ; INT 0!
mov dl, al           ; returns here
ret
div_err:
mov ax, 0FFFFh       ; error flag
iret

The first two lines set ES to 0000h. es:[0*4] is the IP half of the vector of type 0, that is, the very start of the table. The third line writes the offset of the div_err label there, and the fourth line writes CS to 0000:0002h. Before the program, the vector pointed to the emulator's default routine; in this trace the old value is taken to be F000:1000h. In this short example the old vector is not saved. In a real program it is saved and restored before exit.

Let us count the offsets: mov ax, 0 is 3 bytes, mov es, ax 2, the two vector writes 7 and 5, mov ax, 100 3, mov bl, 0 2, div bl 2, mov dl, al 2 and ret 1 byte. So div bl is at 0116h, mov dl, al at 0118h and the div_err label at 011Bh.

Table 5.1.10: Trace of the program with our own INT 0 handler (state after each line executes).
LineInstructionAXBLDLCS:IP (next)SPIFVector 0 / stack
2mov ax, 00000h00h00h0700:0103FFFEh1F000:1000
3mov es, ax0000h00h00h0700:0105FFFEh1F000:1000
4mov … [0*4], offset div_err0000h00h00h0700:010CFFFEh1F000:011B
5mov … [0*4+2], cs0000h00h00h0700:0111FFFEh10700:011B
6mov ax, 1000064h00h00h0700:0114FFFEh10700:011B
7mov bl, 00064h00h00h0700:0116FFFEh10700:011B
8div bl → INT 00064h00h00h0700:011BFFF8h0[FFF8h] = 0118h, [FFFAh] = 0700h, [FFFCh] = F202h
12mov ax, 0FFFFhFFFFh00h00h0700:011EFFF8h0stack unchanged
13iretFFFFh00h00h0700:0118FFFEh1stack emptied
9mov dl, alFFFFh00hFFh0700:011AFFFEh1—
10retFFFFh00hFFh0700:00000000h1return to DOS

The rows of Table 5.1.10 read in three phases. Lines 4–5 change the vector in two pieces. After line 4, half of the vector is new and half is old: F000:011B. This intermediate state points to no routine. In this program the intermediate state is harmless, because only the program's own DIV can trigger type 0. When the vectors of hardware interrupts are changed, however, this intermediate state is a serious danger.

In line 8, div bl divides by zero. The processor does not write the quotient and starts the type 0 interrupt. FLAGS (F202h), CS (0700h) and the return IP are pushed on the stack. The IP pushed is not the address of DIV, 0116h, but the address of the next instruction, 0118h. SP = FFF8h and IF = 0, CS:IP ← 0700:011B. AX has not changed; the dividend stays 0064h.

IVT 0000:0000h (type 00h)1B010007IPCSvector = 0700:011Bhstack (SS = 0700)FFF6····FFF80118← SPFFFA0700FFFCF202FFFE0000AXFFFFBL00DL00CS:IP0700:011EIF0
Figure 5.1.8: After div bl triggers INT 0: the vector of type 0 is 0700:011Bh, the stack holds the return IP 0118h, CS and FLAGS; IF = 0 and CS:IP is at the first instruction of the routine.

Lines 12–13 are the routine. mov ax, 0FFFFh puts an invalid marker in the result register. iret pops IP = 0118h, CS = 0700h and FLAGS = F202h; SP = FFFEh and IF = 1. The DIV does not run again. In line 9 the main program moves AL into DL with mov dl, al and learns of the error from DL = FFh. The ret on the last line takes the 0000h at the top of the stack in a .COM program and returns to DOS through the INT 20h at the start of the PSP.

The marking method in this program has a weakness. FFh can also be the result of a real division: 255 / 1 = 255. In real programs the error information is returned instead in a separate variable or in a flag, for example CF. To change CF, the ISR must modify the copy of FLAGS on the stack, because IRET restores that copy.

5.1.4.3INTO and the overflow interrupt (INT 4)

In signed addition and subtraction, OF = 1 if the result does not fit in the signed range. The processor does not raise an interrupt by itself in this case; testing OF is the program's job. INTO (interrupt on overflow) makes this test in a single byte.

Definition 5.1.6

INTO is a one-byte (CEh) instruction that calls the type 4 interrupt if OF = 1 and does nothing if OF = 0. It is written immediately after a signed addition or subtraction.

Example 5.1.5

ADD AL, BL followed by INTO runs with AL = 64h and BL = 32h. Then the same operation is repeated with BL = F6h. In each case, what are AL, OF and CF, and is INT 4 called?

  1. 64h + 32h = 96h. In the unsigned reading, 100 + 50 = 150 ≤ 255; there is no carry, CF = 0. In the signed reading, the sum of two positive numbers is +150, which exceeds +127. The top bit of 96h is 1; the result looks like −106. OF = 1 and INTO calls INT 4. AL stays 96h; INTO does not correct the result.
  2. 64h + F6h = 15Ah; AL = 5Ah and CF = 1. In the signed reading +100 + (−10) = +90 is correct; the sum of two numbers of different signs cannot overflow: OF = 0. INTO does nothing. CF = 1 does not affect INTO.

Running the two cases in emu8086 gives the same result: in the first the INT 4 routine runs, in the second it does not.

The cost of INTO is small: with OF = 0 it takes only 4 clock cycles. A program that does signed arithmetic can therefore put an INTO after every important operation and catch overflows in a central routine. In practice, though, DOS does not install a meaningful routine for INT 4. The default vector often points to an empty routine consisting only of IRET. A program that is going to use INTO must install its own INT 4 routine.

Common mistake

Assuming that INTO looks at CF. INTO looks only at OF; an unsigned overflow (CF = 1) does not trigger INTO. A program that works with unsigned numbers catches overflow with JC, not with INTO.

5.1.4.4Single step (INT 1)

The most effective way to find a bug in a program is to execute it instruction by instruction and look at the registers after each one. The 8086 supports this in hardware. While the trap flag TF, bit 8 of the FLAGS register, is 1, the processor raises the type 1 interrupt after every instruction. The INT 1 routine, which is part of the debugger, prints the registers on the screen and waits for the user to press a key. It then returns to the program with IRET, the program executes one more instruction, and the cycle repeats.

There is no instruction that changes TF directly. CLC/STC, CLD/STD and CLI/STI have no counterpart for TF. TF is changed through the stack: FLAGS is pushed, popped into a register, bit 8 is set, and the value is loaded back into FLAGS.

PUSHF
POP  AX
OR   AH, 01h      ; bit 8 = TF
PUSH AX
POPF              ; TF = 1

If FLAGS = F202h at the start, then after PUSHF and POP AX AX = F202h. Bit 0 of AH is bit 8 of FLAGS; OR AH, 01h makes AX F302h. POPF loads this value into FLAGS and TF = 1. To clear TF, the same sequence is written with AND AH, 0FEh.

There is a subtle but important point here. The INT 1 routine is also a sequence of instructions. If every instruction of this routine also raised INT 1 while TF = 1, the routine would interrupt itself forever. What prevents this is the second of the INT n steps: on entering an interrupt, the processor pushes FLAGS on the stack and clears TF. The INT 1 routine runs with TF = 0, so its own instructions are not single-stepped. When the routine returns with IRET, the copy of FLAGS on the stack restores TF = 1 and tracing continues.

The single-step interrupt has the lowest priority of all interrupts (Table 5.1.12). If another request is also waiting at the same instruction boundary, that one is serviced first.

5.1.4.5Breakpoint (INT 3)

Single stepping is too slow for stopping at every instruction of a long program. Often you want the program to run at full speed up to a certain point and stop there. This point is called a breakpoint. On the 8086 breakpoints are set with INT 3.

INT 3 has a special one-byte encoding: CCh. Written in the general INT n form it would be the two-byte CD 03. A debugger sets and removes a breakpoint in four steps:

  1. It saves the first byte of the instruction to stop at and writes CCh in its place.
  2. The program runs at full speed. When that address is reached, CCh, that is INT 3, executes. FLAGS, CS and the address after INT 3 are pushed on the stack; the debugger's INT 3 routine shows the registers.
  3. The debugger writes the saved byte back and decreases the return IP on the stack by 1. The return address then becomes the address where CCh was, that is, where the original instruction starts.
  4. With IRET the original instruction is executed from the beginning, undamaged.

The reason for the one-byte encoding lies in the first step. The shortest instructions of the 8086 are a single byte: INC AX, PUSH BX, CLC and so on. If the two-byte CD 03 were written in place of such an instruction, the second byte would corrupt the first byte of the next instruction. If the program reached that next instruction by a jump, a corrupted instruction would now be executed. CCh, on the other hand, fits in place of the first byte of any instruction and affects only that instruction. Decreasing the return IP by 1 also depends on INT 3 being a single byte.

The "single step" button of emu8086 does the same job inside the emulator. On a real 8086 system, DOS's DEBUG program and similar tools work by installing their own routines on the INT 1 and INT 3 vectors.

Common mistake

Taking the CCh bytes for the program's own instructions when the code of a program running under a debugger is dumped from memory. At addresses where a breakpoint is set, CCh temporarily sits in memory. If the program reads its own code or computes a checksum, it may find a different result under the debugger.

5.1.5Hardware interrupts

5.1.5.1The INTR and NMI pins

External devices send interrupt requests to the 8086 over two pins. The behavior of the two pins differs from the way they are triggered to the way the type number is determined.

INTR (pin 18) is the maskable interrupt request input. It is level-triggered: the processor samples the pin during the last clock cycle of each instruction and sees the request if the pin is 1 at that moment. If IF = 0 the request is ignored; if the pin stays at 1 it is seen as soon as IF = 1. The type number is not fixed inside the processor. When the processor accepts the request, it produces two pulses on the INTA̅ output (pin 24, interrupt acknowledge) and reads the type number from the data bus. This arrangement makes it possible to connect many devices behind a single INTR pin; each device can be given a different type number.

NMI (pin 17) is the non-maskable interrupt input. It is rising-edge triggered: the 0-to-1 transition of the pin is recorded in a latch inside the processor, so the request is not lost. IF is not consulted; it cannot be turned off with CLI. The type number is always 2, so no INTA cycle is needed and the vector is read directly from 00008h. On the IBM PC, NMI is used to report memory parity errors. Circuits that sense loss of power also use NMI to give the processor a few milliseconds to save important data before the supply fails completely.

Table 5.1.11: Comparison of INTR and NMI.
INTRNMI
Pin1817
Triggeringlevel (sampled at the end of an instruction)rising edge (latched internally)
When IF = 0held offaccepted
Type numberfrom the data bus via INTA (08h–0Fh on the PC)fixed at 2
Usekeyboard, timer, disk, serial portparity error, power loss

Level triggering has a consequence. The device must hold INTR at 1 until the processor accepts the request. If the request comes as a very short pulse and the processor is running with IF = 0 at that moment, the request is lost. On the PC, the 8259A between the devices and the processor solves this problem. The 8259A stores incoming requests in its own register and holds INTR until the request is serviced.

Common mistake

Thinking that the vector of NMI is also read with INTA. The INTA cycle is only for INTR. The type of NMI is fixed (2) and the processor does not ask outside for it. In the same way, the types of INT 0, INT 1, INT 3 and INT 4 are fixed and have nothing to do with external hardware.

5.1.5.2The INTR acknowledge sequence

Let us follow step by step the chain of events from the moment a key is pressed to the execution of the first instruction of the keyboard ISR. On the PC the keyboard controller is connected to input IRQ1 of the 8259A.

  1. The keyboard controller activates the IRQ1 line. The 8259A records the request and, if the mask allows, drives the INTR pin to 1.
  2. The 8086 finishes the instruction it is executing. Interrupts are not accepted in the middle of an instruction; the processor samples INTR only at instruction boundaries.
  3. If IF = 0 the request is held off and INTR stays at 1. If IF = 1 the request is accepted.
  4. The processor produces two INTA̅ pulses. The first tells the 8259A to "get ready". On the second pulse the 8259A puts the type number on data bus lines D0–D7; on the PC this is 09h for the keyboard.
  5. From here on it is the same as INT n: FLAGS, CS, IP are pushed on the stack; IF = TF = 0; CS:IP ← [n × 4], that is, [0000:0024h].
  6. When the ISR has read the key and finished its work, it sends the 8259A an EOI (end of interrupt) and returns with IRET.
INTR = 11instruction ends2IF = 1?3INTA̅ ×2 → 09h4pushed on stack5ISR … IRET6time
Figure 5.1.9: Timeline from an INTR request to the ISR: the request arrives, the running instruction finishes, IF is tested, the type number is read with two INTA pulses, the return information is pushed on the stack, and the ISR ends with IRET.

The fourth step in Figure 5.1.9 is the only step that separates a hardware interrupt from a software interrupt. The INTA cycle resembles a read bus cycle: the processor puts no meaningful address on the address bus, activates INTA̅ instead of RD̅, and takes the byte on the data bus. Between the two pulses, in maximum mode, the LOCK̅ signal is also held active so that no other bus master can take the bus in the meantime. Once the type number is received, the processor behaves as if there were an INT 09h instruction in the program.

The rule in the second step, that an interrupt is accepted only at an instruction boundary, is the foundation of ISR design. An instruction is never left half done. For example, while ADD [BX], AX reads and writes memory, no interrupt comes in between; the ISR always sees memory either as it was before the instruction or as it is after it. A task done by two separate instructions, however, can be interrupted between the two. This must be kept in mind for data shared by the ISR and the main program.

5.1.5.3Priority and the PC interrupt map

If several interrupt requests are waiting at the same instruction boundary, the processor decides which to look at first by a fixed order. Table 5.1.12 gives the priority order of the 8086.

Table 5.1.12: Interrupt priority order of the 8086.
RankSourceRationale
1 (highest)divide error, INT n, INTOarises from the instruction being executed; it is part of that instruction
2NMIurgent hardware event; non-maskable
3INTRordinary hardware request; can be held off by IF
4 (lowest)single step (TF)debugging; waiting costs nothing

The logic of the order is clear. An interrupt produced by an instruction itself is part of that instruction's execution and is handled first. Among external requests, NMI comes before INTR because it is an urgent event that a program cannot turn off. Single step is for a person to look at the registers; waiting a few microseconds costs nothing.

This priority is among the processor's own inputs. The priority of the eight devices behind INTR relative to one another is decided by the 8259A. In the PC's standard setting IRQ0 has the highest priority and IRQ7 the lowest. Table 5.1.13 gives the hardware interrupts of the IBM PC. At boot the BIOS programs the 8259A so that IRQ0 gets type 08h; the type of IRQ n is therefore 08h + n.

Table 5.1.13: IBM PC hardware interrupts (type = 08h + IRQ number).
IRQDeviceTypeVector address
0timer (18.2 Hz)08h00020h
1keyboard09h00024h
3 / 4serial ports (COM2 / COM1)0Bh / 0Ch0002Ch / 00030h
6floppy disk0Eh00038h
7printer0Fh0003Ch

The timer's 18.2 Hz frequency comes from an interesting calculation. The PC's 8253 timer chip is fed by a 1,193,182 Hz clock. When the counter is run with the largest divisor, 65,536, the output frequency is 1,193,182 / 65,536 ≈ 18.2 Hz. That means an INT 08h about every 55 ms. The BIOS uses this interrupt to count the time of day.

The keyboard example also shows the division of labor between a hardware interrupt and a software interrupt. When a key is pressed, the hardware interrupt INT 09h runs first. This ISR reads the key's code from the keyboard controller and puts it into the BIOS keyboard buffer. When a program wants to read a key, it calls the software interrupt INT 16h; INT 16h reads from this buffer. This way the user can press keys even while the program is busy. The keys wait in the buffer and are taken in order when the program is ready. The details of the buffer and the INT 16h services are the subject of the notes of Chapter 5.2, Interrupt Functions.

5.1.5.4The 8259A interrupt controller

The 8086 has a single INTR pin, while the PC has at least six interrupt sources. The chip that gathers these sources onto one pin, sets a priority order among them and gives the processor the right type number is the 8259A.

Definition 5.1.7

The programmable interrupt controller (8259A) is a chip that puts eight interrupt request inputs (IRQ0–IRQ7) into a priority order, masks them, and places the corresponding type number on the data bus during the processor's INTA cycle. On the PC it is at ports 20h and 21h.

Inside the 8259A are three registers, each eight bits wide with each bit corresponding to one IRQ (Figure 5.1.10).

IRQ0–7IRR (request)IMR (mask)priority +ISR (in service)INTRport 21h: bit = 1 → that IRQ blockedEOI: port 20h ← 20hpending requestsINTA: the 8259A puts the type number (base + IRQ no.) on the data bus
Figure 5.1.10: Inside the 8259A. Requests IRQ0–7 are written to the IRR, those masked in the IMR are filtered out, the priority resolver selects the highest-priority request and drives INTR. During INTA the type number (base + IRQ no.) is put on the data bus and the request's bit moves to the ISR register.
  • IRR (interrupt request register): holds requests that have arrived but have not yet been serviced. When an IRQ line becomes active, the corresponding bit becomes 1.
  • IMR (interrupt mask register): holds one mask bit for each IRQ. If the bit is 1, the request on that line is not passed on to the processor. While IF shuts off the whole INTR input, the IMR shuts off lines one by one. On the PC it is read and written at port 21h.
  • ISR (in-service register): marks the IRQ currently being serviced. During INTA the bit of the selected request moves from the IRR to the ISR. Until the EOI arrives this bit stays 1, and the same or lower-priority IRQs are held off.

The third register's name, ISR, is the same as the abbreviation of interrupt service routine. To avoid confusion, these notes say "ISR register" when speaking of the register.

EOI. The bit in the ISR register does not clear by itself. When the service routine has finished its work, it must tell the 8259A so. This notification is called end of interrupt (EOI). On the PC it is done with two instructions:

MOV AL, 20h     ; non-specific EOI command
OUT 20h, AL     ; to the 8259A's command port

This command clears the highest-priority 1 bit in the ISR register. That the port number and the command value are both 20h is a coincidence. If the EOI is forgotten, the 8259A thinks that IRQ is still in service. The same and lower-priority IRQs never reach the processor again. For example, if the EOI is forgotten in the timer ISR, then because IRQ0 has the highest priority, the keyboard, disk and serial port interrupts all stop. The system appears frozen.

Cascading. Eight inputs are sometimes not enough. 8259As can be cascaded: if a slave 8259A is connected to each input of a master 8259A, the count rises to 8 × 8 = 64 IRQs. The IBM PC/AT connects a second 8259A to input IRQ2 of the master chip. The inputs of the second chip are called IRQ8–IRQ15 and map to types 70h–77h. On the AT, IRQ8 is the real-time clock and IRQ14 is the interrupt of the hard disk.

Common mistake

Reading a 1 bit in the IMR as "interrupt allowed". The IMR is a mask register: 1 blocks, 0 allows. For IF the situation is the opposite: IF = 1 allows. To avoid mixing up the two rules, it helps to read a 1 in the IMR as "masked" and a 1 in IF as "open".

5.1.5.5Masking with the IMR: code trace

Sometimes a program needs to block the interrupt of just one device for a short time. For example, a piece of code that changes the keyboard buffer directly does not want the keyboard ISR to run in the meantime, but wants the timer to keep counting. CLI is too crude here, because it shuts off the whole INTR input. The right tool is the IMR.

org 100h
in  al, 21h        ; read the IMR
or  al, 00000010b  ; mask IRQ1
out 21h, al
mov cx, 3          ; critical work
in  al, 21h
and al, 11111101b  ; unmask IRQ1
out 21h, al
ret

The program applies the read–modify–write pattern twice. Only one bit of the IMR is to be changed; the other seven bits are the settings of other programs, the BIOS or the operating system. So the IMR is read first, the wanted bit is set with OR or cleared with AND, and the result is written back. Writing MOV AL, 02h / OUT 21h, AL directly would mask IRQ1, but it would unmask all the other IRQs.

In the trace the initial value of the IMR is taken, as an example, to be B8h: 1011 1000b. In this value IRQ3, 4, 5 and 7 are masked; IRQ0 (timer), IRQ1 (keyboard), IRQ2 and IRQ6 (floppy disk) are enabled.

Table 5.1.14: Trace of the program that masks IRQ1 with the IMR (IMR initially B8h).
LineInstructionAL (binary)ALCXIMRIRQ1
2in al, 21h1011 1000B8h0000hB8henabled
3or al, 00000010b1011 1010BAh0000hB8henabled
4out 21h, al1011 1010BAh0000hBAhmasked
5mov cx, 31011 1010BAh0003hBAhmasked
6in al, 21h1011 1010BAh0003hBAhmasked
7and al, 11111101b1011 1000B8h0003hBAhmasked
8out 21h, al1011 1000B8h0003hB8henabled
9ret1011 1000B8h0003hB8henabled

Table 5.1.14 reads as follows. In line 2 the IMR is read: AL = B8h. In line 3 or al, 02h sets only bit 1: 1011 1000 OR 0000 0010 = 1011 1010 = BAh. The other bits are preserved. The IMR has not changed yet; only AL has. In line 4 out writes the value to the 8259A and IMR = BAh. From this moment a request on IRQ1 does not reach INTR; IF and the other IRQs are not affected.

AL1IRQ70IRQ61IRQ51IRQ41IRQ30IRQ21IRQ10IRQ0BAhIMR10111010BAhtimerkeyboardCOM2COM1floppyprinterred = masked (1) · port 21h = IMR
Figure 5.1.11: The AL and IMR bits after out 21h, al: both are BAh. The masked bits (1) are IRQ3, 4, 5, 7 and the newly masked IRQ1; IRQ0, IRQ2 and IRQ6 are enabled.

Line 5 stands in for the work that must not be interrupted. If the keyboard is pressed in the meantime, the request is not lost: the 8259A stores it in the IRR. Lines 6–8 remove the mask with the same pattern. With and al, 0FDh, the mask 1111 1101b clears only bit 1: 1011 1010 AND 1111 1101 = 1011 1000 = B8h. With out the IMR becomes B8h again. If a keyboard request is waiting in the IRR, it now reaches INTR and is serviced. In line 9 the program returns; the mask is back to its original state and nobody else's bits have been touched.

The difference between the IMR and CLI is plain in this trace. CLI holds off all maskable interrupts; the timer's pulses wait too, and the clock may fall behind. The IMR holds off only the selected device. The price is that access to the IMR takes two IN/OUT instructions and, because it writes to an I/O port, is slower than CLI.

Common mistake

Writing to the IMR without reading it first: MOV AL, 02h and OUT 21h, AL. These two lines mask IRQ1 but unmask IRQ3, 4, 5 and 7. If a device with no ISR installed is connected to those lines, the first request that arrives sends the processor to a meaningless vector.

5.1.5.6When an interrupt is held off

The 8086 accepts an interrupt only at instruction boundaries. In some cases this boundary is deliberately moved forward by one instruction. Table 5.1.15 collects these cases.

Table 5.1.15: Situations in which INTR is not accepted immediately.
SituationBehaviorReason
in the middle of an instructionthe request waits until the running instruction finishesso that no instruction is left half done
prefixes (LOCK, REP, segment prefix)no interrupt is accepted between a prefix and its instructionthe prefix is part of the instruction
after MOV SS, … or POP SSno interrupt arrives until the next instruction has also finishedso that the following MOV SP, … completes safely
after STIone more instruction executes, then the interrupt is acceptedso that no interrupt slips between STI / IRET or STI / HLT
string instruction with REPcan be interrupted between iterations; after IRET it continues for the remaining CXso that a long copy does not increase the delay
HLT and WAITINTR or NMI wakes the processorthe wait ends with an interrupt

After SS is loaded. Moving the stack takes two instructions: MOV SS, AX and MOV SP, 0FFFEh. If an interrupt arrived between the two, the processor would push FLAGS, CS and IP at the address given by the new SS and the old SP. This address is most likely on top of some other data. For this reason the 8086 postpones interrupts by one instruction after every instruction that writes a segment register. For this to work safely, MOV SP must be written immediately after MOV SS.

After STI. STI enables interrupts not immediately but after the instruction following it has finished. This small delay makes two common patterns safe. The first is the STI / IRET sequence at the end of an ISR: a new interrupt cannot arrive before IRET finishes and the stack is emptied. The second is the STI / HLT sequence. The program wants to say "enable interrupts and wait until an interrupt arrives". If an interrupt slipped in between STI and HLT, the ISR would run and return, and HLT would wait needlessly until the next interrupt.

String instructions with REP. A copy of 60,000 bytes with REP MOVSB takes hundreds of thousands of clock cycles. Interrupts cannot be allowed to wait for all that time. The 8086 therefore can interrupt a REP instruction between iterations. The return address pushed on the stack is the address of the REP prefix; SI, DI and CX hold the progress so far. After IRET the instruction restarts and runs for the remaining CX iterations. This scheme has a flaw specific to the 8086: on return from an interrupt the processor remembers only one prefix. If an instruction with two prefixes such as REP ES: MOVSB is interrupted, the segment prefix is lost on return and the copy continues from the wrong segment. For this reason such a line is put between CLI and STI, or written so that no segment prefix is needed.

HLT and WAIT. HLT halts the processor. INTR (with IF = 1) or NMI wakes the processor; the ISR runs and IRET returns to the instruction after HLT. This is the most economical way of writing a main program as "sleep until something happens". WAIT waits for the 8087 coprocessor to finish its work; an interrupt that arrives during this wait is also accepted.

Common mistake

Loading SP first and then SS when moving the stack, or putting another instruction between the two. The postponement protects only the one instruction after the one that writes a segment register. The correct order is MOV SS, AX followed immediately by MOV SP, …; the safest approach is to put these two lines between CLI and STI as well.

5.1.5.7Interrupt latency

When a device requests an interrupt, the ISR is expected to start running at once. In reality this time is not zero and for some devices it is bounded.

Definition 5.1.8

Interrupt latency is the time between the arrival of an interrupt request and the start of the first instruction of the ISR.

Latency has two parts. The first is waiting for the instruction that is running when the request arrives to finish. The second is the acceptance process itself: the INTA cycles, three stack writes, two vector reads and refilling the queue. Table 5.1.16 gives the relevant times.

Table 5.1.16: Clock cycle counts of interrupt-related operations on the 8086 (8086 manual).
OperationClock cyclesTime at 5 MHz
INT n5110,2 µs
INT 35210,4 µs
INTO (OF = 1 / OF = 0)53 / 410,6 / 0,8 µs
INTR acceptance (including two INTA)6112,2 µs
IRET244,8 µs
16-bit IDIV (register)165–18433–36,8 µs
Example 5.1.6

On a 5 MHz 8086 an INTR arrives just after a 16-bit IDIV has started. What is the worst-case interrupt latency in clock cycles and in µs? What would it be if the processor ran at 8 MHz?

  1. In the worst case the running instruction must finish: IDIV takes at most 184 cycles.
  2. Then the acceptance process: 61 cycles. The total is 184 + 61 = 245 cycles.
  3. At 5 MHz a clock cycle is 1 / 5 MHz = 200 ns. 245 × 200 ns = 49 µs.
  4. At 8 MHz a cycle is 125 ns: 245 × 125 ns ≈ 30.6 µs.

If the program had turned interrupts off with CLI at that moment, the time spent with them off adds directly to this latency. A 100 µs CLI–STI interval raises the worst-case latency to about 149 µs at 5 MHz.

What these numbers mean depends on the device. For the timer interrupt, which arrives 18.2 times per second, 49 µs is negligible; there are 55 ms between two interrupts. A serial port is different. Characters arriving at 9600 bit/s are about 1.04 ms apart, and at 115,200 bit/s about 87 µs apart. With a serial port controller that has a one-character buffer, the ISR must read the previous character before the next one arrives. If the latency plus the ISR's running time exceeds this interval, a character is lost.

This calculation gives directly the two basic rules of ISR writing. First, the CLI–STI interval must be kept short, because this time adds to the latency of all devices. Second, the ISR itself must be kept short. While an ISR runs, IF = 0 and the same or lower-priority IRQs wait until the EOI. A long ISR has the same effect on all the other devices as a long CLI.

The share of the processor an ISR takes can also be computed. Suppose the timer ISR takes 200 clock cycles. Running 18.2 times per second, it spends 200 × 18.2 = 3640 cycles. That is only 0.07% of the 5,000,000 cycles per second of a 5 MHz processor. The advantage of interrupts over polling is clear in this figure.

5.1.6Writing our own interrupt service routine

5.1.6.1Installing a vector: INT 90h

Installing an interrupt service routine takes three jobs: writing the routine, choosing an unused type, and writing the routine's address into that type's vector. The following program does these three jobs in the simplest form and calls its own interrupt once.

org 100h
mov ax, 0
mov es, ax                         ; ES = 0: IVT segment
cli                               ; interrupts off
mov word ptr es:[90h*4], offset isr ; IP
mov word ptr es:[90h*4+2], cs        ; CS
sti                               ; interrupts on
int 90h                           ; our own interrupt
ret
isr:
mov ah, 0Eh
mov al, '*'
int 10h
iret                              ; not RET!

Every decision in the program has a reason.

  • Choice of type. 90h is a type that neither the BIOS nor DOS uses on the PC. Its vector is at address 90h × 4 = 240h; IP is at 0000:0240h–0241h and CS at 0000:0242h–0243h.
  • ES = 0. The vector table is in segment 0000h. Since DS points to the program's own data, the table is accessed through ES, with the es: prefix. Because an immediate value cannot be loaded into a segment register, 0 is put into AX first.
  • CLI / STI. The vector is written as two words with two separate MOVs. After the first MOV, the IP half of the vector is new and the CS half is old. If an interrupt of this type arrived at that moment, the processor would jump to a meaningless address. CLI holds off maskable interrupts during this short interval. Since only the program itself calls type 90h, there is no danger in this example; but for hardware types the same pattern is mandatory, and applying it every time a vector is written is a good habit.
  • The end of the ISR. The ISR writes an asterisk to the screen with the BIOS INT 10h teletype service and returns with IRET. Another software interrupt can be called from inside an ISR; with nested interrupts, 6 more bytes are added to the stack for each level.

When the program runs, * is printed on the screen and the program returns to DOS. This short example does not save and restore the old vector. After the program ends, the vector of type 90h keeps pointing to memory into which another program will now be loaded. If another program calls INT 90h, the random bytes there are executed as instructions. The correct form, which saves and restores the old vector, is traced separately below.

Under DOS, instead of writing vectors directly in memory, two DOS services can be used: INT 21h with AH = 25h sets a vector and AH = 35h reads one. These services manage interrupts themselves while a vector is written and make the operating system aware of the vectors. That makes this the safer way. The register layout of the services is given in the notes of Chapter 5.2, Interrupt Functions; here the direct-write method is used to show how the vector table works.

5.1.6.2Our own ISR on INT 60h: code trace

A slightly different form of the same arrangement passes a parameter to the ISR in a register. The main program puts the character to be written in AL; the ISR only prepares AH and calls INT 10h. Type 60h, which is reserved for user programs, is used.

org 100h
mov ax, 0
mov es, ax           ; ES = 0: IVT
cli
mov word ptr es:[60h*4], offset isr
mov word ptr es:[60h*4+2], cs
sti
mov al, '#'
int 60h              ; our own interrupt
ret
isr:
mov ah, 0Eh
int 10h
iret

The offsets are as follows: mov ax, 0 0100h, mov es, ax 0103h, cli 0105h, the two vector writes 0106h and 010Dh, sti 0112h, mov al, '#' 0113h, int 60h 0115h, ret 0117h and isr 0118h. The vector is at address 60h × 4 = 180h.

Table 5.1.17: Trace of the INT 60h program (state after each line executes; SS = 0700h).
LineInstructionAXESCS:IP (next)SPFLAGSIVT 0180h–0183h / stackScreen
2mov ax, 00000h0700h0700:0103FFFEhF202h?? ?? ?? ??
3mov es, ax0000h0000h0700:0105FFFEhF202h?? ?? ?? ??
4cli0000h0000h0700:0106FFFEhF002h?? ?? ?? ??
5mov … [60h*4], offset isr0000h0000h0700:010DFFFEhF002h18 01 ?? ??
6mov … [60h*4+2], cs0000h0000h0700:0112FFFEhF002h18 01 00 07
7sti0000h0000h0700:0113FFFEhF202h18 01 00 07
8mov al, '#'0023h0000h0700:0115FFFEhF202h18 01 00 07
9int 60h0023h0000h0700:0118FFF8hF002h[FFF8h] = 0117h, [FFFAh] = 0700h, [FFFCh] = F202h
12mov ah, 0Eh0E23h0000h0700:011AFFF8hF002hstack unchanged
13int 10h0E23h0000h0700:011CFFF8hF002hstack unchanged#
14iret0E23h0000h0700:0117FFFEhF202hstack emptied#
10ret0E23h0000h0700:00000000hF202hreturn to DOS#

Table 5.1.17 divides into four phases. Preparation (lines 2–3). ES is initially 0700h, like the other segment registers of a .COM program. After mov es, ax, ES = 0000h and es:[180h] now points to byte 0000:0180h in the vector table. The value of these four bytes of the table before the program is unknown; it is shown as "??" in the trace.

Writing the vector (lines 4–7). cli clears IF and FLAGS drops from F202h to F002h. Line 5 writes offset isr = 0118h to the IP half; in memory, in little-endian order, 18 01 is seen. Line 6 writes 0700h to the CS half: 00 07. The vector is now 0700:0118. With sti, IF = 1 and FLAGS = F202h. Because bit 1 and bits 12–15 of FLAGS on the 8086 are always 1, IF alone makes a difference of 0200h.

The interrupt (lines 8–9). mov al, '#' puts 23h in AL. This value is the parameter passed to the ISR in a register. int 60h pushes FLAGS (F202h), CS (0700h) and the return IP 0117h on the stack. INT 60h starts at 0115h and is two bytes; the return address is 0117h. IF = 0 and CS:IP is loaded as 0700:0118 from the vector at 0000:0180h.

IVT 0000:0180h (type 60h)18010007IPCSvector = 0700:0118hstack (SS = 0700h)FFF80117h← SPFFFA0700hFFFCF202hFFFE0000hCS:IP (next)0700:0118FLAGSF002hIF = 0screen:
Figure 5.1.12: After int 60h executes: the vector of type 60h is 0700:0118h, the stack holds the return IP 0117h, CS and FLAGS; SP = FFF8h, IF = 0 and CS:IP is at the first instruction of the ISR.

The ISR and the return (lines 12–14 and 10). In the ISR, mov ah, 0Eh makes AX 0E23h. AH = 0Eh selects the BIOS teletype service; the character in AL will be written. int 10h writes # on the screen. This is a second interrupt called from inside an interrupt. The BIOS releases its own stack use, and when it returns SP is again FFF8h. iret pops IP = 0117h, CS = 0700h and FLAGS = F202h; SP = FFFEh and IF = 1. The ret in the main program returns to DOS.

Note that the ISR changes AX. The main program continues after the interrupt with AX = 0E23h. In this program AL is passed to the ISR as a parameter on purpose, so the change in AX causes no problem. But if the ISR were attached to a hardware interrupt, the main program would suddenly find AH equal to 0Eh. An ISR of this kind must save every register it uses.

5.1.6.3Save, replace and restore a vector: code trace

What the previous two programs lack is that they change the table and leave it that way. A correct program first saves the old vector and restores it when done. The following program does this for type 3 and also shows how the ISR protects the main program's registers.

org 100h
xor ax, ax
mov es, ax          ; ES = 0: IVT
mov ax, offset isr3
xchg ax, es:[3*4]   ; new IP ↔ old
mov old_vec, ax
mov ax, cs
xchg ax, es:[3*4+2] ; new CS ↔ old
mov old_vec+2, ax
mov ax, 1234h
int 3               ; our ISR
mov bx, old_vec
mov es:[3*4], bx    ; restore
mov bx, old_vec+2
mov es:[3*4+2], bx
ret
isr3: push ax
mov ax, 0E21h       ; AH=0Eh, AL='!'
int 10h
pop ax
iret
old_vec dw ?, ?

The new element in the program is the XCHG instruction. xchg ax, es:[3*4] swaps AX with the word in memory in a single instruction: while the new IP is written to memory, the old IP comes into AX. If the read and the write were done with two separate MOVs, a gap of two instructions would remain between them. With XCHG it is impossible for the new value to be written without the old one being read, or for the old value to be lost before it is read. The old vector is saved in a two-word variable named old_vec. xor ax, ax zeroes AX; it is one byte shorter than MOV but changes the flags: ZF = 1 and PF = 1. That is why FLAGS is F246h in this program.

The type 3 vector before the program is F000:1003h: emu8086 sets the default vector for each type n to F000:(1000h + n) (F000:1000h for type 0). On a real PC this value varies with the BIOS and any debugger that is loaded; the correctness of the program does not depend on it. The offsets: int 3 is at 011Ch and is one byte, isr3 is at 0130h, old_vec at 0138h.

Table 5.1.18: Trace of the program that saves, replaces and restores the vector (SS = 0700h).
LineInstructionAXBXType 3 vectorCS:IP (next)SPIFStack / output
2–3xor ax, ax / mov es, ax0000h0000hF000:10030700:0104FFFEh1—
4mov ax, offset isr30130h0000hF000:10030700:0107FFFEh1—
5xchg ax, es:[3*4]1003h0000hF000:01300700:010CFFFEh1—
6mov old_vec, ax1003h0000hF000:01300700:010FFFFEh1old_vec = 1003h
7mov ax, cs0700h0000hF000:01300700:0111FFFEh1—
8xchg ax, es:[3*4+2]F000h0000h0700:01300700:0116FFFEh1—
9mov old_vec+2, axF000h0000h0700:01300700:0119FFFEh1old_vec+2 = F000h
10mov ax, 1234h1234h0000h0700:01300700:011CFFFEh1—
11int 31234h0000h0700:01300700:0130FFF8h0[FFF8h] = 011Dh, [FFFAh] = 0700h, [FFFCh] = F246h
17push ax1234h0000h0700:01300700:0131FFF6h0[FFF6h] = 1234h
18mov ax, 0E21h0E21h0000h0700:01300700:0134FFF6h0—
19int 10h0E21h0000h0700:01300700:0136FFF6h0output: !
20pop ax1234h0000h0700:01300700:0137FFF8h0—
21iret1234h0000h0700:01300700:011DFFFEh1stack emptied
12–13mov bx, old_vec / mov es:[3*4], bx1234h1003h0700:10030700:0126FFFEh1—
14–15mov bx, old_vec+2 / mov es:[3*4+2], bx1234hF000hF000:10030700:012FFFFEh1—
16ret1234hF000hF000:10030700:00000000h1return to DOS

The first phase of Table 5.1.18 is changing the vector. In line 5 XCHG writes the new IP (0130h) to the table and brings the old IP (1003h) into AX. The vector is then F000:0130: half new, half old. In line 8 the second XCHG writes the new CS (0700h) and brings the old CS (F000h) into AX. The vector is now 0700:0130, and the old vector F000:1003 is saved in the variable old_vec. Because only the program calls type 3, CLI was not needed in this example. When the vector of a hardware type is changed, these lines are put between CLI and STI.

The second phase is the interrupt. In line 10 AX = 1234h; this is the main program's value that must be protected. In line 11 int 3 is a single byte (CCh). FLAGS (F246h), CS (0700h) and the return IP 011Dh are pushed on the stack. The return address is 011Ch + 1 = 011Dh; the one-byte nature of INT 3 is visible here as well. CS:IP ← 0700:0130.

IVT 0000:000Ch (type 03h)30010007IPCSvector = 0700:0130hstack (SS = 0700)FFF61234← SPFFF8011DFFFA0700FFFCF246FFFE0000AX1234BX0000CS:IP0700:0131IF0output:
Figure 5.1.13: After the ISR's first instruction push ax: there are four words on the stack. At the bottom the FLAGS, CS and IP pushed by the interrupt, on top the AX = 1234h saved by the ISR; SP = FFF6h.

The third phase is the ISR. In line 17 the ISR first pushes the AX it will use: SP = FFF6h and [FFF6h] = 1234h (Figure 5.1.13). Lines 18–19 write ! on the screen with AX = 0E21h. In line 20 pop ax restores 1234h; SP = FFF8h and the top of the stack is again the IP pushed by the interrupt. At this point the number of PUSHes and POPs must be equal. If they were not, IRET would take the wrong words for the return address. In line 21 iret pops IP = 011Dh, CS = 0700h and FLAGS = F246h; SP = FFFEh and IF = 1.

The last phase is the restoration. Lines 12–15 write the two words in the old_vec variable back to the table. Here too the vector passes for a moment through a meaningless intermediate value such as 0700:1003. In line 16, when the program returns, AX = 1234h is preserved and the vector table is as it was before the program. This is what it means for a program to exit without leaving a trace in the vector table.

Common mistake

Forgetting to restore the vector on every exit path of the program. If the program restores only at its normal end, but returns early to DOS in an error case, the vector points to code that is no longer loaded. The next INT 3 or hardware interrupt crashes the system. The restoration code must be placed at a single point through which all the program's exits pass.

5.1.6.4Rules for writing an ISR

The previous traces brought out the rules of ISR writing one by one. Table 5.1.19 collects these rules and the symptoms that appear when they are not followed.

Table 5.1.19: Rules for writing an ISR and the problems that appear when they are ignored.
RuleIf ignored
Every register used is protected with PUSH/POP (the processor protects FLAGS).The main program continues with a register whose value has changed on its own; the bug appears at random moments.
A hardware ISR sends the 8259A an EOI: MOV AL, 20h · OUT 20h, AL.The 8259A does not clear the bit in the ISR register; the same and lower-priority IRQs never arrive again.
The ISR is kept short; long work is left to the main program through a flag variable.Interrupt latency grows and data from fast devices is lost.
INT 21h is not called from a hardware ISR.DOS is not reentrant; the data of the interrupted DOS call gets corrupted.
The vector is written with CLI or with AH = 25h, and the old one is restored on exit.After the program ends, the interrupt jumps to memory where something else now lives.
The ISR ends with IRET.The stack is off by 4 bytes and IF stays off.

Protecting registers. A hardware ISR can run after any instruction of the program. It cannot be known which register the program is using at that moment. For this reason the ISR pushes every register it uses on entry and pops them in reverse order on exit. There is no need to save the flags; INT and IRET do that themselves. Segment registers must not be forgotten either. If the ISR changes DS to reach its own data, it must save DS too.

A short ISR and a flag variable. Work that takes long is not done inside the ISR. The ISR does only the urgent part: it reads the data from the device, puts it in a buffer and sets a variable to 1. The main program looks at this variable in its loop and does the long work with interrupts enabled. This pattern looks like polling, but what is polled is a variable in memory rather than a slow device, and the ISR has removed the risk of losing data.

Definition 5.1.9

A reentrant routine is one that works correctly even when it is called again before an earlier call has finished, for example because of an interrupt. To achieve this, the routine keeps its persistent state not in fixed memory cells but on the stack or in registers.

Not calling DOS. While running, DOS keeps its internal variables and its own stack in fixed memory areas. If a hardware interrupt arrives while the program is in the middle of an INT 21h call and the ISR calls INT 21h again, the second call overwrites the variables and the stack of the first. When the first call is resumed, the data are corrupted. Because DOS is not reentrant, hardware ISRs do not use DOS services. BIOS services such as INT 10h are often safer in this respect; the example ISRs above use INT 10h for this reason and are called by a software interrupt.

STI inside an ISR. An ISR starts with IF = 0. A long ISR can allow higher-priority hardware interrupts at the start of its work with STI; the 8259A already holds off the same and lower-priority IRQs until the EOI. In this case the ISR itself must also be written to be reentrant, because the interrupt of another device can run another routine in the middle of the ISR and touch the variables the ISR shares.

The skeleton of a typical hardware ISR that applies these rules is as follows. The code is written to show the order of the rules; the lines in the middle change with the device.

isr_irq:
    push ax              ; save the registers used
    push ds
    mov  ax, seg data    ; the ISR's own data segment
    mov  ds, ax
    in   al, 60h          ; get data from the device (example port)
    mov  last_code, al    ; put in the buffer / variable
    mov  ready, 1         ; flag for the main program
    mov  al, 20h          ; EOI
    out  20h, al
    pop  ds               ; restore in reverse order
    pop  ax
    iret                  ; not RET
Common mistake

Putting an EOI in an ISR called by a software interrupt. EOI is only for hardware interrupts coming from the 8259A. If the ISR of a software interrupt such as INT 60h sends an EOI, the 8259A clears the bit of some other IRQ that is in service at that moment, and the interrupt scheme of that device is disrupted.

5.1.7Exercises and solutions

The six exercises in the slides are solved here with their intermediate steps.

1. At which physical addresses is the INT 13h vector located?

13h × 4 = 4Ch (decimal: 19 × 4 = 76). The vector is in bytes 0004Ch–0004Fh. IP is at 0004Ch–0004Dh and CS at 0004Eh–0004Fh.

2. If SP = FFFEh before INT 21h runs, what is SP inside the ISR? What is on the stack?

INT pushes three words, 6 bytes: FFFEh − 6 = FFF8h. At the top of the stack, at [FFF8h], is the return IP; at [FFFAh], CS; at [FFFCh], FLAGS. The copy of FLAGS on the stack carries IF = 1; the FLAGS in the register has IF = TF = 0.

3. With IMR = B8h, write the instructions that also mask IRQ0 (the timer) alone. What does the IMR become?

The read–modify–write pattern is used: IN AL, 21h · OR AL, 01h · OUT 21h, AL. 1011 1000 OR 0000 0001 = 1011 1001 = B9h. IRQ3, 4, 5 and 7 stay masked, and IRQ0 is masked too. As long as the timer stays masked the time of day does not advance; for this reason such a mask is kept very short.

4. The vector of type 61h is to be made 0700:0120h. Which bytes are written to which physical addresses?

61h × 4 = 184h. IP is written first, then CS; both are written in little-endian order. 00184h ← 20h, 00185h ← 01h, 00186h ← 00h, 00187h ← 07h. The physical address of this ISR is 07000h + 0120h = 07120h.

5. On a 5 MHz 8086, an INTR arrives just after MUL BX (at most 133 cycles) has started. What is the maximum interrupt latency?

The MUL must finish first: 133 cycles. Then acceptance: 61 cycles. The total is 194 cycles. 194 × 200 ns = 38.8 µs ≈ 39 µs.

6. What problems does an ISR cause by ending with RET instead of IRET?

A near RET pops only IP. CS and FLAGS stay on the stack and SP is off by 4 bytes. Because FLAGS is not restored, IF stays 0 and maskable interrupts are never accepted again. If the ISR is in another segment, CS is also left wrong and the program continues in the wrong segment. The first RET or POP afterwards takes the CS left on the stack for data or a return address. All of these cases are seen in the trace of the ISR that ends with RET.

5.1.8Summary

  • An interrupt makes the processor drop its current work at an instruction boundary, run an interrupt service routine (ISR), and return to where it left off with IRET. The interrupted program does not notice that it was interrupted.
  • In polling the processor keeps asking the device and wastes most of its time; with an interrupt the device alerts the processor when it is ready. The price of interrupts is the vector table, stack and ISR machinery.
  • Interrupts come from three sources: software (INT n, INT 3, INTO), hardware (INTR, NMI) and internal (divide error INT 0, single step INT 1). Once the type number is determined, all three follow the same steps.
  • The interrupt vector table is at 00000h–003FFh: 256 types × 4 bytes. The vector of type n is at address n × 4; the low word is IP, the high word is CS, and both are stored little-endian.
  • INT n: FLAGS is pushed, IF = TF = 0, CS and IP are pushed (SP − 6), CS:IP ← vector. The IP pushed is the address of the instruction after INT. IRET pops IP, CS and FLAGS; IF and TF return to their old values.
  • Ending an ISR with RET shifts the stack by 4 bytes and leaves IF off; RETF does not pop FLAGS either. ISRs always end with IRET.
  • A divide error occurs both when the divisor is zero and when the quotient does not fit in the destination. The 8086 pushes the address of the instruction after DIV. INTO calls INT 4 only when OF = 1. While TF = 1, INT 1 is raised after every instruction; TF is changed through the stack. INT 3 is a single byte (CCh) and is used for breakpoints.
  • INTR is level-triggered, accepted only when IF = 1 and at an instruction boundary; the type number is read from the 8259A on the second INTA pulse. NMI is rising-edge triggered, non-maskable, and always type 2.
  • Priority: divide error / INT n / INTO, then NMI, then INTR, and last single step. On the PC the type of IRQ n is 08h + n; timer 08h, keyboard 09h.
  • In the 8259A, the IRR holds pending requests, the IMR holds the masks (port 21h, bit 1 = blocked), and the ISR register holds the IRQ in service. A hardware ISR sends an EOI at its end: MOV AL, 20h · OUT 20h, AL. The IMR is changed with the read–modify–write pattern.
  • After a load of SS and after STI, an interrupt is postponed by one instruction; string instructions with REP can be interrupted between iterations.
  • Interrupt latency = the remaining time of the running instruction + the acceptance time (61 cycles for INTR). Time spent with interrupts off by CLI adds to latency; the CLI–STI interval and the ISR are kept short.
  • To install your own ISR, an unused type is chosen and the vector is written between CLI/STI (or with INT 21h, AH = 25h). The old vector is saved and restored on exit. The ISR protects the registers it uses and ends with IRET.

5.1.9Key terms

  • interrupt
  • interrupt service routine (ISR)
  • polling
  • hardware / software interrupt
  • exception
  • interrupt vector
  • interrupt vector table (IVT)
  • interrupt flag (IF)
  • trap flag (TF)
  • single-step
  • breakpoint (INT 3)
  • maskable / non-maskable interrupt
  • interrupt acknowledge (INTA)
  • programmable interrupt controller (8259A)
  • interrupt mask register (IMR)
  • end of interrupt (EOI)
  • interrupt latency
  • reentrant
  • stack
  • offset
  • physical address

5.1.10Test Yourself

  1. In a memory dump the bytes A5 FE 00 F0 are seen starting at address 0000:0020h. Which type's vector is it, and which device does it belong to on the PC? What is the physical address of the ISR?

    Answer

    20h / 4 = 08h: type 08h, that is, the timer interrupt attached to IRQ0. IP = FEA5h, CS = F000h. Physical address F0000h + FEA5h = FFEA5h.

  2. Before the INT 21h at 0700:0200 runs, SP = FFF0h and FLAGS = F246h. At the first instruction of the ISR, what are SP, the three words on the stack, and FLAGS?

    Answer

    SP = FFF0h − 6 = FFEAh. [FFEAh] = 0202h (INT 21h is two bytes), [FFECh] = 0700h, [FFEEh] = F246h. In the FLAGS register IF (bit 9) is cleared: F246h − 0200h = F046h. TF is already 0.

  3. With BL = 2, what does DIV BL give for AX = 01FEh and for AX = 0200h?

    Answer

    510 / 2 = 255 = FFh fits in AL: AL = FFh, AH = 00h. 512 / 2 = 256 does not fit; INT 0 is raised even though the divisor is not zero. A quick check: in the second case AH = 02h ≥ BL = 02h.

  4. With IMR = 00h, what instruction sequence masks the timer and keyboard interrupts together? What is the new IMR? What happens if a key is pressed in the meantime?

    Answer

    IN AL, 21h · OR AL, 03h · OUT 21h, AL; the IMR becomes 03h. The request of the key that was pressed waits in the 8259A's IRR; it is serviced when the mask is lifted.

  5. On an 8 MHz 8086, an INTR arrives just after an IDIV of at most 184 cycles has started. What is the worst-case interrupt latency in µs?

    Answer

    184 + 61 = 245 cycles. At 8 MHz a cycle is 125 ns: 245 × 125 ns ≈ 30.6 µs.

  6. To move the stack, a program writes MOV SP, 0FFFEh first and then MOV SS, AX. Why is this order not safe?

    Answer

    The postponement protects only the instruction after the one that writes a segment register. An interrupt can arrive between the two instructions, that is, after MOV SP. At that moment SP is new and SS is old, and FLAGS, CS and IP are pushed to a wrong place. The correct order is MOV SS first, followed immediately by MOV SP.

  7. A hardware ISR uses BX and DX but pushes and pops only BX. What symptom is seen in the main program?

    Answer

    Because an interrupt can arrive after any instruction of the program, DX changes at moments the main program does not know about. The program usually works correctly, but gives a wrong result in the rare cases when the interrupt arrives exactly while DX is in use. The bug is hard to reproduce and looks random.

  8. A debugger has written CCh in place of a one-byte instruction at address 0150h. Which IP does INT 3 push on the stack? Why does the debugger change this value?

    Answer

    Because INT 3 is a single byte, the IP pushed is 0151h. The debugger writes the saved original byte back to 0150h and decreases the IP on the stack by 1, making it 0150h. After IRET the original instruction is executed from the beginning, undamaged.

  9. A memory parity error occurs while a program has interrupts turned off with CLI. Is the interrupt accepted? From which address is the vector read?

    Answer

    On the PC a parity error is reported through NMI. NMI is non-maskable; it is accepted even when IF = 0. Its type is fixed at 2 and the vector is read from bytes 2 × 4 = 00008h–0000Bh. No INTA cycle is performed.

5.1.11Further reading

  • Intel, The 8086 Family User's Manual (1979), the Interrupts section: interrupt types, priority order, the timing of INTR and NMI, and instruction clock cycle counts are found in this source. The values in Tables 5.1.6 and 5.1.16 are taken from it.
  • B. B. Brey, The Intel Microprocessors (8th ed.), Chapter 12: interrupts in real mode, programming and cascading the 8259A, the PC interrupt scheme.
  • A. S. Tanenbaum, Modern Operating Systems (3rd ed.): the place of interrupts in the operating system, device drivers, and the comparison of interrupts and polling.
  • R. Brown, Ralf Brown's Interrupt List: a number-by-number reference list of all BIOS, DOS and driver interrupts on the PC.

5.1.12References

  1. A. S. Tanenbaum, Modern Operating Systems, 3rd ed., Pearson, 2008.
  2. Intel, The 8086 Family User's Manual, 1979 — Interrupts section.
  3. B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009 — Chapters 6 and 12.
  4. emu8086 help documents: the "Interrupts" and "Supported interrupts" pages.
  5. R. Brown, Ralf Brown's Interrupt List (BIOS/DOS interrupt reference).