Upload
mohammad-mohsen-amiri
View
215
Download
0
Embed Size (px)
Citation preview
7/29/2019 03ddPolIntr.pdf
1/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-1
Chapter
3Polling and Interrupt
Handling
7/29/2019 03ddPolIntr.pdf
2/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-2
Polling and Interrupt Handling
3.1 Overview
Polling
Interrupt Handling
Design Considerations
7/29/2019 03ddPolIntr.pdf
3/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-3
Overview
A device driver is a software solution for a hardware
operation problem.
The software must be aware of state changes or eventsin the hardware. Examples of state changes and events
are:
q Floppy drive door openedq DMA operation completeq Data has arrivedq Device has completed initialization and is now
available for use.q . . .
7/29/2019 03ddPolIntr.pdf
4/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-4
Methods
Polling
q Software periodically queries the hardware for event
occurrences. Interrupt Handling
q Hardware causes flow of execution to be changeddue to a event occurrences.
7/29/2019 03ddPolIntr.pdf
5/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-5
Polling and Interrupt Handling
Overview
3.2 Polling
Interrupt Handling
Design Considerations
Managing non-interrupt driven devices using polling techniques
q Task polling during idle times
q Task polling at periodic intervals
q Using watchdog timers
q Using auxiliary clock
Task synchronization
Data buffering (asynchronous I/O)
Mutual exclusion and race condition issues
7/29/2019 03ddPolIntr.pdf
6/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-6
Approach Overview
DriverDriver
ApplicationApplication
Driver Poll Task
DeviceDevice
Application program calls driver routines, which access device.
q driver is executed in the context of the application task
q all I/O is synchronous
Application program calls driver routines, which communicate with the
driver poll task.
q poll routine executes as separate task
q I/O may be asynchronous
7/29/2019 03ddPolIntr.pdf
7/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-7
Task Time Polling
To poll your device when the system is idle:
q Create a low priority taskq
In an infinite loop poll the device:FOREVER
{
status = *pDeviceAdr;
...
}
What are the consequences of the above?
7/29/2019 03ddPolIntr.pdf
8/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-8
Task Time Polling
To poll device at a periodic interval:
q Create a moderate or high priority task
q In an infinite loop poll device and call taskDelay( ).FOREVER
{
status = *pDeviceAdr;
...
taskDelay (POLL_RATE);
}
What are the consequences of this choice?
7/29/2019 03ddPolIntr.pdf
9/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-9
Task Time Polling Without Drift
Poll device from a task synchronized by a watchdog timer:
1 LOCAL SEM_ID fooSemId;
2 LOCAL WDOG_ID fooWdId;
3
4 STATUS fooInit (void)
5 {
6 /* Create poll task */
7 fooSemId = semBCreate (SEM_Q_PRIORITY,SEM_EMPTY);
8 taskSpawn (...fooPoll,...);
9
10 /* Create watchdog timer and start it */11 fooWdId = wdCreate ();
12 wdStart (fooWdId, POLL_RATE, fooWdFunc, param);
13 }
What are the consequences of this choice?
Please note that error checking has been removed in the code above.
7/29/2019 03ddPolIntr.pdf
10/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-10
Code Example (Contd)
14 LOCAL void fooWdFunc (int param)
15 {
16 semGive (fooSemId);
17 wdStart (fooWdId, POLL_RATE, fooWdFunc, param);18 }
19
20 LOCAL void fooPoll (void)
21 {
22 semTake (fooSemId, WAIT_FOREVER);
23 status = *pDeviceAdr;
24 ...
25 }
7/29/2019 03ddPolIntr.pdf
11/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-11
Interrupt Time Polling
Poll device using a watchdog timer:
1 LOCAL WDOG_ID fooWdId;
2
3 STATUS fooInit (void)
4 {
5 fooWdId = wdCreate ();
6 wdStart (fooWdId, POLL_RATE, pollFunc, param);
7 }
8
9 LOCAL void pollFunc (int param)
10 {
11 status = *pDeviceAdr;12 ...
13 wdStart (fooWdId, POLL_RATE, pollFunc, param);
14 }
7/29/2019 03ddPolIntr.pdf
12/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-12
High Speed Interrupt Time Polling
Use the auxiliary clock for very fast polling:
void fooPollStart (int rate)
{
sysAuxClkConnect (fooPoll, param);
sysAuxClkRateSet (rate);
sysAuxClkEnable ();
}
LOCAL void fooPoll (int param)
{
status = *pDeviceAdr;
...
}void fooPollStop (void)
{
sysAuxClkDisable ();
}
The existence and restrictions on the auxiliary clock is board dependent.
See config.h for the minimum (AUX_CLK_RATE_MIN) and maximum
(AUX_CLK_RATE_MAX) auxiliary clock rates.
For simplicity, error checking has been removed from the example
routines above.
7/29/2019 03ddPolIntr.pdf
13/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-13
Comparison of Polling Techniques
Using a low priority task allows device polling as
system load permits.
Polling task could starve if priority is not high enough.
The higher the priority, the more consistently the task
accesses the device.
A high priority polling task may block out other tasks.
Using watchdogs provides the most reliable periodic
device access with the greatest cost (to the rest of the
system).
To reduce overhead, interrupts should be used for high
speed polling.
Since there is less overhead in servicing an interrupt then in a context
switch, high speed polling is best done in an auxiliary clock ISR.
7/29/2019 03ddPolIntr.pdf
14/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-14
Polling and Interrupt Handling
Overview
Polling
3.3 Interrupt Handling
Design Considerations
Installing an interrupt service routine (ISR).
What can and cannot be done in an ISR.
Debugging an ISR.
7/29/2019 03ddPolIntr.pdf
15/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-15
Interrupt Service Routine (ISR)
User-defined routine to execute upon receipt of an
interrupt.
In an ISR, do not:
q Block, e.g. call semTake( )
q Use a routine that requires a task context (TCB), e.g.call taskIdSelf( )
q Use floating point operations (unless floating pointregisters are saved and restored)
7/29/2019 03ddPolIntr.pdf
16/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-16
Handling Interrupts
1. Interrupt task when device asserts IRQ line
2. During interrupt acknowledge cycle, decide which
device needs service3. Call routine appropriate for the device as indicated in
the Interrupt Vector Table
4. In VxWorks-defined interrupt wrapper routine, saveregisters and call user-defined ISR
5. Restore registers on return from ISR
6. Unless ISR made a task of higher priority ready to run,resume interrupted task
Floating point registers are NOT automatically saved and restored by
interrrupt wrapper routine.
7/29/2019 03ddPolIntr.pdf
17/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-17
Auto-vectored, Vectored andChained Interrupts
If the system is autovectored, software will be run to
determine which device caused the interrupt.
In a true vectored system, hardware will complete a set
of bus cycles to determine the STATUS/ID information
and the service routine for this particular device will be
called.
Chained interrupts allow multiple service routines to besimultaneously connected to a particular vector. All
chained routines will be executed in response to an
interrupt for a particular vector. It is the responsibility
of the ISR to determine if its device is active.
7/29/2019 03ddPolIntr.pdf
18/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-18
Converting Interrupt Number toInterrupt Vector
INUM_TO_IVEC (intNum)
Converts an interrupt number to interrupt vector in anarchitecture dependent manner:
Interrupt InterruptNumber Vector
Interrupt Table Example (MC68K)012
3
048
12
255 1020
Macro defined in iv.h.
7/29/2019 03ddPolIntr.pdf
19/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-19
Installing an ISR
STATUS intConnect (vector, routine, param)
vector The interrupt vectorroutine The address of the user-defined ISR
param Any value to be passed to this ISR
Example:
#include "iv.h"
...
void myISR();...
if (intConnect (INUM_TO_IVEC(intNum), myISR, 0) ==
ERROR)
return (ERROR);
The vector is NOT the interrupt number. It is the address offset of the
entry in the interrupt vector table.
The param is sometimes used to indicate which board is interrupting
when managing multiple boards of the same type. This avoids having
to write two separate ISRs. For example:
/* connect first boards ISR */
intConnect (INUM_TO_IVEC(intNumberBoard0), myIsr, 0);
/* connect second boards ISR */
intConnect (INUM_TO_IVEC(intNumberBoard1), myIsr, 1);
...
void myISR (int boardNumber)...
7/29/2019 03ddPolIntr.pdf
20/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-20
ISR Restrictions
No I/O system calls
q Dont call routines that make I/O system calls, e.g.
printf( ) No blocking
q Dont take a semaphore or call any routine that maytake a semaphore, e.g. malloc( )
q No taskDelay( )
Do not do anything that requires a task contextq Dont use 0 for a tid, e.g. taskSuspend (0)
q Dont use mutual exclusion semaphores
I/O system calls, e.g. read( ) and write( ), typically block until the
device is ready to satisfy the request.
It is perfectly OK to read or write to device registers (as long as there is
no blocking).
7/29/2019 03ddPolIntr.pdf
21/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-21
What Can Be Done In An ISR
Calling semGive( ) or semFlush( ) on a binary orcounting semaphore
Reading or writing to memory, including memory-mapped I/O
Making non-blocking writes to a pipe or message queue
Calling logMsg( )
Calling any routine in lstLib or bLib
Calling any routine in rngLib except rngCreate( )
Calling wdStart( ) and wdCancel( )
Calling taskSuspend( ), taskResume( ) or
taskPrioritySet( )
See Programmers Guide for a complete list.
7/29/2019 03ddPolIntr.pdf
22/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-22
ISR Guidelines
Keep ISRs short
The general rule is Do as little as possible.
The longer the ISR, the longer the delay for lower or
equal priority interrupts.
Avoid using floating point operations in an ISR.
The shorter the ISR, the easier it is to debug.
It is the responsibility of the ISR to determine if itsdevice is active. This is required if the ISR is ever to be
installed on a system with chained interrupts.
To use floating point operations in an ISR, you must save and restore the
registers yourself. See fppALib for save and restore routines.
7/29/2019 03ddPolIntr.pdf
23/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-23
Common ISR Scenarios
Call semGive( ) and do everything else at task time.
Read from the device and place data read into pipe or
message queue.
Example:
SEM_ID semId;
...
intConnect (INUM_TO_IVEC (intNumber), semGive, semId);
...void myFunc() /* task time */
{
FOREVER
{
semTake (semId, WAIT_FOREVER);
.
. /* deal with device */
.
}
}
7/29/2019 03ddPolIntr.pdf
24/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-24
Enabling Interrupts
In systems with a bridge to an external, shared bus, it is
necessary to program the bridge chip to pass interrupts
asserted on that bus to the processor. Bridge chips for the VMEbus will often have this ability.
It is essential that only one processor in a VME system
service a particular VME interrupt level.
sysIntEnable (intLevel)
Makes target respond to VMEbus interrupts of specified
interrupt level.
There are seven interrupt levels on a VME bus.
Not all interrupt levels may be available on all BSPs.
Some BSPs multiplex VMEbus interrupts. For example, VMEbusinterrupt levels 3 and 4 may be multiplexed into interrupt level 3.
Some BSPs (e.g. hkv2f) require manual handling of the interrupt
acknowledge cycle for certain interrupts levels. See your target specific
documentation.
Some boards may require a hardware jumper change.
7/29/2019 03ddPolIntr.pdf
25/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-25
Debugging ISRs
Whenever possible, start simply and build slowly.
Use logMsg( ) to display information to the console.
Use sprintf( ) to log data into memory:
char * ptr;
...
ptr = (char *) malloc (SIZE_OF_BUFFER);
...
void myISR ()
{
...ptr += sprintf (ptr, "%d", data);
Write data into a location of memory that is not cleared
on reboot. This is particularly helpful when debugging
interrupts that are crashing the system.
How do you find a memory location that is not cleared on reboot? This
requires some trial and error. The most common place to find this is
between the end of the Interrupt Vector Table (typically address 0-
0x400) and the beginning of vxWorks (typically loaded at 0x1000), e.g.address 0x400. You could write to the location you are interested in,
reboot the system and check to see if the contents of the memory have
changed.
7/29/2019 03ddPolIntr.pdf
26/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-26
Polling and Interrupt Handling
Overview
Polling
Interrupt Handling
3.4 Design Considerations
7/29/2019 03ddPolIntr.pdf
27/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-27
Task Synchronization
Task A waits until an event occurs on the device by
calling semTake( ).
When the polling task detects the event, it calls
semGive( ).
Task A returns from the semTake( ).
Task APoll TaskDevice
The event could be:
q a state change
q data received
q device available for writing
q an error condition
To synchronize multiple tasks, have the poll task call semFlush( ) instead of
semGive( ).
7/29/2019 03ddPolIntr.pdf
28/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-28
Task Synchronization
Task executes semTake( ) and blocks.
When device receives data it generates an interrupt.
The ISR calls semGive( ).
The task returns from the semTake( ).
Device ISR Task
7/29/2019 03ddPolIntr.pdf
29/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-29
Data Buffering
When data is available on device, the poll task reads it
and puts it in shared memory, ring buffer, linked list,
pipe or message queue.
Cooperating task gets data from buffer.
taskbufferPoll TaskDevice
For output reverse process:
q Task writes data into buffer.q When device is ready to receive data, poll task copies data from
buffer to device. Advantages of using a pipe or message queue:
q Provides task synchronizationq Guards against mutual exclusion problems
If shared memory, ring buffers, or linked lists are used, the driver must:q insure mutual exclusion, if necessaryq provide its own means of task synchronization
7/29/2019 03ddPolIntr.pdf
30/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-30
Data Buffering
When data available on device, the device generates an
interrupt.
In the ISR, read data from device and put it on a ring
buffer, pipe or message queue.
Task reads data from device by getting data from buffer.
Device ISR taskbuffer
As we saw with polled devices:
q pipes and message queues have the advantage of providing built-inmutual exclusion and task synchronization facilities.
q shared memory, or ring buffers provide no mutual exclusionprotection or task synchronization facilities
7/29/2019 03ddPolIntr.pdf
31/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-31
Design Questions: Speed vs.Robustness
The assumptions made dictate design choices:
q
Assumptions about the hardware environmentmultiple I/O boards?
always have the same jumper settings?
q Assumptions about the intended use
always have the same devices connected?
will the action to be performed after an event ever change?
The more that may be assumed, the faster the driver can be. The nature of the device may dictate a certain level of
performance (i.e. there may be timing restrictions).
When in doubt, dont assume!
7/29/2019 03ddPolIntr.pdf
32/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-32
Design Questions: Who Handles theAction?
Typically, the driver handles the events (the hardware
changed) and leaves it to an application program tohandle the actions (what to do about it).
Sometimes it is not obvious what constitutes an
event.
This scheme, although flexible, typically requires a
synchronization and data communication mechanism.Which is most appropriate depends on speed vs.
robustness.
Using semaphores for synchronization is very fast but does not provide
any data.
Using message queues provides both synchronization and data communication.
Using pipes provides the benefits of message queues plus those of the standard
I/O system interface.
7/29/2019 03ddPolIntr.pdf
33/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-33
Case Study
Input board not interrupt driven.
Status Light should reflect status of remote railroad
crossing.
Remote RR Crossing
Input Board
Output BoardStatus Light
Sensor
How do you write your driver?
q Will the number of railroad crossings change?
q Will the method of monitoring the railroad crossings ever change?
Could the action (lighting the light) change?q What is more critical: speed or extensibility/maintainability?
7/29/2019 03ddPolIntr.pdf
34/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-34
Driver Cautions
Mutual exclusion
q Is required for multiple tasks modifying data
structures at the same timeq Is required for multiple tasks attempting to program
the device at the same time
q Is provided by mutual exclusion semaphores
Race conditions
q Can be avoided with mutual exclusion semaphoresor taskLock( )
q Avoidance may require non-atomic test and set whenthe condition tested may be changed by apreempting task
Remember that your ISR can cause mutual exclusion and race
conditions.
Try to restructure your design to avoid task/interrupt conflicts.
As a last resort, use intLock( ) to lock out interrupts.
7/29/2019 03ddPolIntr.pdf
35/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-35
taskLock/ taskUnlock
taskLock( ) prevents task preemption until
taskUnlock( ) is called.
Does not disable interrupts.
Task preemption is not enabled until as many
taskUnlocks as taskLocks have been called.
Performing any action which blocks will enable task
preemption.
Example:
taskLock();
...
/* critical region: task preemption disabled */
...taskUnlock();
7/29/2019 03ddPolIntr.pdf
36/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-36
intLock/ intUnlock
intLock( ) disables interrupts until intUnlock( ) is
called.
Returns an architecture dependent integer that must bepassed to intUnlock( ).
Does not disable task preemption.
May be called at interrupt time.
Example:
key = intLock();
...
/* critical region: interrupts disabled */
...intUnlock (key);
7/29/2019 03ddPolIntr.pdf
37/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-37
Interrupt Level Caveat
VxWorks enables interrupts on context switches.
Use intLock( ) to mask your interrupts; do not raise the
interrupt level at task time.
The intLevelSet( ) routine (which allows raising the interrupt level)
should only be used at interrupt time. If used at task time, a higher
priority interrupt could cause a context switch which would end up
enabling interrupts.
7/29/2019 03ddPolIntr.pdf
38/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-38
Test and Set
BOOL sysBusTas (addr)
If the value pointed to by addr is not set, function sets it
and returns TRUE; otherwise returns FALSE.
The test-and-set is an atomic operation.
Example:
char * addr;
...
/* wait until available */while (sysBusTas (addr) == FALSE)
taskDelay (ticks);
...
/* reset test address when done */
*addr = 0;
There is a vxTas( ) routine, written in assembler, that could be used for
local test-and-set operations.
Not all boards support sysBusTas( ).
7/29/2019 03ddPolIntr.pdf
39/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-39
Review
Polling techniques.
Mutual exclusion & race conditions tools:
Routines Description
semGive/semTake Uses mutex semaphores
taskLock/taskUnlock Prevents/allows task
preemption
intLock/intUnlock Prevents/allows interrupts
sysBusTas Atomically tests-and-sets a
memory location
7/29/2019 03ddPolIntr.pdf
40/40
Wind River SystemsTornado Device Driver Workshop Copyright Wind River Systems 3-40
Review
Routine Description
intConnect Installs an ISR
sysIntEnable Enables a VMEbus interrupt
level
INUM_TO_IVEC Converts interrupt number to
vector