1.1 Sistemas Embutidos – Versão Modificada Interrupts and Exceptions (Traps , Aborts)
1.1Sistemas Embutidos – Versão Modificada
Interrupts
and
Exceptions (Traps , Aborts)
1.2Sistemas Embutidos – Versão Modificada
Lecture outline
Interrupt vectors
Software interrupts
Hardware interrupts
8259 Programmable Interrupt Controller
Writing your own handlers
Installing handlers
1.3Sistemas Embutidos – Versão Modificada
Why are interrupts important
Interrupts let you use the operating system (run your programs, manage your files, access your peripherals etc.)
Interrupts help peripherals “talk” to your microprocessor
Interrupts help you measure time and control the timing of certain tasks in your microprocessors
1.4Sistemas Embutidos – Versão Modificada
Interrupts from a pedagogical perspective
By learning interrupts you learn important concepts such as:
Concurrency: how your processor manages to service interrupts while your program doesn’t know anything about them and how multiple interrupts are serviced at the same time
Preemptability and priorities, how can a low priority-task be preempted by a high-priority task
Scheduling: how can we assure that both low and high-priority tasks get the service they deserve from the processor
1.5Sistemas Embutidos – Versão Modificada
Defining Interrupts on a PC
Triggers that cause the CPU to perform various tasks on demand
Three types: Software interrupts – initiated by the INT instruction in your
program Hardware interrupts – initiated by peripheral hardware Exceptions – occur in response to error states in the processor or
during debugging (trace, breakpoints etc.)
Regardless of source, they are handled the same Each interrupt has a unique interrupt number from 0 to 255. These
are called interrupt vectors. For each interrupt vector, there is an entry in the interrupt vector
table. The interrupt vector table is simply a jump table containing
segment:offset addresses of procedures to handle each interrupt These procedures are called interrupt handlers or interrupt service
routines (ISR’s)
1.6Sistemas Embutidos – Versão Modificada
Interrupções
Conceito Geral de Interrupção:
É uma maneira de tratar eventos, onde a sequência de instruções que se está executando é temporariamente interrompida de forma a executar uma outra sequência de instruções mais importante.
Eventos não programados (assíncronos ao programa) alteram a sequência do programa. São geralmente requisições de serviço por dispositivos externos (E/S).
Prog x
Estou tratando algo
ou verificando variáveis
Rotina Trata_Int
Salva Contexto
Reseta_Int
Trata_Int
Restaura Contexto
Retorna de Int
É possível gerar interrupções por software (síncronas com programa e consideradas exceções) através do uso da instrução INT n. É uma maneira alternativa de executar uma rotina, diferindo de um CALL
1.7Sistemas Embutidos – Versão Modificada
Interrupções
Maneiras de Tratar Interrupção:
1. Ignorá-la até que não haja nada mais prioritário a fazer. Isto pode ocorrer se eu estiver atendendo uma interrupção de mais alto nível e estiver com interrupções de mais baixo nível inibidas. Também pode acontecer se o programa principal inibir todas as interrupções por um certo tempo.
2. Atendo parcialmente o pedido, ou seja, ao receber Int, seto um flag ou incremento um contador para indicar que Int ocorreu e o programa principal (quando puder) vai tratar o evento.
3. Processo Interrupção Imediatamente.
1.8Sistemas Embutidos – Versão Modificada
Interrupções
Como resolver os seguintes Problemas? Enquanto estou atendendo a interrupção de uma chamada
telefônica, toca a campainha do apto. Enquanto atendo a porta, sinto um cheiro de queimado vindo da
cozinha.
Interrupções de 1 só nível Embora possam existir diversos pinos de interrupção no
microprocessador, só atendo uma nova interrupção quando terminar de atender a anterior. E se a rotina de interrupção ficar em loop?
Interrupções de Múltiplos Níveis É possível ter diversos níveis de prioridade no atendimento das
interrupções e principalmente poder atender interrupções mais prioritárias dentro das rotinas de interrupções menos prioritárias (interrupções aninhadas).
1.9Sistemas Embutidos – Versão Modificada
Interrupções no AT802051(ou similar)
Pergunta: Quando Ocorrer uma Interrupção, para que endereço devo desviar (Hardware força um CALL para onde?)?
Pergunta: Onde na Memória Fica a Rotina de Tratamento da Interrupção?
Int:
push ACC
push Status (PSW)
mov ACC, Contador
inc ACC
mov Contador, ACC
pop Status
pop ACC
reti
MEMÓRIA
Interrupt 2
8-byte data area
Interrupt 1
8-byte data area
Interrupt 0
8-byte data area
Reset Vector
0013h
000Bh
0003h
0000h
Cabe ?
Preciso salvar ACC e PSW
aqui ?
1.10Sistemas Embutidos – Versão Modificada
Interrupções AT802051
Exemplo em C para fazer o “Debounce” de um Botão, Usando Interrupções e Timer:ButInt() { // Interrompe ao Apertar botão
SetTimer (20msec); // Seta o Timer p/ atraso 20msec
ResetTimerOverflow(); //Reseta Ovf do timer
EnableTimerInt();
} // End ButInt
TImerInt() { // Interrompe qdo timer overflow
DisableTimer Int() // Inibe Interrupcao do timer
if (Button == Low) // Se botão ainda apertado
ButtonFlag = 1; // Indique que botão estava apert.
} // End TimerInt
main () { // Progr. Principal do botão
TimerSetup(); // Timer0 em modo 1, entrada /4
EnableButtonInt(); // Enable Int. do botão
while (1==1) { // Loop p/ sempre (ou outra coisa)
while (Button ==0); // Espere botão ser liberado
ButtonFlag = 0; // Resetar flag do botão
while (ButtonFlag ==0); // Espere o botão ser apertado
LED ^= 1; // Inverta o estado do LED
}
} // End main
O Problema:
R
0
5V
5V
SBotão
1.11Sistemas Embutidos – Versão Modificada
Interrupções no AT802051
Exemplo em Assembly para fazer o “Debounce” de um Botão, Usando Interrupções e Timer:
clock = 4MHz
Flags EQU 20h ; botão apertado qdo bit 0 setado
org 000h ; origem do programa na memoria
ajmp MainLine ; Desvie p/programa principal
org 003h ; codigo da interrupção zero (0)
mov TH0, #2*256/3 ; Espere 20msec p/botao ativo
setb IE.1 ; Enable Interr. Timer
clr TCON.5 ; Assegure-se overflow desligado
reti
org 00Bh ; codigo da interrupção timer 0
clr IE.1 ; Libere só interrupç. Do botão
jb P3.2, IntT0_End ; Se bot. n/apertado, n/marque
setb 0 ; Setar interrupção do botão
IntT0_End: ; Fim da Interrupção de overflow T0
reti
Org 20h ; Programa Principal
MainLine:
mov CKCON, #%00001000 ; Use ck/4 Timer0
mov TMOD, #%00000001 ; Timer0 – Int clock
; - roda em modo 1
mov TCON, #%00010001 ; Inicíe Timer 0
; Interrupções de borda
mov IE, #%10000001 ; Enable Interr. botão
MainLoop:
jnb P3.2, MainLoop ; Esp. Apertar botao
clr 0 ; Limpa flag botão
ButtonLoop:
jnb 0, ButtonLoop ; Espere setar bit
cpl P1.0 ; Inverte estado LED
ajmp MainLoop ; Espere para decr.
; na proxima vez
1.12Sistemas Embutidos – Versão Modificada
Interrupções no PC
Rotina de Tratamento de Interrupção num uP 80x86Procedure Trata_Int_M; Far; Assembler;ASM
Push Ax ; Acumulador PrincipalPush Bx ; Reg. End. Base- - - - - - - -Push Bp ; Reg. Ponteiro Base da PilhaMov Bp, SpSub SP, Tam_LocalMov Ax, Seg_Data ; Aponta Novo segmento de dadosMov Ds, AxSTI ; Enable outras Interrupções (OPCIONAL) !!!!!!Call Serve_Int_M ; Chama Rotina que serve InterrupçãoMov Sp, Bp ; Pop Bp- - - - - -Pop BxPop AxIRET
End;
NOTA: Se Trata Interrupções de Hardware não usar Rotinas de I/O nem Funções DOS pois DOS não é reentrante
1.13Sistemas Embutidos – Versão Modificada
Interrupções no PC
Funções Para Tratamento de Interrupção em Borland Pascal (C é parecido) – Apenas como exemplo
Procedure Trata_Int (Flags, CS, IP, Ax, Bx, Cx, Dx, SI, DI, DS, ES, Bp:Word): Interrupt;var - - -Begin // Salva todos os registros passados como parâmetro, mas
- - - - // pode não ser necessário salvar todosEnd;
Procedure GetIntVec // Retorna End. Especificado num vetor Int EspecificadoDeclaração: GetIntVec (IntNo: Byte; var Vector: Pointer)OBS: IntNo especifica vetor de Interrupção (0 .. .255) e o end. é retornado em vetor
Procedure SetIntVec // Associa a um vetor de Interr. Especificado o Endereço// da rotina de tratamento
Declaração: SetIntVec (IntNo: Byte; Vector: Pointer)
OBS: IntNo especifica No. do vetor (0 .. .255) e Vector especifica endereço
1.14Sistemas Embutidos – Versão Modificada
Interrupções no PC - 80x86 A - Geradas por Hardware
End (Hex) No.(Hex) Nome
0 - 3 0 Div. Por Zero
4 - 7 1 Single Step
8 - B 2 NMI
C - F 3 Overflow
14 - 17 4 Print Screen
- - - 5
24 - 27 9 Keyboard
34 - 37 D Hard Disk
38 – 3B E Floppy
3C – 3F F Printer
40 - 43 10 Video
1.15Sistemas Embutidos – Versão Modificada
Interrupções no PC - 80x86 B - Por Software – Instruçao INT n (exceções)
End (Hex) No. (Hex) Função
80 - 83 20 DOS Program Terminate
84 - 87 21 DOS Function Call
88 – 8B 22 DOS Terminate Address
- - - - - - - -
94 - 97 25 DOS Absolute Disk Read
- - - - - - - -
- - - - - - - -
A0 - FF 33 Driver de Mouse
1.16Sistemas Embutidos – Versão Modificada
Níveis de Interrupção
Os primeiros uP só Possuíam 1 nível de Interrupção, ou seja, o uP não distinguia interrupções com Diferentes Prioridades ou níveis. Caso fosse necessário usavam hardware externo. Uma das poucas exceções era o sinal de interrupção NMI (Non-Maskable Interrupt)
Como é feito no PC ? Controlador de Interrupções 8259 (antigamente era externo ao uP) Prioridade em Níveis – Nível 0 = Mais Prioritário; Nível 7 = Menos Prioritário Se UCP permitir (Enable Interrupt ou EI), interrupções podem ser atendidas dentro
de outras, obedecendo as prioridades
Prioridade Rotativa – O periférico que acabou de ser atendido passa para o fim da fila
Prioridade Especificada por Software – Neste modo não há interrupção – UCP faz “polling”
Prioridade em Níveis, mas Com Possibilidade de Liberar/Inibir níveis + baixos – (Semelhante aos microprocessadores SPARC e MC680xx)
1.17Sistemas Embutidos – Versão Modificada
Interrupções de Múltiplos Níveis
Quais os Problemas a Tratar ?
Permitir que Possa Haver Tratamento de Chamadas de Interrupção de um Certo Nível, Dentro de Uma Rotina de Interrupção, ou seja, Tratamento de Interrupções Aninhadas.
Fazer com que o Procedimento Descrito Acima Possa ser Facilmente Controlado pelo Programador
Permitir que um Sistema Possa ter Diversos Periféricos Dentro de um Mesmo Nível de Interrupção, mas com Subníveis, Fazendo com que o Sistema Possa Atender Muitos Periféricos de Forma Estruturada
1.18Sistemas Embutidos – Versão Modificada
Tratamento de Interrupções no SPARC (Estações SUN) e Processadores Similares - I
Conceito Importante: Processador tem 3 bits na PSW indicando o nível de Interrupção Atual
Passos Automáticos do Hardware numa Interrupção:
Se a Prioridade da Interrupção é Maior do que a Prioridade Corrente do uP, Desvia para Rotina da nova Interrupção, ao Final da Instrução
O Registro de Status do uP é Salvo, o Estado de Privilégio vai para Supervisor e o Nível de Prioridade do uP é Tornado Igual à Int Atendida.
O uP Busca o Valor do Vetor de Int. no Dispositivo que Interrompeu, Indicando IACK e Indicando o Nível de Int. nas linhas de Endereço. O Periférico Insere Vetor de Interrupção.
O uP Salva o PC e a PSW na Stack do Modo Supervisor
O PC é Carregado com a soma do Vetor de Interrupção e do Endereço Base. O uP Passa a Executar a Rotina de Interrupção a Partir Deste Endereço.
1.19Sistemas Embutidos – Versão Modificada
Tratamento de Interrupções no SPARC (Estações SUN) e Processadores Similares - II
Conceito Importante: Processador tem 3 bits na PSW indicando o nível de Interrupção Atual
Passos em Software numa Interrupção:
O Programador Deve Salvar o Contexto Não Salvo pelo Hardware
Caso Outras Interr. de Nível mais Baixo Devam ser Atendidas (O que não é usual), o Programador Deverá Alterar o Registro de Nível de Interrupção do uP.
O Programador Deve Ler o Registro De Estados da Interface que Causou a Interrupção e Desligá-lo.
A Rotina de Interrupção Deve Realizar as Operações Necessárias
Ao Final da Rotina de Interrupção, Deve ser Executada a Instrução de Retorno de Exceção (RTE), que Carregará de Volta o PC, a PSW, Voltando ao Nível de Interrupção Anterior
1.20Sistemas Embutidos – Versão Modificada
EXCEÇÕES – Armadilhas (Traps)
Exceções Ocorrem Quando o Processador Detecta uma Condição de Êrro (Causado por Software ou Hardware)
TRAPS – Causam um Desvio Imediato para a Rotina de Tratamento (Não Esperam o Final da Instrução) Instrução que as causou é abortada antes que mude o estado da
UCP. Êrro de Memória Exceção de Ponto Flutuante (e.g. divisão por zero) Exceçaõ de Có-Processador Instrução Ilegal Instrução Privilegiada em Modo Usuário End. Memória Não Alinhado uP SPARC e 68020 permitem reiniciar a instrução do ponto onde
parou.
1.21Sistemas Embutidos – Versão Modificada
EXCEÇÕES – Abortos
ABORTOS – Também Causam um Desvio Imediato para a Rotina de Tratamento (Não Esperam o Final da Instrução)
Não Permitem Reinício da Instrução S.O. Deve Assumir o Contrôle ( mensagem PANIC ! Do UNIX)
Exemplos: Duplo TRAP ou Outros Êrros Sérios do Hardware Duplo Bus Error Dupla Instrução Ilegal Time-Out do Barramento
1.22Sistemas Embutidos – Versão Modificada
Interrupt vectors – x86 and Pentium
The first 1024 bytes of memory (addresses 00000 – 003FF) always contain the interrupt vector table. Always. Never anything else.
Each of the 256 vectors requires four bytes—two for segment, two for offset
Memory address (hex) Interrupt function pointer
003FC4 * x000080000400000
INT 255INT xINT 2INT 1INT 0
1.23Sistemas Embutidos – Versão Modificada
Software interrupts
Essentially just function calls using a different instruction to do the calling
Software interrupts give you access to “built-in” code from BIOS, operating system, or peripheral devices
Use the INT instruction to “call” these procedures
1.24Sistemas Embutidos – Versão Modificada
The INT and IRET instructions
Syntax: INT imm8Imm8 is an interrupt vector from 0 to 255INT does the following:
Pushes flag register (pushf) Pushes return CS and IP Far jumps to [0000:(4*imm8)] Clears the interrupt flag disabling the interrupt
system
IRET is to INT what RET is to CALL Pops flag register Performs a far return
1.25Sistemas Embutidos – Versão Modificada
Things to notice
The interrupt vector table is just a big permanently located jump table
The values of the jump table are pointers to code provided by bios, hardware, the os, or eventually 291 students
Interrupt service routines preserve the flags – the state of the computer should be completely unaltered by an ISR
1.26Sistemas Embutidos – Versão Modificada
Hardware interrupts
Alert the processor of some hardware situation that needs tending to A key has been pressed A timer has expired A network packet has arrived
Same software calling protocol
Additional level of complexity with the interrupt “call” not coming from your program code
Can happen at any time during the execution of your program
1.27Sistemas Embutidos – Versão Modificada
The 80x86 interrupt interface
Device generates request signal Device supplies interrupt vector number on data bus Processor completes the execution of current
instruction and executes ISR corresponding to the interrupt vector number on the data bus
ISR upon completion acknowledges the interrupt by asserting the INTA signal
80x86 processor
Some device
INT Request (INTR)
INT Acknowledge (INTA)
Data bus
1.28Sistemas Embutidos – Versão Modificada
But wait there’s more…
The above setup could get complicated with multiple devices generating multiple interrupts connected to the same few pins on the processor
Enter the 8259 Programmable Interrupt Controller
1.29Sistemas Embutidos – Versão Modificada
The 8259 PIC
8259PIC
01234567
INTRINTAINT#
80x86
Interrupt outputs from peripheral
devices
1.30Sistemas Embutidos – Versão Modificada
The 8259 PIC
The PIC is programmed with a base interrupt vector number “0” corresponds to this base “1” corresponds to this base + 1 “n” corresponds to this base + n
For example, if the PIC is programmed with a base interrupt vector of 8, then “0” corresponds to interrupt vector 8
1.31Sistemas Embutidos – Versão Modificada
Master-Slave Configuration
Master8259
INTR
01234567
Slave8259
INTR
01234567
IRQ0IRQ1
IRQ3IRQ4IRQ5IRQ6IRQ7
IRQ8IRQ9IRQ10IRQ11IRQ12IRQ13IRQ14IRQ1580x86
Base vector is 78h
Base vector is 08h
1.32Sistemas Embutidos – Versão Modificada
Typical IRQ assignments IRQ 0: Timer (triggered 18.2/second) IRQ 1: Keyboard (keypress) IRQ 2: Slave PIC IRQ 3: Serial Ports (Modem, network) IRQ 5: Sound card IRQ 6: Floppy (read/write completed) IRQ 8: Real-time Clock IRQ 12: Mouse IRQ 13: Math Co-Processor IRQ 14: IDE Hard-Drive Controller
1.33Sistemas Embutidos – Versão Modificada
Interrupt priority
Lower interrupt vectors have higher priority
Lower priority can’t interrupt higher priority ISR for INT 21h is running
• Computer gets request from device attached to IRQ8 (INT 78h)
• INT 21h procedure must finish before IRQ8 device can be serviced
ISR for INT 21h is running• Computer gets request from Timer 0 IRQ0 (INT 8h)• Code for INT 21h gets interrupted, ISR for timer runs
immediately, INT21h finishes afterwards
1.34Sistemas Embutidos – Versão Modificada
Servicing an interrupt
Complete current instruction Preserve current context
PUSHF Store flags to stack Clear Trap Flag (TF) & Interrupt
Flag (IF) Store return address to stack
PUSH CS, PUSH IP Identify Source
Read 8259 PIC status register Determine which device (N)
triggeredinterrupt
Activate Interrupt Service Routine Use N to index vector table Read CS/IP from table Jump to instruction
Execute Interrupt Service Routine usually the handler immediately re-
enables the interrupt system (to allow higher priority interrupts to occur) (STI instruction)
process the interrupt Indicate End-Of-Interrupt (EOI) to
8259 PIC mov al, 20h out 20h, al ;transfers the contents of AL to I/O port 20h Return (IRET)
POP IP (Far Return) POP CS POPF (Restore Flags)
1.35Sistemas Embutidos – Versão Modificada
Interrupt service routines
Reasons for writing your own ISR’s to supersede the default ISR for internal hardware interrupts
(e.g., division by zero)
to chain your own ISR onto the default system ISR for a hardware device, so that both the system’s actions and your own will occur on an interrupt (e.g., clock-tick interrupt)
to service interrupts not supported by the default device drivers (a new hardware device for which you may be writing a driver)
to provide communication between a program that terminates and stays resident (TSR) and other application software
1.36Sistemas Embutidos – Versão Modificada
Interrupt vectors and the 8259 PIC
Master8259
INTR
01234567
Slave8259
INTR
01234567
IRQ0IRQ1
IRQ3IRQ4IRQ5IRQ6IRQ7
IRQ8IRQ9IRQ10IRQ11IRQ12IRQ13IRQ14IRQ1580x86
Base vector is 78h
Base vector is 08h
1.37Sistemas Embutidos – Versão Modificada
Interrupt service routines
DOS facilities to install ISRs
Restrictions on ISRs Currently running program should have no idea
that it was interrupted. ISRs should be as short as possible because lower
priority interrupts are blocked from executing until the higher priority ISR completes
Function Action
INT 21h Function 25h Set Interrupt vectorINT 21h Function 35h Get Interrupt vectorINT 21h Function 31h Terminate and stay resident
1.38Sistemas Embutidos – Versão Modificada
Interrupt Service Routines
ISRs are meant to be short keep the time that interrupts are disable and the total length
of the service routine to an absolute minimum remember after interrupts are re-enabled (STI instruction),
interrupts of the same or lower priority remain blocked if the interrupt was received through the 8259A PIC
ISRs can be interrupted ISRs must be in memory
Option 1: Redefine interrupt only while your program is running
• the default ISR will be restored when the executing program terminates
Option 2: Use DOS Terminate-and-Stay-Resident (TSR) command to load and leave program code permanently in memory
1.39Sistemas Embutidos – Versão Modificada
Installing ISRs
Let N be the interrupt to service
Read current function pointer in vector table Use DOS function 35h Set AL = N Call DOS Function AH = 35h, INT 21h Returns: ES:BX = Address stored at vector N
Set new function pointer in vector table Use DOS function 25h Set DS:DX = New Routine Set AL = N DOS Function AH = 25h, INT 21h
1.40Sistemas Embutidos – Versão Modificada
Installing ISR
Interrupts can be installed, chained, or called
Install New interruptreplace old interrupt
Chain into interruptService myCode first
Call Original InterruptService MyCode last
MyIntVector Save Registers Service Hardware Reset PIC Restore Registers IRET
MyIntVector Save Registers MyCode Restore Registers JMP CS:Old_Vector
MyIntVector PUSHF CALL CS:Old_Vector Save Registers MyCode Restore Registers IRET
1.41Sistemas Embutidos – Versão Modificada
Interrupt Driven I/O
Consider an I/O operation, where the CPU constantly tests a port (e.g., keyboard) to see if data is available CPU polls the port if it has data available or can accept data
Polled I/O is inherently inefficient
Wastes CPU cycles until event occurs
Analogy: Checking your watch every 30 seconds until your popcorn is done, or standing at the door until someone comes by
Solution is to provide interrupt driven I/O
Perform regular work until an event occurs
Process event when it happens, then resume normal activities
Analogy: Alarm clock, doorbell, telephone ring
1.42Sistemas Embutidos – Versão Modificada
Timer interrupt example
In this example we will replace the ISR for the Timer Interrupt
Our ISR will count the number of timer interrupts received
Our main program will use this count to display elapsed time in minutes and seconds
1.43Sistemas Embutidos – Versão Modificada
Timer interrupt - main proc skeleton
;====== Variables ===================; Old Vector (far pointer to old interrupt function)oldv RESW 2count DW 0 ;Interrupt counter (1/18
sec)scount DW 0 ;Second counter mcount DW 0 ;Minute counterpbuf DB 8 ;Minute counter;====== Main procedure =====..start…;----Install Interrupt Routine-----call Install ;Main program (print count values) .showcMov ax, [mcount] ;Minute Count…
call pxymov ax, [scount] ;Second Count…call pxymov ax,[count] ;Interrupt Count (1/18
sec)… call pxymov ah,1int 16h ;Check for key press jz .showc ;Quit on any key
;---- Uninstall Interrupt Routine-----call UnInst ;Restore original INT8…call mpxit
1.44Sistemas Embutidos – Versão Modificada
Timer interrupt – complete main proc
..start
mov ax, cs ;Initialize DS=CS
mov ds, ax
mov ax, 0B800h ;ES=VideoTextSegment
mov es, ax
call install ;Insert my ISR
showc:
mov ax, [mcount] ;Minute Count
mov bx, pbuf
call binasc
mov bx, pbuf
mov di,0 ;Column 0
mov ah,00001100b ;Intense Red
call pxy
mov ax,[scount] ;Second Count
mov bx,pbuf
call binasc
mov bx, pbuf
mov di,12 ;Column 6 (DI=12/2)
mov ah,00001010b ;Intense Green
call pxy
mov ax,[count] ;Int Count (1/18th sec)
mov bx,pbuf
call binasc
mov bx, pbuf
mov ah,00000011b ;Cyan
mov di,24 ;Column 12 (DI=24/2)
call pxy
mov ah,1
int 16h ;Key Pressed ?
jz showc
Call UnInst ;Restore original INT8
mov ax,4c00h ;Normal DOS Exit
int 21h
1.45Sistemas Embutidos – Versão Modificada
Timer interrupt – PXY and Install interrupt
;pxy (bx = *str, ah = color, di = column)pxy
mov al, [bx]cmp al, ‘$'je .pxydonemov es:[di+2000], axinc bxadd di,2jmp pxy
.pxydoneret
;====== Install Interrupt =====
install ;Install new INT 8 vector
push es
push dx
push ax
push bx
mov al, 8 ;INT = 8
mov ah, 35h ;Read Vector Subfunction
int 21h ;DOS Service
mov word [oldv+0], bxmov word [oldv+2], esmov al, 8 ;INT = 8mov ah, 25h ;Set Vector Subfunction
mov dx, myint
;DS:DX point to functionint 21h ;DOS Service
pop bx pop axpop dxpop esret
1.46Sistemas Embutidos – Versão Modificada
Timer interrupt – uninstall interrupt
;====== Uninstall Interrupt ===========
UnInst ; Uninstall Routine (Reinstall old vector)
push ds
push dx
push ax
mov dx, word [oldv+0]
mov ds, word [oldv+2]
mov al, 8 ; INT = 8
mov ah, 25h ; Subfunction = Set Vector
int 21h ; DOS Service
pop ax
pop dx
pop ds
ret
1.47Sistemas Embutidos – Versão Modificada
Timer interrupt – ISR code
;====== ISR Code =========myint
push ds ;Save all registerspush axmov ax, cs ;Load default segmentmov ds, axpushf ;Call Orig Function w/flagscall far [oldv] ;Far Call to existing routine
inc word [count];Increment Interrupt
countcmp word [count],18jne .myintdone
inc word [scount] ;Next second mov word [count], 0cmp word [scount], 60jne .myintdoneinc word [mcount] ; Next minutemov word [scount], 0
.myintdonemov al, 20h ;Reset the PIC out 20h, al ;End-of-Interrupt signalpop ax ;Restore all Registerspop dsiret ;Return from Interrupt
1.48Sistemas Embutidos – Versão Modificada
The complete code with exe
www.ece.uiuc.edu/ece291/lecture/timer.asm
www.ece.uiuc.edu/ece291/lecture/timer.exe
1.49Sistemas Embutidos – Versão Modificada
Replacing An Interrupt Handler
;install new interrupt vector
%macro setInt 3 ;Num, OffsetInt, SegmentInt
push ax
push dx
push ds
mov dx, %2
mov ax, %3
mov ds, ax
mov al, %1
mov ah, 25h ;set interrupt vector
int 21h
pop ds
pop dx
pop ax
%endmacro
;store old interrupt vector
%macro getInt 3 ;Num, OffsetInt, SegmentInt
push bx
push es
mov al, %1
mov ah, 35h ;get interrupt vector
int 21h
mov %2, bx
mov %3, es
pop es
pop bx
%endmacro
1.50Sistemas Embutidos – Versão Modificada
Replacing An Interrupt Handler
CR EQU 0dhLF EQU 0ah
SEGMENT stkseg STACK resb 8*64stacktop:
SEGMENT code
Warning DB “Overflow - Result Set to ZERO!!!!”,CR,LF,0
msgOK DB “Normal termination”, CR, LF, 0
old04hOffset RESWold04hSegment RESW
New04h ;our new ISR for int 04
;occurs on overflow
sti ;re-enable interrupts
mov ax, Warning
push ax
call putStr ;display message
xor ax, ax ;set result to zero
cwd ;AX to DX:AX
iret
1.51Sistemas Embutidos – Versão Modificada
Replacing An Interrupt Handler
mov ax, msgOK
push ax
call putStr
Error:
;restore original int handler
setInt 04h, [old04hOffset], [old04hSegment]
mov ax, 4c00h
int 21h
..startmov ax, csmov ds, ax
;store old vectorgetInt 04h, [old04hOffset], [old04hSegment]
;replace with address of new int handlersetInt 04h, New04h, cs
mov al, 100add al, alinto ;calls int 04 if an overflow occurredtest ax, 0FFhjz Error NOTES INTO is a conditional instruction that acts only when the overflow flag is set With INTO after a numerical calculation the control can be automatically routed to a
handler routine if the calculation results in a numerical overflow. By default Interrupt 04h consists of an IRET, so it returns without doing anything.
1.52Sistemas Embutidos – Versão Modificada
Why are interrupts important
Interrupts let you use the operating system (run your programs, manage your files, access your peripherals etc.)
Interrupts help peripherals “talk” to your microprocessor
Interrupts help you measure time and control the timing of certain tasks in your microprocessors
1.53Sistemas Embutidos – Versão Modificada
Interrupts from a pedagogical perspective
By learning interrupts you learn important concepts such as:
Concurrency: how your processor manages to service interrupts while your program doesn’t know anything about them and how multiple interrupts are serviced at the same time
Preemptability and priorities, how can a low priority-task be preempted by a high-priority task
Scheduling: how can we assure that both low and high-priority tasks get the service they deserve from the processor
1.54Sistemas Embutidos – Versão Modificada
Interrupts and our everyday lives
We will spend at least two lectures to explain how to measure and track time in your microprocessor and you will be wondering why don’t we just look at our watches…
But we will also learn that looking at your watch all the time is not a good thing to do, especially if you’re a microprocessor…
We all have priorities E.g. you do your ECE291 homework and your
girlfriend/boyfriend calls, there’s a high-priority interrupt While you talk to your girlfriend/boyfriend you get another
incoming call from your mom, there’s an interrupt that you decide how to handle
• High priority: put the girlfriend/boyfriend on hold• Low priority: put your mom on hold or don’t even bother to
switch to the other line
1.55Sistemas Embutidos – Versão Modificada
Interrupts…seriously defined
Triggers that cause the CPU to perform various tasks on demand
Three types: Software interrupts – initiated by the INT instruction in your
program Hardware interrupts – initiated by peripheral hardware Exceptions – occur in response to error states in the processor or
during debugging (trace, breakpoints etc.)
Regardless of source, they are handled the same Each interrupt has a unique interrupt number from 0 to 255. These
are called interrupt vectors. For each interrupt vector, there is an entry in the interrupt vector
table. The interrupt vector table is simply a jump table containing
segment:offset addresses of procedures to handle each interrupt These procedures are called interrupt handlers or interrupt service
routines (ISR’s)
1.56Sistemas Embutidos – Versão Modificada
The 80x86 interrupt interface
Device generates request signal Device supplies interrupt vector number on data bus Processor completes the execution of current
instruction and executes ISR corresponding to the interrupt vector number on the data bus
ISR upon completion acknowledges the interrupt by asserting the INTA signal
80x86 processor
Some device
INT Request (INTR)
INT Acknowledge (INTA)
Data bus
1.57Sistemas Embutidos – Versão Modificada
It is not that simple…
What if we want to connect more than one devices to the processor ?
What happens if multiple devices generate multiple interrupts at the same time ?
We need a way to share the two interrupt lines among multiple devices
8259 Programmable Interrupt ControllerThe 8259 PIC operates as an arbiter for
interrupts triggered by multiple devices One 8259 serves up to 8 devices, but multiple
8259 chips can be “cascaded” to serve up to 64 devices
1.58Sistemas Embutidos – Versão Modificada
The 8259 PIC
8259PIC
01234567
INTRINTAINT#
80x86
Interrupt outputs from peripheral
devices
1.59Sistemas Embutidos – Versão Modificada
Master-Slave Configuration
Master8259
INTR
01234567
Slave8259
INTR
01234567
IRQ0IRQ1
IRQ3IRQ4IRQ5IRQ6IRQ7
IRQ8IRQ9IRQ10IRQ11IRQ12IRQ13IRQ14IRQ1580x86
Base vector is 78h
Base vector is 08h
1.60Sistemas Embutidos – Versão Modificada
The 8259 PIC
PIC is very complex to program, fortunately the BIOS does most of the work needed
Programmed with the I/O address 20h-21h (master) and 0A0h-0A1h (slave)
I/O instructions yet to be discussed… in reads from an I/O address out writes to an I/O address
Consider them as two registers the status register and the interrupt mask register
1.61Sistemas Embutidos – Versão Modificada
The 8259 PIC
The mask register is addressed from 21h It lets you enable/disable specific hardware interrupts Counterintuitive: a 0 ENABLES an interrupt and a 1
DISABLES the interrupt Never load a value immediately to the mask register Always read the previous value and use and/or
instructions to set the new maskin al, 21h ; this one reads the value of the mask register
and al, 0efh ; this zeroes out bit 4 i.e. IRQ4
out 21h, al ; this actually disables the interrupt in IRQ4
1.62Sistemas Embutidos – Versão Modificada
The 8259 PIC
When an interrupt occurs and the processor starts executing the ISR all further interrupts from the same device are blocked until the ISR issues an end of interrupt instructionmov al, 20hout 20h, al
You must end exactly one interrupt! Not sending one will block all interrupts from the save device Sending two or more means that you might accidentally
acknowledge the end of a pending interrupt! Two more registers track pending interrupts received
at the PIC and interrupt priorities You must be careful when you’re patching existing
ISR’s (because the end instruction sequence may already be included in the ISR)
1.63Sistemas Embutidos – Versão Modificada
The 8259 PIC
IRQ mapping Interrupt vectors 8 through 0Fh map to IRQ0-IRQ7 Interrupt vectores 70h-77h map to IRQ8-IRQ15
1.64Sistemas Embutidos – Versão Modificada
Interrupt vectors and the 8259 PIC
Master8259
INTR
01234567
Slave8259
INTR
01234567
IRQ0IRQ1
IRQ3IRQ4IRQ5IRQ6IRQ7
IRQ8IRQ9IRQ10IRQ11IRQ12IRQ13IRQ14IRQ1580x86
Base vector is 78h
Base vector is 08h
1.65Sistemas Embutidos – Versão Modificada
Typical IRQ assignments
IRQ 0: Timer (triggered 18.2/second) IRQ 1: Keyboard (keypress) IRQ 2: Slave PIC IRQ 3: Serial Ports (Modem, network) IRQ 5: Sound card IRQ 6: Floppy (read/write completed) IRQ 8: Real-time Clock IRQ 12: MouseIRQ 13: Math Co-Processor IRQ 14: IDE Hard-Drive Controller
1.66Sistemas Embutidos – Versão Modificada
Interrupt priority
Lower interrupt vectors have higher priorityLower priority can’t interrupt higher priorityHigher priority can interrupt lower priority
ISR for INT 21h is running• Computer gets request from device attached to IRQ8 (INT
78h)• INT 21h procedure must finish before IRQ8 device can be
serviced
ISR for INT 21h is running• Computer gets request from Timer 0 IRQ0 (INT 8h)• Code for INT 21h gets interrupted, ISR for timer runs
immediately, INT21h finishes afterwards
1.67Sistemas Embutidos – Versão Modificada
Priority in the 8259
8259 supports several priority schemes On PC’s the 8259 uses the simplest form of fixed
priorities Each IRQ has a fixed priority Lower IRQs has higher priority The timer interrupt (IRQ0) has lower priority than any
other IRQ If you really need higher priority than the timer (e.g.
connecting a nuclear reactor to your microprocessor) it is possible to use a NMI (non-maskable interrupt)
NMI has the highest priority among all hardware interrupts and cannot be disabled by the program
1.68Sistemas Embutidos – Versão Modificada
Interrupt enabling/disabling
You can enable/disable all maskable hardware interrupts
The CLI instruction disables all maskable hardware interrupts
The STI instruction enables all maskable hardware interrupts
Be very careful if you ever need to use them Many deadlock scenarios!
1.69Sistemas Embutidos – Versão Modificada
The ugly details
ISRs for hardware interrupts clear the interrupt flag at the beginning to disable interrupts. They may include a STI instruction if they want to enable interrupts before they finish It’s all about performance! Keeping interrupts blocked for long is a
BAD IDEA
ISRs for software interrupts do not disallow hardware interrupts automatically at the beginning. If an ISR for a software interrupt needs to do that it must issue a CLI instruction This is what most ISRs do Again for the sake of performance a STI instruction must be issued
as soon as possible Note that when interrupts are enabled the priority rule applies
The CLI works only for maskable hardware interrupts Code enclosed between CLI/SCI is often called a critical section,
an uninterruptible piece of code
1.70Sistemas Embutidos – Versão Modificada
Is there a way out of this mess ?
In many critical section situations (e.g. patching the interrupt vector tables) DOS helps us ensure the required atomicity
Convenient calls for Safely getting the value of the interrupt vector from the
interrupt vector table Safely storing a new value to the interrupt vector table
(patching the interrupt vector table)
In all difficult situations always examine what if scenarios What if a hardware interrupt occurs at different points of our
ISR ? Identify the points that need to be protected and protect them
with CLI/STI
1.71Sistemas Embutidos – Versão Modificada
Servicing a hardware interrupt
Complete current instruction Preserve current context
PUSHF Store flags to stack Clear Trap Flag (TF) & Interrupt
Flag (IF) Store return address to stack
PUSH CS, PUSH IP Identify Source
Read 8259 PIC status register Determine which device (N)
triggered the interrupt Activate ISR
Use N to index vector table Read CS/IP from table Jump to instruction
Execute ISR usually the handler
immediately re-enables the interrupt system (to allow higher priority interrupts to occur) (STI instruction)
process the interrupt Indicate End-Of-Interrupt
(EOI) to 8259 PIC mov al, 20h out 20h, al
Return (IRET) POP IP (Far Return) POP CS POPF (Restore Flags)
1.72Sistemas Embutidos – Versão Modificada
Interrupt service routines
Reasons for writing your own ISR’s to override the default ISR for internal hardware
interrupts (e.g., division by zero need not terminate the program)
to chain your own ISR onto the default system ISR for a hardware device, so that both the system’s actions and your own will occur on an interrupt (e.g., clock-tick interrupt, measure elapsed time)
to service interrupts not supported by the default device drivers (a new hardware device for which you may be writing a driver)
to provide communication between a program that terminates and stays resident (TSR) and other application software (maintain your ISRs)
1.73Sistemas Embutidos – Versão Modificada
Impact of interrupts on performance
The frequency of occurrence and the latency of the ISR determine the impact of servicing interrupts to your program
The latency of the ISR is non-negligible! You may not notice it but you may be interrupted
several times while executing your program. The good thing is that you don’t notice it!
Always remember: When the processor starts executing an ISR there might be
other ISRs executing already Your ISR may be interrupted by a higher-priority interrupt Many devices expect low latency from your ISR (imagine
what happens if you hit a key in the keyboard and wait for a minute!)
Even those devices with high latencies (e.g. the disk) are not allowed to block other activity in the processor for long
1.74Sistemas Embutidos – Versão Modificada
Interrupt Service Routines
ISRs are meant to be short keep the time that interrupts are disabled and the total length
of the service routine to an absolute minimum remember after interrupts are re-enabled (STI instruction),
interrupts of the same or lower priority remain blocked if the interrupt was received through the 8259A PIC
ISRs can be interrupted ISRs must be in memory
Option 1: Redefine interrupt only while your program is running
• the default ISR will be restored when the executing program terminates
Option 2: Use DOS Terminate-and-Stay-Resident (TSR) command to load and leave program code permanently in memory
1.75Sistemas Embutidos – Versão Modificada
Interrupt Driven I/O
Consider an I/O operation, where the CPU constantly tests a port (e.g., keyboard) to see if data is available CPU polls the port if it has data available or can accept data
Polled I/O is inherently inefficient Wastes CPU cycles until event occurs Analogy: Checking your watch every 30 seconds until
your popcorn is done, or standing at the door until someone comes by
Solution is to provide interrupt driven I/O Perform regular work until an event occurs Process event when it happens, then resume normal
activities Analogy: Alarm clock, doorbell, telephone ring