Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Hardware Interrupts: Thorne: 21.1, 21.3 Thorne: 21.1, 21.3 (Irvine Edition IV: Section 16.4)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

Hardware Interrupts

Thorne : 21.1, 21.3


(Irvine Edition IV : Section 16.4)

SYSC3006

The Particular Challenges of I/O Programming

Reference : Fundamentals of Embedded Software : Where C


and Assembly Meet, Daniel Lewis. Chapter 6.

With memory programming :


1. Data transfers between memory occur as a result of an
instruction fetch-execute cycle
1. Time to complete is in the order of microseconds

2. A program runs synchronously : Instructions are fetched


then executed.

CPU controls the data transfers between memory.

SYSC3006

The Particular Challenges of I/O Programming


With I/O programming
1. Input and output from/to external I/O devices (keypads,
sensors, switches) often involve physical movement
Response times are determined by physical nature of
device (eg. Bouncing of switches, A/D conversion,
movement of disk head)
Response times are an order of magnitude slower than
an instruction execution
2. I/O devices operate asynchronously from the processor (and
the program being run)
Availabilityy of data for input
p OR device for output
p is
not under the control of CPU
To transfer any data, the processor and I/O device must
synchronize
y
or handshake
SYSC3006

Polled Input/OutputWaiting Loops Busy Waiting


CPU controls the synchronization with I/O device
Execution is simple : sequential control flow
Example : Lab Switches
Is Switch E up?
while ( ! (g
(getSwitches()
() && 1000 0000B)) ) { }
processSwitch()
Example : Hypothetical Simple Keyboard Device :
When key pressed, character is put in data port and bit 0 in
the status port is set to indicate Key Ready.
When
Wh character
h
t is
i readd from
f
data
d t port,
t status
t t bit is
i cleared.
l
d
while (status && 0000 0001b == 0) { }
Read Keystroke from Data port
Is bit 0 in the status p
port set?
SYSC3006

(Hardware) Interrupts : A Device-centric Handshake


Example : Lewis
You are working at home doing taxes
The phone rings (an interrupt)
You stop work on the taxes and answer the phone (You
accept the interrupt)
A friend wants to know a mechanics phone number to
arrange service
You give the phone number (You process the interrupt
immediately)
You hang up and go back to your taxes.
Example : Classroom questions

SYSC3006

Example : Interrupt-Driven Keyboard


Simple Keyboard model:
When key pressed,
pressed character is put in data port and bit 0 in
the status port is set to indicate Key Ready and an
interrupt is sent to the CPU
When
Wh character
h
t is
i readd from
f
data
d t port,
t status
t t bit is
i cleared
l
d
Keyboard
CPU

Address Bus
Data Bus

Data Port
Status Port

Hardware Interrupts
require a hardware
signal
g from the device
to the processor.

Control Port

SYSC3006

Hardware Interrupts
The interrupted processing doesnt know it was interrupted
The processor just:
1 temporarily suspended current thread of control
1.temporarily
2.ran Interrupt Service Routine (ISR, later!)
3.resumed suspended thread of control
Polling:
P lli
CPU asks
k the
h peripheral
i h l devices
d i
whether
h h there
h is
i
anything to do now ?
Programming is sequential : Next instruction is determined
b the
by
h fetch-execute
f h
cycle
l andd by
b controll transfer
f
instructions.
Interrupts: Device tells CPU it is time to do something NOW
External hardware signals spontaneously cause transfer of
control (cause interruption in default sequential program).
No busy waiting, no polling.
Programming now requires an event-driven mindset
SYSC3006

Learning the Event-Driven Mindset


We will show two ways to depict the runtime behaviour of an
interrupt-driven
p
pprogram
g
Lets set up an example to demonstrate :
main PROC
here:
MOV AX
AX,BX
BX
MOV BX, CX
MOV CX, DX
JMP here

; m-1
; m-2
; m-3
; m-4

ISR PROC
MOV AX,1
IRET

; i-1
; i-2
i2

ISR ENDP

main ENDP
SYSC3006

Learning the Event Driven Mindset : CPU Utilization


Diagram
Di
Diagram depicts what CPU does as time progresses to the right
If no interrupts happen (and interrupts dont have to happen!)
Main thread of control completely consumes the CPU
m-1 m-2 m-3 m-4 m-1 m-2 m-3 m-4 m-1 m-2 m-3 m-4 .

If interrupts happen
CPU is used by ISR whenever the interrupt occurs.

time

m-1
m
1 m
m-2
2 ii-1
1 ii-2
2 m
m-3
3 m-4
m 4 m-1
m 1 ii-1
1 ii-2
2 m
m-2
2 m-3
m 3 m-4
m 4 m-1
m 1m
m-2
2 m-3
m 3 m-4
m 4
time
Interrupt
p signal
g
SYSC3006

Learning the Event Driven Mindset : Thread Diagrams


Diagram depicts the lifelines of each thread of control
Time

main

ISR
m-1
1
m-2

Interrupt
signal

i-1
ii-2
2
m-3
m-4
m-1
m
1

i-1
i-2

m-2
m-3
m-4
m-1

SYSC3006

10

The Interrupt Mechanism on the Intel 8086


The 8086 processor has two hardware interrupt signals
NMI
non-maskable interrupt
p
INTR
Interrupt request (maskable interrupt)
8086

Inside the computer


system

NMI INTR

bus

Outside the
computer system
SYSC3006

11

Interrupt Maskability

Maskable interrupts can be ignored by the CPU


Must be enabled before interrupting the CPU
8086 Example : INTR is maskable

NonMaskable
k bl interrupts
i
cannot ever be
b ignored
i
d by
b the
h CPU
8086 Example : NMI is non-maskable
Used for catastrophic
p errors (e.g.
( g RAM failure
Power failure, etc).

An Interrupt request can be pending: the signal is active but it has not
yyet serviced
For maskable interrupts, it may or may not be serviced
until/if it is enabled

SYSC3006

12

8086 Instructions for Interrupt Masking


Masking of INTR is done with the control flag IF in FLAGS register
CLI - clears IF bit in flags register (IF = 0)
disables (masks) interrupts at the processor
processor does not monitor INTR line while IF = 0
STI - sets IF bit in flags register (IF = 1)
enables (unmasks) interrupts at the processor
processor monitors INTR line while IF = 1
state of IF does not affect NMI, software interrupts or dedicated
interrupts
e up s (0..
(0..4))
Later, we shall say : CLI/STI instructions disable/enable
interrupts at the processor

SYSC3006

13

The Interrupt Mechanism on the Intel 8086


Interrupt signals can occur anytime.
When
Wh does
d
processor consider
id interrupt
i t
t signals?
i l?
What ISR does processor execute ? Where is this ISR ?
The complete instruction execution cycle :
1. Fetch instruction & adjust IP
2. Decode instruction
3. Execute instruction
4. Check NMI : If NMI asserted, perform related behaviour
5 If IF = 1 check
5.
h k INTR :
If INTR asserted, perform related behaviour

SYSC3006

14

8086 Vector Table


An array of 256 entries located at
the reserved memory location
0000:0000
Each entry is address of an
interrupt service routine (ISR).
The address is a FAR Pointer
(CS:IP pair) (32-bits = 4bytes)
The array occupies addresses
from 0:0 to 0:3FF (256*4 bytes)
Each entry is identified by unique
"interrupt-type"
p yp ((number),
), ranging
g g
from 0 to 255
If interrupt-type = i then the
offset to relevant entryy in the
vector table = 0000H + 4 * i

0:0

IP

0:2

CS

0:4

IP

0:6

CS

Just another example of


Array Programming

Address of type 0

Address of type 1

IP at low
CS at high
0 : 3FC
0 : 3FD
0 : 3FE
0 : 3FF

SYSC3006

IP
Address of type 255
CS
15

Interrupt Types : Deciding which ISR to run

Auto-vectored interrupts : The interrupt-type (the vector) is


predefined as part of the processor design
For a given hardware signal, the CPU automatically goes to
ap
particular interrupt-type
p yp in the vector table.
8086 Example : NMI is auto-vectored to Interrupt-type 2
Whenever NMI is asserted, the 8086 always executes
ISR att IInterrupt
t
t Type
T
=2
The address of the NMI ISR is always at 0000:0008h

SYSC3006

16

Interrupt Types : Deciding which ISR to run


Vectored interrupts : The interrupt-type (the vector) is
determined during systems design and is provided to the CPU.
The CPU pperforms an interrupt-acknowledge
p
g cycle
y where
it reads the interrupt-type from the data bus
No software is involved (More in 4601)
Interrupting device must provide (ie.
(ie write) the interrupt
interrupttype
External hardware
The address of the ISR is at 0000:type*4
VARIABLE

8086 Example : INTR is a vectored interrupt


Question : NMI and INTR Does this mean we can have only 2
interrupt sources ?
Question : Why do we need 256 entries in the vector table ?
SYSC3006

17

Multiple Interrupt Sources with AutoVectored Interrupts

Multiple devices share the same interrupt line


CPU must poll status port on each device to determine which
one generated interrupt.
interrupt signals from devices
Device 1
8086
processor

. . .
Device 2

NMI

bus
SYSC3006

18

Multiple Interrupt Sources with Vectored Interrupts


Interrupt
p controller acts as a funnel for multiple
p device interrupts
p
Interrupt controller handshakes with CPU (Interrupt
Acknowledge Cycle) on behalf of the device.
Interrupt controller knows which device interrupted
Interrupt controller tells the CPU by writing a unique
interrupt-type associated with interrupting device on the
data bus
CPU uses interrupt-type to execute the appropriate ISR
device
8086
processor

interrupt
controller

INTR

. . .
device

bus
SYSC3006

19

Perform Related Behaviour


Review : Execution semantics of CALL
NEAR CALL target
PUSH IP, IP := target
FAR CALL target
PUSH CS, PUSH IP,
CS:IP := target
Execution semantics of Interrupt
Push FLAGS register
Clear IF bit in flags to 0
Clear TF bit in flags to 0
Push CS
Learn this
Push IP
Fetch
F t h new CS ffrom
0 : n*4
*4 + 2 From Vector Table in memory!
n: Interrupt Type!
Fetch new IP from
0 : n*4
Question : What does all this ?
SYSC3006

20

ISR Stack Frame


The ISR stack frame different from subroutines!
Return address is always
y a FAR address CS:IP
FLAGs are also pushed.
SP

return IP
return CS
fl
flags

SYSC3006

Return
Address

21

Returning from an ISR


The RET instruction will not work
Why not ?
SP

When writing ISRs, you must use IRET.


1. Pops
p 32-bit return address ((CS:IP))
2. Pops flags
Restores FLAGS value to
Example :
isr PROC FAR
IRET
isr ENDP

return IP
return CS
flags
arguments

what they were before IF


and TF were cleared !

SYSC3006

22

Installing an ISR

Interrupts only work if ISR address has been loaded


previously into correct vector!
This is called installing the ISR in the vector table

SYSC3006

23

Dynamic Installation of an ISR


myint_type
myint
type
myvector
.code
myisr
i
IRET
myisr
y
main PROC
CLI
MOV
MOV
MOV
MOV
...
STI

EQU
EQU

40
; install as vector
myint_type * 4

PROC FAR
ISR
ENDP
IP of ISR

AX, 0
ES, AX
; ES vector table segment
ES:[myvector] , OFFSET myisr
segment override for
destination segment !
ES:[myvector+2] , @code
CS of ISR

; NOW, interrupts can happen


SYSC3006

24

Installing the ISR


When installing an ISR, you are over-writing a previous value
inserted by the O/S during startup
Example : The entry may have a useful DOS value .
Example : Even unused entries have an address of a default
ISR jjust in case (eg.
( g a simple
p return))
Whenever installing vectors, first save the existing contents of
the vector.
vector
The saved values should be restored before the program exits
If save/restore is not done, the OS (eg. DOS) might not run
properly.
properly
Sound familiar ? (Hint : SYSC-3006 Subroutine Policies)

SYSC3006

25

Robust Version of ISR Installation


.data
old_vector_offset
dw ?
old ector segment
old_vector_segment
d ?
dw
.code

MOV AX, 0
MOV ES, AX
; ES vector table segment
MOV AX, ES:[myvector]
MOV old_vector_offset, AX
Save original vector table!
MOV AX, ES:[myvector+2]
MOV old_vector_segment,
ld
t
t AX
MOV ES:[myvector] , OFFSET myisr
MOV ES:[myvector+2] , @code
...
SYSC3006

26

The Intel Programmable Interrupt Controller (PIC)


In 80x86 based PCs
PCs, interrupt controller is the Intel 8259A
Complex (ie. configurable / programmable) behaviour
Example : The specific interrupt-type to be associated
with each interrupting device is often programmable
Itself is an I/O device to be read/written.

INTR

IR0
8259 IR1
PIC IR2
IR3
IR4
IR5
IR6
IR7

Interrupting
Device
. . .

Interrupting
Device

D0..D7 Data bus


8-bit, 0 to 255 (Interrupt type )

It supports 8 device inputs : IR0

IR7
SYSC3006

27

Daisy-Chaining or Cascading the PIC


The maximum configuration is 1 master PIC and up to 8 slave
PICs, allowing up to 64 devices to generate interrupts
Modern PCs have a master + (at least) one slave
slave PICs
INTR signal
g

CPU

Interrupting Device
Slave
PIC

Master
PIC

INTR

interrupt signals from devices


. . .

Interrupting Device

value exchanged during interrupt


acknowledge hand-shake

bus
Interrupt type is read from data bus.
SYSC3006

28

The PC configuration of 80x86 and 8259 PIC


(NB The PC is one particular configuration of 8086 and PIC)

8086
processor

IR0
8259 IR1
PIC IR2
IR3
IR4
IR5
IR6
IR7

INTR

Timer

Keyboard
. . .

LPT1
Pi t
Printer

T
Type-08h
08h

Type-09h

Type-0Fh

Interrupt type

bus

During power-up, BIOS programs (initialises) the master PIC:


IR0 IR7 mapped to interrupt types 08h 0Fh
SYSC3006

29

PC Example : Keyboard
Assume interrupts are enabled (assume IF = 1)
When the keyboard hardware logic asserts IR1 at PIC, the PIC
generates INTR signal to the processor
During interrupt acknowledge, PIC identifies interrupt Interrupts
disabled
source as type 9
when ISR
The CPU executes the INT 9h behaviour
begins
Saves the flags
execution
Clears IF and TF (Disabling interrupts at processor)
Saves CS and IP
Reads the interrupt-type = 9h from the Data bus and
vectors to the ISR pointed to by the double word at
address of 0 : 9h*4 in Vector Table (memory)
Execution of ISR 9 is caused by hardware interrupt mechanism
No software
so twa e involved
vo ved in the invocation oof ISR
S 9!
SYSC3006

30

Some (as yet) Unanswered Questions:


1. If two devices generate interrupt signals at the same time,
which ISR should be executed first?
order?

2. If the CPU is executing an ISR, and a second device interrupts,


when should the second ISR be executed?
interrupting an ISR?
not possible unless ISR
re-enables interrupts !
i.e. IF = 1

When IF=0, no further (maskable) interrupts are accepted.


y accepted
p regardless
g
of IF.
NMI is always
SYSC3006

31

Interrupt Priority
Interrupting Devices are assigned priorities
Higher priority devices take precedence over lower priority
devices
Priority is applied whenever interrupts coincide
When multiple interrupts occur at the same time
When
h new interrupts
i
occur while
hil still
ill processing
i the
h ISR
S off
previous interrupts.
Typically, interrupt controllers manage priority issues.
In PCs
The devices have pre-configured connections to PIC
Timer is always IR0 and Keyboard is always IR1
DOS programs the 8259A to assign priority based on the
device connection
IR0 == highest priority and IR7 == lowest priority
SYSC3006

the lower the number,


the higher the priority32

Interrupt Priority Scenarios


1. If two devices generate interrupt signals at the same time,
which ISR should be executed first?
Time
IF=1
IF=1

IF=0

IF=1
IF=0

IF=1

IF=0

Main INT 8 ISR INT 9 ISR Main


IRET

IF=1

INT 9 ISR INT A ISR

IRET

IRET

IR1(= 09h)
IR0 (= 08h)

IF=0

Main
IRET

IR2 (= 0Ah)
IR1 (= 09h)

SYSC3006

33

Interrupt Priority Scenarios


2 If the
2.
th CPU iis executing
ti an ISR
ISR, andd a secondd device
d i interrupts,
i t
t
when should the second ISR be executed?
If a higher priority interrupt follows a lower priority, the PIC
generates
t another
th interrupt.
i t
t
No STI in ISR

With STI in ISR

IF 1
IF=1
IF=1

IF=0

IF=0

IF=1

IF=1

Main INT 9 ISR INT 8 ISR Main


IRET

IR1

IR0

IF 0
IF=0

IF 0
IF=0

IRET

IF=1

IF=0
IF
0
IF=1

IF=1

INT 9

INT 8 ISR 9 ISR Main

STI

STI

IR1

IRET

STI IRET

IR0

The PIC will


Th
ill try
t to
t allow
ll a higher
hi h priority
i it interrupt
i t
t to
t interrupt
i t
t
a lower priority ISR !
The second interrupt will not be recognized by the
processor until
til interrupts
i t
t are re-enabled
bl d . until
til IF = 1
SYSC3006

When is this ?

34

Interrupt Priority Scenarios

If a lower priority interrupt follows a higher priority


priority, the PIC
maintains the priority .
No STI in ISR

With STI in ISR

Main INT 8 ISR INT 9 ISR Main

IR0

IR1

INT 8 ISR INT 9 ISR

IR0

IR1

It remembers (latches) the lower priority interrupt until the


high
g ppriorityy ISR is finished regardless
g
of interrupts
p beingg
enabled/disabled
When finished, PIC generates another interrupt on behalf of
the lower priority device.
Hmmm. Two More Questions:
1. How many interrupts can the PIC remember?
2 How does the PIC know when the higher priority ISR is
2.
finished?
SYSC3006

35

Pending Interrupts
Terminology: A Pending Interrupt is an interrupt signal that
i latched
is
l t h d somewhere
h in
i the
th system,
t
but
b t has
h nott yett been
b
acknowledged by the processor
Interrupts can be pending at device and / or at the PIC
Example : The Intel 8259 has an internal 8-bit register
one bit pper IR input
p
When IR is asserted, the associated bit is set
When the interrupt on IR is acknowledged, the associated bit
is cleared
In summary, the PIC has 1-bit memory for each IR
It can remember up to 1 pending interrupt for each IR
Total 8 different IRs
SYSC3006

36

End-of-Interrupt (EOI)
After sending an interrupt to processor, PIC needs to know
when it is safe to generate a lower priority interrupt
the PIC requires feedback from the CPU
End Of Interrupt (EOI) is a command sent to PIC from the CPU
It is not part of the INTA cycle; it is not done in hardware
It is a software command; ie. something your program must
do.
do

SYSC3006

37

PIC Programmer
Programmerss Model

Simple version here


on a need-to-know basis.
Complete
p
details in ELEC 4601

The PIC is an I/O Device so it has I/O port addresses


It appears as two 8-bit ports:
Interrupt Mask Register (Port 21H) read/write
Allows us to enable/disable individual interrupts at the PIC
bit i = 1 IRi is masked (not recognized by the PIC)
bit i = 0 IRi is unmasked (recognized by the PIC)
Beware : mask at PIC

bit = 1

mask at processor

IF = 0

Command Register (Port 20H) - write-only


Write
W it 20H tto iinform
f
PIC off endd off interrupt
i t
t (EOI)
SYSC3006

38

PC Keyboard : I/O Programmers Model


The PC keyboard is interrupt driven
It cant run in polled mode because there is no status port
It is
i connected
t d to
t IR1 off th
the PIC,
PIC through
th
h 8255 P
Parallel
ll l
Peripheral Interface (PPI)
The 8255 is our programming interface to the keyboard

There are 2 interrelated 8255 PPI ports:


Data Port (Port PA) :
I/O address 60H
Control Port (Port PB) :
I/O address 61H

SYSC3006

39

PC Keyboard : I/O Programmers Model


The keyboard data port (Port A) has dual functionality :
Dual = Different values are read from the same port!
The
Th value
l readd depends
d
d on the
th setting
tti off Port
P t B,
B Bit 7!
Port B, Bit 7 = 0 Scan Code is read.
((ie. identify
y the keystroke)
y
)
Port B, Bit 7 = 1 Configuration switch data is read
In this course, we never use the configuration data, so why dont
we just set Port PB, Bit 7 = 0 and leave it there ?

SYSC3006

40

PC Keyboard : Hardware Requirement

The keyboard will not send the next scan code until the previous
scan code has been acknowledged
T acknowledge
To
k
l d scan code:
d
PB bit 7 must be toggled from 0 1 and then 1 0

CAREFUL! All bits in PB have important values


To acknowledge:
1. Read Port B : PB_value
PB value
2. Force bit 7 = 1: PB_value OR 80H
3. Write modified value back to Port B
4 Write
4.
W it original
i i l value
l (with
( ith bit 7 = 0) back
b k to
t Port
P tB

NB. The keyboard hardware is initialised when DOS boots


SYSC3006

41

PC Keyboard : Scan Codes


The scan code is a code sent from keyboard whenever its keys
change state
Scan
S
codes
d are NOT ASCII codes!!
d !!
The scan codes runs from 0 53H
e.g. A key scan code = 1EH
Scan codes are make/break coded
one code sent when key is pressed (make)
different code sent when key is released (break)
The only difference is the most-significant bit
If MSBit = 0 key was pressed
If MSBit = 1 key
k was released
l
d
Example : Letter A
Make A
= 1EH (0001 1110b)
Break A
= 9EH (1001 1110b)
SYSC3006

42

PC Keyboard : Multiple Key Combinations


Multiple key combinations
<SHIFT> A
<CTRL><ALT><DEL>
Software must manage multiple key combinations.
Left Shift key press, make code = 2AH
Right Shift key press,
press make code = 38H
Ctrl key press, make code = 1DH
Alt key press, make code = 3AH
Keyboard software must track the state of control keys for
correct interpretation

SYSC3006

43

Example : A Simple Keyboard Driver

Requirements
prints uppercase chars representing keys pressed
ALT,
ALT SHIFT,
SHIFT CTRL keys
k
(and
( d a few
f others)
th ) are nott
managed
exit the program by resetting
ISR ignores key released scan codes
uses lookup table to convert key released scan code to
uppercase ASCII representation

SYSC3006

44

Example : A Simple Keyboard Driver


Program architecture
The
Th duties
d ti have
h
been
b
divided
di id d between
b t
the
th main
i program andd
keyboard ISR
Keyboard ISR gathers data as user enters keystrokes
Main prints the keystrokes
The data is shared between the two threads in a
variable KEYBOARD_CHARACTER (global variable)
The variable is initialised to 0FFh to represent no data
(0FFh is not an ASCII code for any key)
H ddoes The keyboard ISR puts ASCII code in the variable
How
Main program polls the variable until valid data is found;
it know
when ?
When main reads ASCII code, it must reset the variable
to no
no data
data value
SYSC3006

45

Keyboard : Code Fragments


LF
CR

EQU
EQU

0AH
0DH

shared variable initialized to no data value


.data
KEYBOARD_CHARACTER
DB
0FFH
SCAN_TABLE ; lookup table
Use 0 for keys to ignore
DB
0,0,'1234567890-=',8,0
DB
'QWERTYUIOP[]',CR,0
DB
'ASDFGHJKL;',0,0,0,0
DB
'ZXCVBNM,./',0,0,0
, , , ,
DB
' ',0,0,0,0,0,0,0,0,0,0,0,0,0
DB
'789-456+1230'

SYSC3006

46

.code
Keyboard : Code Fragments
MAIN PROC
CLI
; Disable ints while installing ISR
; Install the Keyboard ISR at Interrupt Type = 9
; Enable keyboard
y
interrupts
p at the PIC
STI
; Enable interrupts at the processor
FOR_EVER:
; press reset to exit
CALL GET_CHAR
; returns ASCII in AL
PUSH AX
; save char & pass parameter
CALL DISPLAY_CHAR ; displays char in AL
POP
AX
; restore char & clear stack
CMP
AL , CR
; check for Enter key
JNZ
REPEAT_LOOP
MOV
AL , LF
; if Enter do LF too !
PUSH AX
CALL DISPLAY_CHAR
DISPLAY CHAR
ADD
SP, 2
REPEAT_LOOP:
JMP
FOR_EVER
MAIN ENDP
SYSC3006

47

Keyboard ISR : Code Fragments


GET_CHAR
PROC NEAR
; poll until char received from ISR
; check for no data value
CMP KEYBOARD_CHARACTER , 0FFH
JZ GET_CHAR
Is this a critical region?
Should it be protected?
; get ASCII character
MOV AL , KEYBOARD_CHARACTER ; global variable from KISR
MOV
OV KEYBOARD
O
_C
CHARACTER
C
, 00FFH
RET
GET_CHAR
ENDP

SYSC3006

48

Keyboard : Code Fragments


KISR PROC FAR
; Standard ISR Setup (Save registers, including DS)
MOV AX, @data
MOV DS, AX
IN

AL , 60H

; AL = scan code

; Acknowledge Keyboard : Toggle PB bit 7


PUSH
AX
; save scan code
IN
AL , 61H
; read current PB value
OR
AL , 80H
; set bit 7(= 1)
OUT
61H , AL
; write value back + bit 7 = 1
AND
AL , 7FH
; clear bit 7 (=0) back to original
OUT
61H , AL
; write original value back
; restore scan code
POP
AX
SYSC3006

49

Keyboard : Code Fragments


TEST
AL , 80H
; ignore break codes
JNZ SEND_EOI
; Convert make code to ASCII
LEA
BX , SCAN_TABLE
XLAT
CMP
AL , 0
; some keys
k
are ignored
i
d!
JZ
SEND_EOI
; Put ASCII encoded value in shared variable
MOV
KEYBOARD_CHARACTER , AL
SEND_EOI:
MOV
AL , 20H
OUT
20H , AL
; Standard ISR exit code (restore all registers)
IRET
KISR ENDP
SYSC3006
50

Example : Polled Timing Loop


Programs must often manage time (eg. timing constraints)
Example : In animation, motion is timing dependent
Example
E
l : Changing
Ch i di
display
l after
ft fixed
fi d time,
ti
To clear a dialog box.
To turn on/off a LED for the floppy disk access light.

In a program, what is time?


Various schemes are used to manage time : hardware / software

SYSC3006

51

Software Solution : Polled Timing Loop


Example : A software-only solution for a timing loop
Write a loopp that simply
p y counts to waste time (busy
( y waiting)
g)
for ( int i = 0; i < 10000; i++ )
{
for (int j = 0; j < 10000; j++)
{ } // empty body
}
Advantage: It is simple software; No explicit h/w involved
Disadvantage:
Timing is based on the execution speed of the processor.
It is not portable because execution speed varies on different
machines
download old DOS games ??
SYSC3006

52

Hardware Solution : Hardware-Based Timing

Requirement : The computer system includes hardware dedicated to


managing time
We will introduce the timing hardware as a separate I/O device Integration
Often, there is no external device; it is just internal component but
still with usual programmers model of an I/O device

counts
ticks

oscillator signal at
known frequency
Timer

Component

Timing Component :
Input Signal : oscillator circuit generates ticks at a known
frequency e.g. square wave at some frequency
It counts ticks (edge-to-edge) on the input signal
Since frequency of ticks is known, then counting a fixed
number
b represents the
h passage off a known
k
amount off time
i
SYSC3006

53

Intel 8253 Programmable Interval Timer (PIT)


One 8253 component has 3 independent timer components
Each timer counts ticks on the same master clock input
p
Each timer generates its own output signal
Each timer can be programmed for one of 6 modes
(mode 00-5)
5) that determine the shape of the output
signal.
3 independent
output signals

8253
timer
i
0

Input Clock
(crystal oscillator)

timer 1

timer 2

16-bit counter

16-bit counter

16-bit
16
bit counter
SYSC3006

54

Basic Timing Function of 8253


Each timers counter is a 16-bit unsigned value
Timer
Ti
decrements
d
t counter
t every tick
ti k on the
th input
i
t clock
l k
(typically from crystal oscillator)
When counter reaches zero, its output signal changes (if 1, now
0 if 0,
0;
0 now 1)
Some modes automatically reload counter and start again
leading to digital patterns.
16-bit Reload Value
16-bit Counter ((decrements))

0 or 1

Hence, the counter value is related to the period of the output


signal
SYSC3006

55

Square Wave Generator Mode (Mode 3)


In mode 3, a 8253 timer component generates a square wave on
its output signal.
Square wave : approx. 50% duty cycle
Each time master clock input signal ticks, the timers
counter
cou
e iss dec
decremented
e e ed
When the counter reaches half of original value, the output
signals is toggle
When
Wh counter
t reaches
h 0,
0 the
th output
t t signal
i l is
i toggled
t
l d andd the
th
counter is reloaded.
last value written to counter is used as reload (original) value
16-bit Reload Value = 4
4

16-bit Counter = 4,, 3,, 2,, 1,, 0


of input frequency
SYSC3006

56

Square Wave Generator Mode (Mode 3)


In Mode 3, the timers output is a scaled down version of the
input clock
There is one output cycle for every n input cycles where n is
called the scaling factor
output freq. = input freq. scaling factor
Usually, we need to find the scaling factor to program the timer
component
Need to determine the initial counter value that will generate
a desired output frequency
scaling factor = input freq. output freq.
SYSC3006

57

8253 PIT Programmer


Programmerss Model

The PIT is an I/O device with four 8-bit ports (registers)


On the PC: port addresses are 40H 43H

g
There are three 8-bit Data Registers
Timer 0 Counter Register 40H
Timer 1 Counter Register 41H
Timer 2 Counter Register 42H

Question : How can 8-bit data registers be used to initialise 16bit internal counters ?

SYSC3006

58

8253 PIT Programmer


Programmerss Model
Control Register (43H)

write-only

SC1 SC0 RL1 RL0 M2 M1 M0 BCD


0

timer
select
l t
SC1
0
0
1

read/load
sequence
SC0
0
1
0

mode
timer select
select timer 0
select timer 1
select timer 2

SYSC3006

59

8253 PIT Programmer


Programmerss Model
RL1
0
1
1

RL0
1
0
1

read/load sequence
read/load LSB only
read/load MSB only
read/load LSB first,
first then MSB

M2 M1 M0 mode (6 modes)
x
1 1 mode
d 3 square wave generator where
h x = dont
d care
(other modes in ELEC-4601 )
BCD (binary coded decimal)
0 16 bit binary count
1 BCD
C cou
count (4
( decimal
dec
digits)
d g s)
SYSC3006

60

8253 Hardware Configuration and Limits on the PC


On a PC, the 8253 is wired such that
Generate timer interrupts!
master input signal = 1.19318 MHz
output from timer 0 connected to IR0 on PIC
The scaling factor is an unsigned number from 0 FFFFh
(65,535) but 0000H = 65,536 (i.e. 10000H, with implied MS
bit)
Question : What is the maximum frequency ?
Question : What is the minimum frequency ?
min output = input max scaling factor
= 1.19318 MHz 65,535
= 18.2 Hz
SYSC3006

61

Hardware Timing Example : DOS Time-of-Day


The DOS maintains the time-of-day feature HH : MM : SS
> date
Provide file timestamps
timestamps.
DOS uses Timer 0 to provide a real-time clock interrupting at a
frequency of 18
18.2
2 Hz
Hz.
When DOS boots, Timer 0 is programmed for Mode 3
(square wave) and an initial time is loaded
The
Th Timer
Ti
0 ISR counts ticks
k (at
( 18.2
18 2 Hz)
H )
initial time + ticks is used to calculate current the timeof-day
SYSC3006

62

Hardware Timing Example : 20Hz Real-Time Clock


Example : Devise a program that provides replaces the DOS
time-of-day to provide a ticksCount = number of 20Hz ticks
Program timer to interrupt at 20 Hz
Timer ISR keeps running tick count of 20 Hz ticks
Main program can use tick count to provide timing
information

SYSC3006

63

20Hz Real
Real-Time
Time Clock : Before Programming
1. Develop the Program Architecture
Two software components - main program and timerISR
will share a 32-bit unsigned count variable
Why 32-bit ?
timerISR increments count everyy tick
Main program reads count whenever it needs to

Will encapsulate in a subroutine : double getTicks()

Main Program
Initialize system
do work (usually a loop)
{
current= getTicks()
}
exit

timerISR
count

SYSC3006

count++

64

20Hz Real-Time Clock : Before programming


2. Determine values for programming the 8253 Timer 0:
a) Write to the timers control register: (at 43H)
SC1 SC0 = 00 (select
( l t timer
ti
0)
RL1 RL0 = 11 (LS byte then MS byte)
M2 M1 M0 = 011 (square wave): mode 3
could also use M2 M1 M0 = 111
BCD = 0 (16 bit binary count)
select

load

mode

Control Register : 00 11 011 0


SYSC3006

BCD

36H
65

20H Real-Time
20Hz
R l Ti
Clock
Cl k : Before
B f
programming
i

b) Determine the initial (reload) counter value:


scaling factor = input freq. output freq.
= 1.19318 MHz 20 Hz
= 59,659 (decimal) = 0E90BH

After writing to control register, write timer 0 counter value:


(at 40H)
First write LSB:
0BH
Then write MSB:
E9H

SYSC3006

66

20Hz Real-Time Clock : Code Fragments


; Symbolic Definitions
; PIC registers and constants
PIC COMMAND REG
PIC_COMMAND_REG
PIC_IMR_REG
EOI

equ 20H ; Command register


equ 21H ; Interrupt mask register
equ 20H ; EOI to port 20h (Command Register)

;Timer registers and constants


TIMER_0_REG
TIMER_CTRL_REG
TIMER_0_MODE

equ 40H ; Timer 0 counter data register


equ 43H ; Control register
equ 36H ; = 0011 0110b

SYSC3006

67

20Hz Real-Time Clock : Code Fragments


.data
; Program modifies state of system; need variables to save
; state
t t to
t allow
ll restoring
t i off state
t t upon exit
it
old_pic_imr
db ?
old_int8_vector_offset
dw ?
old_int8_vector_segment
dw ?
; 32-bit count: shared by ISR and main program
count_low dw ?
count high dw ?
count_high
SYSC3006

68

20Hz Real-Time Clock : Code Fragments


.code
MAIN PROC
; Initialize data structures used by ISR
SUB AX , AX
; trick! AX = 0 !
MOV count_low , AX
; tick count = 0
MOV count_high , AX
CLI
; Disable interrupts while installing and setting up timer. Why ?
; Install Timer ISR at interrupt type = 8 (As before)
; Program timer 0 to interrupt at 20 Hz
MOV AL , TIMER_0_MODE
TIMER 0 MODE
; Control Register
MOV DX , TIMER_CTRL_REG
OUT DX , AL
MOV AL , 0BH
; scaling factor = E90BH
MOV DX , TIMER_0_REG
OUT DX , AL
; write low byte
MOV AL , 0E9H
OUT DX , AL
; write high byte
SYSC3006

69

20Hz Real-Time Clock : Code Fragments


; Enable TIMER interrupts at the PIC (As before)
MOV DX , PIC_IMR_REG
IN
AL , DX
MOV old_pic_imr, AL
; for later restore
AND AL , 0FEH
; clear bit 0 of IMR
OUT DX , AL
; Enable interrupts at the processor
STI
forever: .
; Main loop of program
CALL get_ticks
; Returns tick count in dx:ax
; Use
U value
l as needed
d d
JNE forever
exit : ; Restore state before returning to DOS (not shown)
SYSC3006

70

Event-driven thinking !
timerisr PROC FAR
STI
; Re-enable ints
PUSH DS
; Save EVERY register used by ISR
PUSH DX
What are implications of this?
PUSH AX
Is it really needed?
MOV AX , @data
MOV DS , AX
ADD count_low,1
eventJNC t1
di
driven
thinking !
INC count_high
t1:
CLI
; Lock out all ints until IRET
MOV AL , EOI
; Send EOI to PIC
MOV DX , PIC_COMMAND_REG
OUT DX , AL
POP AX
; Restore registers
POP DX
POP DS

IRET
timerisr
i
i ENDP

How do interrupts get re-enabled? STI?


SYSC3006

71

20H Real-Time
20Hz
R l Ti
Clock
Cl k : Code
C d F
Fragments
t
get_ticks
get
ticks PROC NEAR
CLI
; Lock out ints while accessing shared data
; (ensure mutual exclusion)
eventdriven
thinking !

MOV DX , count_high
MOV AX , count_low
count low

STI
RET
get_ticks ENDP

; Return 32 bit count

; Re-enable ints

SYSC3006

72

20Hz Real-Time Clock : A Timing Analysis


CPU Utilization Diagram
main init

timerISR main timerISR main timerISR main


time

Timer 0 tick

Timer 0 tick

Timer 0 tick

Wh t is
What
i this
thi value
l ?

SYSC3006

73

20Hz Real-Time Clock : A Timing Analysis


Thread Diagram
Time
Timer00
Ti
signal

main

ISR
iinit
i
main work
count++

count++
What is this value ?
What does count
represent ?

SYSC3006

74

Event-Driven Thinking : An Interference Scenario


Suppose CLI / STI protection not there , and:
count_high = 0010H
Whats special about this value ?
count_low = FFFFH
Suppose
pp
main pprogram
g
was executing
g ggetTicks()
() with the
following:
MOV DX , count_high
MOV AX , count_low
count low
Suppose Timer interrupt occurs during /after MOV DX ,
count high
count_high
At this point, DX = 0010H
For count to be correct, AX = FFFFH
BUT . . .
SYSC3006

75

Event-Driven Thinking : An Interference Scenario


In response to the interrupt, timerISR increments count, to
become:
count_high = 0011H
count_low = 0000H
When main program resumes, it executes MOV AX, count_low
(DX = 0010h, from before interrupt)
AX = 0000H (from after interrupt)

The value returned from get_ticks() is:


count_high before Timer interrupt
count_low after Timer interrupt

SYSC3006

DX = 0010H
AX = 0000H

76

I/O Program Metrics


Definition : Transfer Rate
Number of bytes per second transferred between CPU and
device
Maximum transfer rate characterizes the capability of the I/O
program
Definition : Latency (Response time)
Delay from the time the device is ready until the first data
byte is exchanged.

SYSC3006

77

Polled Input/Output
CPU controls the synchronization
y
with device
Execution is simple : sequential control flow
Polled transfer rates are usually reasonable
Maximum
i
transfer
f rate is
i the
h time
i to execute the
h check
h k (once
(
the device is ready) and then transfer
Polled latencyy is usuallyy unpredictable
p
Depends on the other works being done between checks
unless CPU works only on polling, in which case CPU is
dedicated to I/O and cannot perform any other work.
work
What if other interesting events happen on other devices ?

SYSC3006

78

Interrupt-Driven Input/Output
Device signals CPU of a new I/O event
Event-driven programming
In general, interrupts improve the latency of a system
Interrupt latency is deterministic
Interrupt transfer rates includes interrupt overhead
Can be slower than polled
Depends . If amount of data transferred per interrupt
exceeds the overhead of switching tasks
Advantage : CPU can be doing other work whenever there is no
I/O event.
Software
S ft
structure
t t
remains
i clean
l
andd task-oriented.
t k i t d
Although the time to complete the other work is marginally
increased, depending on the number of interrupts.
SYSC3006

79

You might also like