Real Time System 03 Philip A Lapalante 2nd Edition
Real Time System 03 Philip A Lapalante 2nd Edition
Real Time System 03 Philip A Lapalante 2nd Edition
Real-Time
l4l
Chap.6l Real-TimeKem
.\
Chao. 6 I Real-Time Kemels r43
Userinterface Operatingsystem
Shell
Fileanddisksupport Executive
lnterorocessor
communication
andsvnchronization Kemel
Taskscheduling Micro-kemel
Threadfaskcontrol
Blockmanagement Nanekemel
Hardware
*IINIX is not an acronym, and therefore need not be capitalized unless referring to the
'Unix' is used throughout this text-
registeredtrademark. Generally, the term
144 Chap. 6 I Real-Time Kerrnl.
6.1 POLLEDLOOPSYSTEMS
Polled loop systemsare the simplest real-time kernel. Polled loops allow for t'as
responseto singledevicesbut can't do much else.In a polled loop system,a single
andrepetitivetestin'structionis usedto testa flag thatindicateswhetheror not some
eventhas occurred.If the eventhas not occulred,then the polling continues.No
intertaskcommunicationor schedulingis neededbecauseonly a sinqletask exists
I EXAMPLE 6.1
A software system is neededto handle packets of data that arrive at a rate of no more than I per
second.A flag called "Packet_here" is set by the network, which writes the data into the CPL-*
memory via DMA. The data are available when Packet_here= 1. Using a Pascalcode fragment, ue
can describea polled loop to handle such a system:
wntre L j < u _ to
ro { do forever }
begrln
if Packet here=TRUE then { flaq set? }
beqin
j -h i q *l-r^ 'l-ts -
process-data; ii L r - - J ny Lr vnece oq ne rr r r o u nr^^^--^a
V M q J - s J L r I s u q L C
6.1"1PolledLoopwith Interrupts
A variation on the polled loop usesa fixed clock intemrpt to wait a period of t
between when the flag is determined to be TRUE and when the flag is reset
FALSE. Such a systemis used to treat events that exhibit a phenomenon
as switch bounce.
Every elgctrical engineerknows that it is impossible to build r switch
can changefrom its OFF condition(e.9.,0 volt) to its ON condition(e.g.,5 vol
instantaneously. A typical responsefor such a switch is given in Figure 6.3. I
example,eventstriggeredby pickle switches,levers, and keyboardsall exhr
this phenomenon.
If we wait a sufficientamountof time afterthe initial triggeringof the evenL
can avoid interpreting the settling oscillations as events. These are, of
spuriouseventsthat would surely overwhelm our little polled loop handler.A
L.
6.1 I PolledLoop Systems lJ5
Srn\\ch
position
On
off
Throwswitch
I EXAMPLE
6.3
A polled loop system is used to handle an event that occurs randomly but no more than once per
second.The event is known to exhibit a switch-bounceeffect that disappearsafter 20 milliseconds.
A 10-millisegond fixed-rate interrupt is available for synchronization.The event is signaled by an
extemal device that sets a memory location FLAG to TRUE.
In Pascal a synchronizedpolled loop would look like:
begin
FLAG = TRUE then
(
if ^ --^ ^ t l^ ! ^ ^ ts ^ i I
begin
'
counter : = 0; { initialize bounce counrer
whife counter < { wait }
-q
FLAG : = FALSE { rpsof F\rprr f- }
end
end
begin
counter := councer+i
end
Intemrpts are enabledin an initialization routine Notice that we wait for three trcks of the interrupt
routine in order to ensure that we wait at least 20 milliseconds. I
146 Chap.6 I Real-Time
Keme
In summary, polled loop systems are simple to write and debug, and th€
responsetime is easy to determine.As suggested,polled loops are excellent for
handling high-speeddata channels,especiallywhen the eventsoccur at widely
dispersed intervals and the processor is dedicated to handling the data
channel.
Polled loop systemsmost often fail, however, becausebursting of events
was not taken into account (this is discussedin Chapter 10). Furthermore,polled
loops by themselvesare generally not sufficient to handle complicated systems
Finally, polled loops inherently waste CPU time, especially if the event being
polled occurs infrequently.
6.2 PHASE/STATE.DRIVEN
CODE
I EXAMPLE6.4
A simple process consists of three states.At the end of each state a flag is set and the processis
terminated. Upon restarting, the process resumes where it left off. The following Pascal code
fragment illustrates this.
procedure taski
begin
n:ca f] an af
1: beqin
perf orm3art_L; /* dn nh:<a 1 nrnnoc<inn */
flag z= 2
end
2: begin
perf ormJart_2; /* do phase 2 processing */
flag := 3
end
s+c.6.2 t Phase/ State-Diven Code 747
3: begin
-l
perf ormjart-3; /
/* dn
vv nv rh ar eqv c nre-e-<S_:::
flag := 1
end
end
end T
This simple nested if-then structure is really just a special case of FSA-
driven code.
T EXAMPLE
6.5
A finite state automaton can be implemented easily in Pascal or another suitable language.First, a
two-dimensional array is constructed containing the table representationof the FSA. Let states be
the variable type depicting the set of states.alphabet the variable type representing the input
alphabet, and table the transition table.
The following code fragment can then be used to read a streamof inputs using proceduregel
(not shown). At the time the cuffent stateis determined,an appropriateprocessis executed.The code
determinesthe final state of the automata after the last input is read.
state: states;
input : aiphabet;
m iq qjzc ol alnhabec
table: array[1..m] o f tabfe_row; {
--r^ ^F
6.3 COROUTINES
I EXAMPLE
6.6
Consider a system in which two processes are executing "in parallel" and in isolation.
executing phaseAl, process_A retums control to the central dispatcher by executing "exiL"
dispatcher initiates process_B, which executesphaseBl to completion before retuming contmi
the dispatcher.The dispatcher then starts processA, which begins phaseA2 and so on. The
code for such a scheme is depicted below:
hoai n
nl-racaA?.
-L-^^A?. ?. nl.rrcaF.?.
Irrro D snJ ,
Sec.6.3 I Coroutines t49
4z phaseA4; 4: phaseB4
5: phaseA5 end
enC
end
where stateA and stateB are state counters thu are managedby the dispatcher.Such a schemecan
be extended to any number of processes,each broken into any number of phases. I
I EXAMPLE6.7
A polled loop routine, Taskl, is to monitor an event flag, "event." If the flag is not set, Taskl exits.
If the flag is set, then a processroutine, process-event,is called. "State" is used to keep track of the
state of the polled loop. The Pascal code for this system is
procedure Taskl;
begin
case state of
2: begin
state:=1 { reset state fy'ag }
process-event; f r
nrnnocc
F ! v v v v v
arrant ]
Such a schemereducesthe amounrof time wasted polling the event flag, and allows for processing
time for other tasks. I
Note that if there is only one coroutine, then it will be rep€ated cycbcally ad
inftnitum. Such a system is called a cyclic executive.
In short, coroutines are the easiesttype of "faimess scheduling" that can be
implemented. In addition, the processes can be written by independent parties,
and the number of processes need not be known beforehand. Finally, certain
Chap. 6 I Real-TimeKernels
DRIVENSYSTEMS
6.4 INTERRUPT
'Jump-to-self'
In intemrpt driven systems, the main program is a single
instruction.'The various tasks in the system are scheduledvia either hardware
or software intemrpts, whereas dispatching is performed by the intemrpt-
handling routines.
The intemrpts in an interrupt driven system may occur at fixed rates
(periodically), aperiodically, or both. Tasks driven by intemrpts that occur
aperiodicallyare called sporadic taskslll5l. Systemsin which intemrpts occur
only at fixed frequencies are called fixed-rate systems, those with intpmrpts
occurring sporadically are known as sporadic systems,and those with intemrpts
occurring both at fixed frequenciesand sporadically are called hybrid systems.
When hardware scheduling is used, a clock or other extemal device issues
intem.rpt signals that are directed to an intemrpt controller. The intemrpt-
controller issuesintemrpt signals dependingon the order of arrival and priority of
the intemrpts involved. If the computer architecturesupportsmultiple intemrpts,
then the hardware handlesdispatching as well. If only a single interrupt level is
available,then the intemrpt-handling routine will have to read the intemtpt vector
on the intemrpt controller, determine which intemrpt occurred, and dispatch the
appropriate tasks. Some processors implement this in microcode and so the
operating systemsdesigner is relieved of this duty.
In any case, a snapshot of the machine-called the context-must be
preserved upon switching tasks so that it can be restored upon reinitiating the
intemrpted process. The context includes the contents of certain registers, the
program counter, and other entities that could be altered by another process.
6.4.1 ContextSwitching /
The most important part of the real-time operation of the intemrpt driven system
is context switching. Context switching is the process of saving and restoring
sufficient informafion for a real-time task so that it can be resumed after being
intemrpted. The context is ordinarily saved to a stack data structure.
I IntemrptDriven Systems 151
l. Contentsof registers
2. Contents of the program counter
3. Contentsof coprocessorregisters
4. Memory page registers(seeChapter8)
5. Memory-mappedI/O location mirror images(seeSection2.3.2)
6. Specialvariables.
Normally, within the intemrpt handlers, intemrpts are disabled during the
critical context-switchingpenod. Sometimes,however, aftet sufficient context
has been saved,intemrptsmay be enabledafter a partial contextswitch in order
to handlea burst of intemrpts,to detectspuriousintenupts,or to handlea time-
overloadedcondition.
6.4.1.2 Stack Model The stack model for context switching is used
mostly in embeddedsystemswhere the number of real-time or intem-rpt-driven
tasks is fixed. In this case,context is savedby the intemrpt handler.Contrast this
schemewith the task-control block model, which is used in more complicated
real-timeoperatingsystemsand is discussedin a later section.
In the stack model, each intemrpt handler is associatedwith a hardware
intemrpt and is invoked by the CPU, which vectors to the instruction storedat the
appropriate intemrpt-handler location. The context is then saved to a specially
designatedmemory areathat can be static,in the caseof a single-intemtpt system,
or a stack, in the case of a multiple-interrupt system. This type of stack
managementis discussedin Chapter8.
I EXAMPI.E 6.8
Consider the following code for a partial real-time system, writted in C and consisting of a simple
jumpto-self and three interrupt handlers,which savescontext using the siack model. The interrupt
handlers' starting addressesshould be loaded into the appropriate interrupt vector location upon
inirialization. Alternatively, this can 6e performed at link time by the link editor or linker control file.
t
save context on stack */
save(context); /*
task3 O ; /* execute task 3 */
restore context from stack */
restore(conEext); /*
{
Thg procedure "save" involves the saving of certain registers to a stack area, whereas "restore"
resto;es those registers from the stack. I
6.4.2 Round-RobinSYstems
pd Task3
o
Task2 Task2
Task 1 Task 1
PreemptivePrioritySystems
A higher-priority task is said to preempt a lower-priority task if it interrupts the
Iower-priority task. That is, the lower-priority task is still running while the
higher-priority task is about to begin. Systems that use preemption schemes
insteadof round-robin or first-come-first-servescheduling are called preemptive
priority systems.The priorities assignedto eachintemrpt are basedon the urgency
of the task associatedwith that intemrpt (seeFigure 6.5).
I EXAMPLE6.9
The nuclearpower station monitoring systemrepresentsa fixed-prioriry system.While the handling
cd intruder events is critical, nothing is more important than processirg the core over-temPerature
T
6.10
I EXAMPLE
Dynamic-priority systemscan be found in many threat-managementsystems,such as those related
to military aircraft. The aircraft's threat-managementcomputer may be able to track up to six enem\
aircraft. Each of theseis tracked by a processin a dynamic-priority multitasking computer' At sorn€
fixed rate, the relative threat of each enemy aircraft is recomputedbasedon proximity, posture, and
other factors. The priority of each of the tasks managing the individual threats is then readjusted
I
I EXAMPLE 6.11
Consider the Unix operating system. In Unix, any task that makes a system call cannot tu
preemptetl;that is, the set of Unix system servicesprovided has highest priority. This is a problen"
iince a low-priority task-making system call cannot be preempted.Real-time Unix solutions striyt
ao rectify this problem (see Chapter 14). I
6.12
I EXAMPLE
In our aircraft navigation system,the task that gathersaccelerometerdata every 5 miiliseconds br
the highest priority. The task that collects gyro data, and compensates these data and fu
accelerometerdata every 40 milliseconds, has the second highest priority. Finally, the task fu
updatesthe pilot's display every secondhas lowest priority. I
_----1
I InterruptDriven Systems 155
Majorand MinorCycles
Some common terminology applies when tasks are assignedto run at specific
frequencies (usually in periodic systemsbut also in nonintemrpt driven cyclic
executives).If a time line is drawn showing the scheduling of tasks and if the
assignment uses rate-monotonic discipline or is a nonintemrpt driven cyclic
executive, then the scheduling sequencerepeats itself after a certain period of
time. This sequenceis called a major cycle.If within the major cycle, smaller
sequencesalso repeat, they are called minor cycles. For example consider the
following nonintemrpt driven cyclic executtve:
while(forever) do
begin
process_a;
process-b;
process_a;
proGess_c;
process_a;
156 Chap. 6 I Real-Time Kemels
nrn-6cc b
h.
d .
end
Notice how pr:ocess-a runs four times more often than process-c or
process_d and twice as often as process-n. Here the major cycle is given by the
process sequence abacabad with minor cycles abad, abac, ab, ac, and ad.
6.4.5 HybridSystems
Hybrid systemsinclude intemrpts that occur at both fixed rates and sporadically.
The sporadic intemrpts may be used to handle a critical error that requires
immediate attention, and thus have highest priority. This type of system is
common in embeddedapplications.
Another type of hybrid system found in commercial operating systemsis a
combination of round-robin and preemptive systems. In this system, tasks of
higher priority can always preempt those of lower priority. However, if two or
more tasks of the samepriority are ready to run simultaneously,then they run in
round-robin fashion.
To summarize,intemrpt-only systemsare easy to write and typically have
fast responsetimes becauseprocess scheduling can be done via hardware.
Interrupt-only systems are a special case of foreground/backgroundsystems,
which are widely used in embeddedsystems.
One weaknessof intemrpt-only systems,however, is the time wasted in the
jump-to-self loop and the difficulty in providing advanced services. These
services include device drivers and interfaces tc multiple layered networks.
Another weaknessis vulnerability to malfunctions owing to timing variations.
unanticipated race conditions, hardware failures, and so on. Some companies
avoid designsbasedon intemrpts for this reason.
SYSTEMS
6.5 FOREGROUND/tsACKGROUND
L *4
Sec.6.5 I Systems
Foreground/Background 157
6.5.1BackgroundProcessing
The questionof what processingshouldbe placedin backgroundis an easyone:
anything that is not time critical. The backgroundprocessis the processwith the
lowest priority. This task will alwaysexecuteto completion,unlessthe systemis
time-overloaded(all processingtime is spent in the foreground). But the rate at
which the backgroundwill be executedcan be very low and dependson the time-
loading factor. That is, if p representsthe time-loading for all the foreground
processes(seeChapter9 to calculatethis), and if e is the executiontime of the
background process,then the background processexecution period, /, is
(6.1)
I - p
6.13
T EXAMPLE
Ir the space shuttle inertial measurementunit computer, a process known as RAM scrubbint is
performed[95]. The memory card of this system is equipped with a Hamming code error correction
and detection schemewhich, for a l6-bit word, can detect l-, 2-, and some 3-bit erron, and correct
all 1- and some 2-bit errors. The device corrects these enon on the data bus, however, and not in
158 Chap.6I Real-TimeKer
memory. By consecutivelyreading and then writing back each memory location, the correctedd
are restored in RAM. This process helps to reduce errors perpetrated against RAM by charl
particles present in space, or in the presenceof a nuclear event (such as in our nuclear pol
station), called single event upsets (see Chapter 11). RAM scrubbing is not suggestedas
foreground process.
6.5.2 Initialization
Initialization of the foreground/backgroundsystem consists of the followj
steps:
1. Disable intemrpts.
2. Set up intemrpt vectors and stacks.
3. Perform self-test.
4. Perform system initialization.
5. Enable intemrpts.
6.5.3 Real-Time
Operation
The real-time or foreground operation for the foreground/backgroundsystem
the same as that for the intemrpt-only system.
I EXAMPLE 6.14
Supposeyou wish to implement an interrupt handler for a 2-addresscomputer architecturewit
single intemrpt. The EPI and DPI instructions can be used to enable and disable the inten
explicitly, and we will assumethat upon receiving an intem.rpt, the CPU will hold off all ot
intemrpts until explicitly re-enabled with an EPI instruction.
For context-switching purposes,we wish to save the eight general registers,R0-R7, on
stack. Note that context switching involves saving the status of the machine as it is used by
background process.The foreground process will run to completion so its context is never sav
Further assume that the CPU will save the prografr counter at the time of intemrptior
memory location 6, and the address of the intemrpt-handler routine (the intemrpt vector) is sto
in memory location 5.
The foilowing code should be used to initialize the foreground/backgroundsystem:
Sec. 6.5 I Foreground/BackgroundSystems 159
Of course other initialization, such as initializing flags and other data, should be performed
before enabling intemrpts.
If symbolic memory locations reg0 through regT are used to save the registers, then the
interrupt handler, coded in 2-addresscode, might look as follows:
In many computers,block save and restore instructions are available tq save and restore a set
of registers to consecutive memory locations.
AIso note that our interrupt handler does not permit the interrupt to interrupt itself. If this is
to be accomplished, or if more than one interrupt routine existed, a stack rather than just static
memory would be needed to save context.
The background program would include the initialization procedure and any processing that
was not time-critical and would be hrinen in the high-order language.If the program were to b€
written in C, it might look like this:
void main(voior
i
rl,.r
l' '
REAL-TIME
6.6 FULL.FEATURED
f,.' OPERATINGSYSTEMS
F'
Fr,-
We can extend the foreground/backgroundsolution into an operating system
adding additional functions such as network interfaces, complicated der
drivers, and complex debugging tools. These types of systems are read
available as commercial products.
Such systems rely on a complex operating system using round-rob
preemptive priority, or a combination of both schemesto provide scheduling;t
operating system represents the highest priority task, kemel, or supervi
Commercial real-time operating systems are most often of this type. The ta
control block model is most often used in these types of systems becauset
nurnber of real-time tasks is indeterminate and dynamic.
6.15
T EXAMPLE
Real-time Unix representsan example of such a full-featured operating system. There are sar
commercial versions of this well-known operating system with specific enhancementsfor reak
operation, most notably, kernel preemption.
In standard Unix, a process that makes system calls is not preemptable.Even if the c{
processis of low priority, it continues executing until it is stoppedor completed. In real-time Li
I Full-Featured Real-Time Operating Systems 161
preemption points have been built into the kemel so that system calls can be preempted without
running to completion. This radically reduces responsetimes.
Real-time Unix includes all the standard Unix device drivers and network interfaces, and
usually includes other features-such as memory locking and contiguous file allocation-to
improve real-time performance (see Chapter 8). For an excellent study of the real-time Unix, the
reader is refened to [58]. t
Task-Control
Block Model
The task-control block model is the most popular method for implemenring
commercial, full-featured, real-time operating systems because the number of
real-time taskscan be variable. This is useful in interactive on-line systemswhere
tasks (users)come and go. This techniquecan be used in round-robin, preemptive
priority, or combination systems,although it is generally associatedwith round-
robin systemsin which a single fixed intemrpt or clock tick is used.In preemptive
systems,however, it can be used to facilitate dynamic task prioritization. The
main drawback of the task-control block model is that when a large number of
tasks are created, the overhead of the scheduler can become significant. what
follows is only a sketch of the technique. To fully implement it, you need to
consult a text that is devotedto the technique,such as [134].
1. Executing
2. Ready
3. Suspended
4. Dormant
Programcounter
Taskstatus
Task lD #
Contentsol register0
Contentsof registern
Other context
Figure 6.6 A typical task-control blocl
Tasks in the ready state are those that are ready to run but are not running.
A task enters the ready stateif it was executingand its time slice runs out, or if
it was preempted.If it was in the suspendedstate,then it can enterthe ready state
if an eventthat initiatesit occurs.If the taskwas in the dormantstate.thenit enters
the ready stateupon creation(if anothertask is executing).
Tasks that are waiting on a particular resource,and thus are not ready, are
said to be in the suspendedor blocked state.
The dormanl stateis usedonly in systemswhere the numberof task-control
blocks is fixed. (This allows for determiningmemory requirementsbeforehand,
but limits availablesystemmemory.)This stateis best descnbedas a task that
existsbut is unavailableto the operatingsystem.Once a task has been created,it
can becomedormantbv deletineit.
6.8 POSTX
Much has been made of the POSIX standard (IEEE Portable Operating System
Interfacefor ComputerEnvironmerits,IEEE 1003.1-1990).The standardprovides
for standardcompliance criteria for operating system servicesand is designedto
allow applications programs to write applications that can easily port across
operating systems.At this writing, systernscan be certified as compliant with the
1003.1standard.
However, 1003.1(sometimescalled POSX.1) doesnot specificallysuppor
real-time applications(althoughreal-time operatingsystemscan run non-real-tirne
applicationsin compliance).A new standard.POSIX 1003.4hasbeenproposedto
rernedi the lack of real-time support. Standard 1003.4 includes five sectionsthar
are,at this writing, in various stagesof approval.Thesesectionsare
.:- -_<
Sec.6.8 | POSIX 165
T POSIX.4
T POSIX.4a
T POSIX.4b
I POSIX.13
I POSIX.4c
Many of the featuresthey proposeto provide are discussedin later chaptersof the
text. However, for completeness,let us summarize them here.
POSIX.4 providesthe basereal-timeextensionsto POSIX.I such as
r Thread management
r Signals
I Processscheduling
r Condition variables
r Thread scheduling
r Thread-safereentrant functions.
I Processspawn
r Time-outs on blocking functions
I Execution time monitoring
r Sporadic server scheduling
r Device conftol
r Inrcrrupt conffol.
EXERCISES
For the real-time systems below, described in Chapter l, discuss which real-time
architectureis most appropnate.
(a) Navigation system
(b) Airline reservation system
(c) Nuclear power station
2. Explain which type of real-time kernel would be most appropriate for the following
systems,and why:
(a) An air traffic control sYstem
(b) A batch uFate system
(c) A video arcade game
3. Using whatever assumptionsyou feel necessary,discuss the differences and similarities
in performing a context switch in O-, l-,2-, and 3-addressmachines.
4. Rewrite the polled loop code in Example 6.1 in
(a) C or C++
(b) Ada or Ada 95
(c) Modula-2
5. Using pseudocode,describe the coffee machine in Example 5.4. Imagine now that a
super coffee machine is built which can serve two cups of coffee simultaneously.
Describe such a machine using coroutines and phase-drivencode. Use the fact that there
is a fixed time to brew coffeeltea,to pour milk and sugar.Also assumethere is only one
brewer and one pourer for sugar and milk.
6. Rewrite the synchronizedpolled loop code in Example 6.3 in
(a) C or C++
(b) Ada or Ada 95
(c) Modula-2
7. Rewrite the statc-driven code in Example 6.4 in
(a) C or C++
(b) Ada or Ada 95
(c) Modula-2
8. Rewrite the table-driven finite state automaton in Example 6.5 in C, using pointers to
functions.
9. Rewrite the coroutine system Example 6.6 in
(a) C or C++ 1
(b) Ada or Ada 95
(c) Modula-2
10. Rewrite the coroutinesystemin Example6.7 in
(a) C or C++
(b) Ada or Ada 95
(c) Modula-2
Testingthe
11. A polledloop systempolls a discretesignaleyery50 microseconds.
and vectoring to the intemrpt-processingroutine takes 40 microseconds.If it takes 6t
milliseconds to pJocess the intemrpt, what is the minimum resPonse time for
interrupt?What is the maximumresponsetime?.
systemin Example6.8 in
12. Rewrite the foreground/background
(a) Pascal
(b) Ada or Ada 95
(c) Mqdula.2
Exercises r67
Task I ,10 3
Task 2 20 I
Task 3 30 2
2?
If the tasks arrive in the order 1,2,3, what is the time neededto completetask
L4. Should a routine be allowed to interrupt itselfl If it does,what does this mean?
15. What criteria are needed to determine the size of the run-time stack in a multiple-
interruptsystem?What safety precautionsare necessary?
16. What is the worst case fesponse time for the background process in a foreground/
backgroundsystemin which the backgroundtask requires100 millisecondsto complete,
the foreground task executesevery 50 milliseconds and requires 25 milliseconds to
(Recall that
complete,and context switching requiresnQ more than 100 microseconds'
the background task can be preempted.)