real time system 05 philip a lapalante 2nd edition

22
18 4 Chap.7 I Intertask Communication and Synchroniza 3. Hold and wait 4. No preemPtion Countering any one of the four necessary conditions is needed to prev deadlock. Mutual exclusion applies to those resources hat can't be shared (e printers, disk devices, output channels). Mutual exclusion can be removed I making such resources shareable, or example, hrough the use of SPOOL which allow these resources to appear to be shareable to an applicat task. The circular wait condition occuts when a circular chain of processes that hold resources eeded by'other processes urther down the chain (such a cyclic processing). One way to eliminate circular wait is to impose an ordering the reslurces and o force all processes o request esources n increasing rde enumeration. For example, consider the following list of resources and th (increasing) order number. Disk Printer Motorconffol Monitor Now if a process wishes o use both th e printer and the monitor, t must req first the printer and then the monitor' It can be proved that such a sch eliminates he possibility of deadlock. The hold and wait condition occurs when processesequest esources then ock that resource ntil subsequent esource equests are hlled. c)nesolu to this problem s to allocate o a process all potentially required esources t same time. This can, however, ead to starvation o other processes' Anoi solution s never to allow a process hat locks more than one resource at a til For example, when writing one semaphore-protected isk file to another, ock file and copy a record, unlock that file, lock the other file, write the record' so on. This, of course, an ead o poor resource tilization as well as window opportunity for other processes to interrupt and interfere with reso utilization. resource and signal the semaphore. f we allow the higher priority task to pree the lower one, then the deadlock can be eliminated. However, this can lea starvation in the low-priority process as well as to nasty interference probl I 2 3 4

Upload: anshuljain77

Post on 30-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 1/22

184 Chap.7 I IntertaskCommunicationand Synchroniza

3. Hold and wait

4. No preemPtion

Countering any one of the four necessaryconditions is needed to prevdeadlock.

Mutual exclusion applies to those resources hat can't be shared (e

printers, disk devices,output channels).Mutual exclusioncan be removed I

making such resourcesshareable,or example, hrough the use of SPOOL

which allow these resources to appear to be shareableto an applicat

task.

The circular wait conditionoccutswhen a circular chain of processes

that hold resources eededby'other processesurther down the chain (suchacyclic processing).One way to eliminatecircularwait is to imposean ordering

the reslurcesand o forceall processeso request esourcesn increasing rde

enumeration.For example, considerthe following list of resourcesand th

(increasing)order number.

DiskPrinterMotor conffolMonitor

Now if a processwishes o useboth the printer and the monitor, t must req

first the printer and then the monitor' It can be proved that such a sch

eliminates he possibility of deadlock.

The hold and wait conditionoccurswhenprocesses equest esources

then ock that resource ntil subsequentesourceequestsarehlled. c)ne solu

to this problem s to allocate o a processall potentially required esources t

sametime. This can, however, ead to starvation o other processes'Anoi

solution s never to allow a process hat locks more thanone resourceat a til

For example,whenwriting one semaphore-protectedisk file to another,ock

file and copy a record, unlock that file, lock the other file, write the record'

so on.This, of course, an ead o poor resource tilization aswell as window

opportunity for other processes tointerrupt and interfere with reso

utilization.

resourceand signal the semaphore. f we allow the higher priority task to pree

the lower one, then the deadlock can be eliminated. However, this can lea

starvation in the low-priorityprocess as well as to nasty interference probl

I

234

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 2/22

Sec.7.6 Deadlock

(For example,what if the ow-priority taskhad locked the printer for output, and

now the high-priority task startsprinting?)

Two other ways of combatingdeadlock are to avoid it throughavoidance

algorithms like the Banker's algorithm, or to detect it and recover from it.

Detection of deadlock is not always easy, although in embedded systems

watchdog imers can be usedand in organicsystemsmonitors are appiopriate.

7.6.1Avoidance

Severalechniquesor avoiding eadlock re available.A more horoughdiscussionf the opiccanbe oundn [146].) orexample,f thesemaphoresprotectingcritical resources re mplementedby mailboxeswith time-outs, hen

deadlocking cannot occut But starvation of one or more tasks is possible.

Starvationoccurswhen a task doesnct receive sufficientresources o complete

processing n its allocated ime.

A secondmethod or preventing deadlock s to allow preemption.That is,

tasksof higherpriority which need esources houldbe allowed o grab hen from

lower prionty tasks. Unfortunateiy, his can causeproblems ike stawation or

incomplete /O operarions.

The fact that each task acquires a resource and then does not relinquish it

until it can acquire another esources called a wait and hold condition. If we

eliminate his condition, then deadlockcan be avoided.

T EXAiIPLE 7.11

A taskneedso rcad rom file 1 andwdte to file 2. It might open ite l, reada record,closehle l.

Then t opens lle 2, writes he ecordandcldseshle 2 Theprocesss repeatedor each ecorduntil

the file is transferred I

This technique,owever, an slowdown esponseimesgreatly.

Finally, a technique nown as hebanker'salgorithmcan sometimese used

to prevent eadlock ituations.he echniqueuggestedy Dijksra [36]uses he

analogy f a small-town ank.The banker's lgorithmworkson like resources,

for example, ools of memoryor printers.The algodthmensureshatthe number

of resources ttachedo all processesannever exceedhenumberof resources

for thesystem.n addition,we cannevermakea"dangeroui llocation"-that s,allocate esourcesn sucha way that we do not haveenough eft to satisfythe

requirements f anyprocess.

I EXAMPLE..I2CoNider a systemwith threeptocesses, , B, alrd C, and a pool of 10 resources f a certain ]?e

(e.g.,memoryblocks). t is knownthat processA will never needmore than 6 blocksat any one

time. For proce-sses and C the totalsare 5 aDd7, respectively. table suchas he one below is

constnrctedokeep rack of the rcsouce needsand availability.

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 3/22

r86 Chap. 7 I Intertask Communica on and S\

Usedax Requirement

c

6

5

1

65

7

6

5 .,1

0

0

23I

t

5

:

taotal Available

When resourcesare requested, he opemting system updates he table, ensuring dll Ideadlockstate s not reached.An example of a "saie state" s

Process Max Requirement Used

Toral Available

Here, the requirementsof processA or B can be satisfied,so the stare s safe An"unsafestate" s

Max Requirement Used

4

l2

Total Available

ln this case, the total requtrementsof no task can be met with the total available

deadlockcould ensue.

The banker's algorithm is often too slow for real-time systems-Habermann 56] has implemented the algorithm for mixed resourcesalways practical. Finally, resourceneeds for each task may not b€prrcrt.

7.6.2 Detectand Recover

Assfming that a deadlock situation can be detected(for example,bgwatchdog timer), what can be done? One technique, known as fualgorithm, advises hat theproblembe gnored. f thedeadlocksituadmto occur infrequently, for example, once per year, and the system is Ddone, this approach may be acceptable.For example, f in a videoproblem is known to occur infrequently, the effort needed o detect and

problemmay not be ustified giventhe cost and functionof the sysren

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 4/22

Sec 7.7 I Exercises

to the child who just losrhis quarter). f the system s a mannedolle or in control

of say,an assembly ine, then the ostrich algorithmis unacceptable

Another method or handling he deadlock s to reset he systemcomPletelY.

Again, this may be unacceptableor certaincritical systerhs.

Finally, f a deadlocksdetected, ome orm of rollback oapre-deadlock tate

canbe perfomred,although his may lead o a recurrentdeadlock,and operations

suchaswriting to certain iles or devicescannotbe rolled backeasily.

7,7 EXERCISES

1 What effect would sizeN of a ring buffer have on its performance?How would you

determine he opdmal size?

2. For a machine you are familiar with, discuss whether the counting semaPhore

implementationgiven in this chapterhas any cntical region problems That is' can the

semaphoretself be tnte[upted in a harmful way'?

3. Why is it not wise to disable intetrupts before the while statement n the binary

semaphore, ?

4. Rewr i le he rinCbulTer ead-and-wr i leroceduresn

(a) C or C++

(b) Ada or Ada 95(c) Modula-2

5. Modify the wnte ptocedure or the ring buffer to handle he overflow condition'

6, Write a set of pseudocode outines to access read from and write to) a 20-item ring

buffer.The routinesshould use semaphoreso allow more than one user o access he

buffer,

7. Considera binary semaphore, ounting semaphore'queues,and mailboxes Any three

can be implementedwith the fourth We have shownhovr' inary semaphoresan be used

to implement counting semaphoresand vice versa, how mailboxes can be used to

implementbinary semaphores,nd how mailboxescan beused o implementqueuesForeachpair, show how one can be used to implement the otherl

(a) Binary semaphoresor impl€mentingmailboxes.

(b) Binary semaphoresor implementingqueues.

(c) Queues or implemeniingbinary semaphores.

(d) Queues or implementingmailboxes.

(e) Queues or implementin8countingsemaphores.

(O Counting semaphoresor implementingmailboxes.

(g) Counting semaphoresor implementingqueues

(h) Mailboxesfor implemenringcountingsemaphores.

8. Discuss heproblems hat can arise f the est andset n theP(S) operationare not atomic

What could happen f the simple assignment tatement n the v(S) operationwere nol

atomic?

9. Rewrite the binary semaphoremplementationof the counling semaphoren

(a) C or C++

(b) Ada or Ada 95(c) Modula-2

10. Using the ANSI-C raise and signal facilities' implement the pend(datas) and

post(data,S) operations for arbitrarymailbox S

lE7

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 5/22

188 Chap. ? I Intertask Communicationand

Rewrite the test_andset procedure n:

(a) C o r C+ +

(b) Ada or Ada 95

(c) Modula-2

The TANDS instructioncan be used n a multiprocessing ystem o preventaccess o a global semaphore y two processors. he instruction s made ndivisiti:

the CPU refusing o issuea DMA acknowledge DMACK) signal n response o a

request (DMARQ) signal dunng execution of the instruction.The other

sharing he bus are ocked out of accessingmemory.What are he real-time

for a processor rying to accessmemory when anolherprocessors executinga

that is looping for a semaphore sing the following code?

rl .

12.

P r o c e s s 2 :

r | a N I n q < a n : 6 h ^ r a

J N E q E ! I O C K

If this busy wait must be used, s therea bettetway to test the semaphoren pror-:rs

so that the bus is not tied up?

13. Rewrite the exceptionhandler n Example7.8 in

(a) Ada or Ada 95

(b) Modula-2

(c) C++

Write a function to compute.x actorial, I, where is somenonnegativenteger

that rI = j . (. r- J) . l and 0/ = .1.)Write an associated xceptionhandler hat

errols related to trying to take .r/ for -t < 0 and to handle overflow conditions-

factorial funcrion should invoke the exception handler if either error type occurs. Dc

ln

(a) c(b) Ada or Ada 95

(c) C+r

15 . Investigate he use of signalhandlers n the imPlementation f a Unix process

communicationmechanism called a pipcline. Pipelines allow lhe outpuls of

processes o be used as inputs to other processes. our investigationcan be doE

examining he sourcecode to any Unix operatingsystem, f available,or by

one of the many texts on the Unix operating system

14.

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 6/22

Real-TimeemoryManagement

KEY POINTS OF THE CHAPTER

1 . Dynamic memory management f any kind in real-time, hough usually

necessary,s detrimental o real-time performanceand schedualabilityanalysis.

Stacksare ypically used n foreground,/backgroundystemsand he ask-

control block used n commercial,genericexecutives.

Techniques or managingstacksand task-controlblocksare given in the

chaDter.

An oftenneglected iscussion,ynamicmemoryallocation,s importantn

terms of both the use of on-demandmemoryby applicationsasks ald therequirementsf the operating ystem. pplicationsasksusememoryexplicitly,for example, hrough equests or heap memory,and implicitly through hemaintenancef the un{ime memory eededo support ophisticatedigh-orderlanguages.heoperating ystemor kemel)needso performextensivememorymanagementn order o keep he asks solated.

Dangerous llocatlon f memory s anyallocationhatcanprecludeystemdeterminism. angerous llocation andestroy ventdeterminism,or example,

by overflowing he stack,or it candestroy emporal eterminism y enteringdeadlock ituationChapter 1). t is important o avoiddangerousllocation fmemorywhile at the same ime reducing he overheadncurredby memoryallocation. hisoverheads a standard omponentf thecontext witch ime andmustbe minimized.Staticmemoryallocation chemes-that s, thepaftitioningof memoryat system enerationime-are discussedn Chapter .

3 .

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 7/22

Chap. I Real-TimeemoryManagemeor

Although some of the memory management chemes iscussed n Section8.2 may seemarchaic(for example,MFT datesback to the early 1960s), heseschemes ave recentlybecome elevantagain.For example,cachememoriesaregenerallyvery small relative to main memory oust as main mernory was smallrelative to secondarystoragedevices n early computers). n the caseof cache,someof the replacement ules suchas LRU and working setsare used o managethe contentsof the cache.

8.1 PROCESS TACKMANAGEMENT

In a multitaskingsystem,context or each askneeds o be savedand restoredn

order o switchprocesses. his can be doneby using oneor more run-timestacksor the task-controlblock model. Run-time stacks work best for interrupt-onlysystems and foreground/background ystems,whereas the task-controlblockmodel works best with full-featured real-time operating systems. Substantialformalization of this statement an be found in [10].

8.1.1Task-Control lock Model

If the task-controlblock model is used, hena list of task-controlblocks is kept.This list can be either fixed or dynamic.

In the fixed case, r task-controlblocks are allocatedat systemgenemtion

time, all in the dormantstate.As tasksare created, he task-confiolblock ententhe readystate.Prioritizationor time slicingwill then movethe task o the executestate. f a task is to be deleted, ts task-controlblock is simply placed in thedormant state. n the caseof a fixed numberof task-conholblocks, no real-timememory management s necessary.

In the dynamic case, ask-controlblocks are added o a linked list or sorneother dynamic data structure as tasks are created.Again, the tasks are in thesuspended tateupon creationand enter he ready statevia an operatingsystemcall or event. The tasks enter the executestateowing to priority or time-slicing.When a task s deleted, ts task-controlblock is removed rom the inked list, andits heapmemory allocation s retumed to the unoccupiedoJ available status.

In this scheme, eal-time memory management onsistsof managing theheap needed o supply the task-control blocks; however, gther data structures such

as a list or queuecan be used. A heap s a specialkind of datastructurebasedona binary tree. For a disiussion of these structures,consult any text on datastructures, or example, 83].)

8.1,2Managinghe Stack

If a run-time stack is to be used, certain considerations are required. In order tohandle he run-time savingand restoringof context, wo simple routines-"save"

and "restore"-are necessary.The save routine is called bv an intemrpt haldler

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 8/22

S:c. 8.1 I ProcessStack Manasement

to save he current contextof the machine nto a stackarea.This call should be

made immediately after intemrpts have been disabled to prevent disaster.The

restore routine should be called just before interrupts are enabled andtf,efore

retuming from the interrupthandler.

T EXAMPLE.'IConsidea he implementationof the save outine.Assume hat global variable"stack' is to point to

the top of the stack and that eight general egisters R0-R7) areto be savedon a stack The memory

location"PC" cofiesponds o the lnterrupt etum vector ocation,and so it contains he PC value at

the time of intefiuption. We need o save his on the stack o allow stackingof interupts The code

for a 2-address rchltecture esembleshe followinsl

191

The save perations illusnatedn Figure8-1.Next considerhe estoreoutine,written n 2-addressode.

context is a pseudo-argument

disable nte.rupts

savecontentsof register0 onto stack

load index registerwith addressof stack

save egrster

save register2

save egister 3

save egrster4

save egister5

save eglster o

save egister7

save retum location

save new stack point&

enable nterrupts

contexts a pseudo-argument

disable nterrupts

rcstore clum location

save (con tex t ) :

STORER0, s tack , I

LOAD R0, s tack

ADD RO,1

STORER1, RO.

ADD RO,1

STORER2, RO,

ADD R O,1

S T O R E 3 ,R O , I

A D D R O ,

STORER4, RO,

ADD RO,1

STORER5, RO,

ADD RO,1

STORER6, RO,

ADD RO,1

s f roRE R7, R0 , 1

ADD RO,1

STOREPC,RO.1

ADD RO,1

STORER0, sLack

res to re ( con tex t ) :

LOAD RO,sLacK

SUB RO,1

LOAD PC,RO I

SUB RO, 1

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 9/22

192

Stack +

Chap.8 I Real-TimeMemoryManagement

L O A D R 7 , R O , I

suB R0, 1

LOAD R6, RO,

SUB RO,1

LOAD R5, RO I

S UB RO,1

LOAD R4, RO,

S U B R O , 1

LOAD R3 R O,

SUB R O,1

LOAD R2 RO,1

SUB RO.1

LOAD R1, RO I

STORER0, s tack

S UB RO,1

LOAD RO,RO I

restore register 7

restore cgister6

restore egister 5

restore egister4

restore egister3

restore egister2

restore egister I

reset stackpointer

restore egister0

enable nterrupts

The estore peratiol s illustratedn Figure8.2.

Certainmachinearchitectures llow block save andblock restore nstructionsEstore and load n general registers n t? consecutivememory locations. ThesE

instructionsgreatlysimplify the implementationof the saveand restore outin€s.

Be aware that such macroinstructionsmay be designed o be interruptable ro

reducecontextswitch time), so that if interruptshave not alreadybeendisabled-

they should be.

Stack

R7

R1

RO

Figure8,1 Thesaveop€ration. Figur€8,2 The estore peration.

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 10/22

8.1 .3

8.1 .5

I Process tackManasement

Run-Time ing Buffer

A run-time stackcannot be used n a round-robinsystembecause f the firsfin/firscout natureof the scheduling. n this casea ring buffer or circular queuecan

be used o save context.The context s saved o the tail of the list and restoredfrom the head.The saveand eslore oulines canbe easilymodified to accompJishthis operation.

MaximumStackSize

The maximum amountof space eeded or the run{ime stackneeds o be known apriori.ln general, tack izecanbe determinedfrecursion s not usedandheapdata

structuresare avoided. f maximum stack memory requirements re not known.thena catastrophicmemory allocationcan occur,and he systemwill fail to satisfyevent determinism. deally, provisionfor at leastone more task than anticipatedshould be allocated to the stack to allow for spurious intem:pm and timeoverloading.We will discuss his matter urther n Chapter11;alsosee 95],

MultipleStackArrangements

Often a single run-time stack s inadequate o manage everalprocessesn, say,aforeground/background ystem. Of course, n a multiprocessingsystem, eachprocesswill manage ts own stack, but this is not the kind of multiple stackschemewe are talking about.

A multiple stackscheme sesa single un-time stackandseveralapplication

stacks. Using multiple stacks in embedded real-time systems has severaladvantages.

1. It permits tasks to interrupt themselves, hus allowing for handling

transientoverload conditionsor for detectingspurious nterrupts,

2. The systemmay be written in a language hat supports e-entrancyandrecursion,such as C or Pascal. ndividual run-timestackscan be kept foreach processwhich contains the appropriate activation records with

dynamic links needed to support recursion. Or two stacks for eachprocesscan be kept, one for the activation ecordsand the other for the

display(a stackof pointersused o keep rack of variableand procedurescope). n either case,a pointer to thesestacksneeds o be saved n the

context or task-conftolblock associatedwith that task.

3. Only non-re-entr.antanguages uch as older versions of FORTRAN or

assemblyanguagecan be supportedwith a single-stackmodel.

We can rewrite the saveard restore outines o use he conFxt arsumentas

a Dointer o the stack.That is.

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 11/22

194 Chap.8 I Real-Time emoryManagement

save (ccn ex t )

DPI

STORER0, conLex t

LOAD R0 cont ext, I

ADD RO,1

STORER1, RO,

ADD RO,1

STORER2,RO,

AD D RO,1

STORE R3 RO,

ADD RO ].

STORER4, RO,

ADD RO,1

sToRE R5. R0 , I

ADD R O,1

STORER6, RO,

ADD RO,1

STORER 7,R O,

ADD R O,1

STOREPC,RO,1

ADD con texL , 9

EPI

This is the new restoreprocedure.

disable nterrupts

savecontentsof register0 onto stack

load ndexregister

save eglsrcrr

save register2

save egister3

save egister4

save egister5

save egister6

save cgister7

save elum locanon

incrementstackpointer

enable nterrupts

disablenterrupts

restore etum ocation

restorc egister7

restoreegister 6

restore egister5

restore cgister4

resaoreegister3

restore egister2

DPI

LOAD RO, context, 1

SU B RO,1

LOAD PC ,RO 1

SUB RO,1

LOAD R7 RO.

suB R0, 1

LOAD R5,RO,1

suB R'0,1

LOAD R5. RO,1

SU B RO,1

LOAD R 4,R O,1

SUB RO,1

LOAD R3. RO, 1

suB R0, 1

LOAD R2 RO ,1

- suB R0, 1

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 12/22

8.1 I ProcessStack Manaeement 195

restoreegister

restoreegister

decrementtack ointer

enable nterupts

interupt-handler routines to save to a main stack, written in

LOAD

SUB

LOAD

SU B

EPI

R 1 ,R 0 ,L

R 0 , 1

R O , O ,

con texL , 9

The individualPascal,ollow.

n r - - 6 1 1 , ' 1 6 i n 1 - .

beg n

save (mains tack ) ;

. : c a i n F a - r r r n F ^ f

1 : i n L l ;

2t i I lL2;

3 : i n L 3 ;

end

resCore (ma insLack )

end

h r ^ - 6 / l . , 7 a i - t s 1

begin

save (s tack l ) ;

t a s k l ;

r e s t o r e ( s t a c k l )

en d

h r ^ - 6 4 , r - 6 i n F , .

begin

d r r r a / c i . ^ l / r \ .

t a s k 2 ;

r a c l ^ , 6 / c r - . ^ L , )

en d

h r ^ - a A , r , 6 i n i - 1 '

begin

. : v a l a l : ^ L 1 \ .

t ask3 ;

restore (s tack3

end

/ * i r t a r r r r - r h : n r l l a r 1 * /

/ * save con tex t on s tack * /

/ " execu te task 1 * /

/ * r es to re con tex t f r on s tack

/r interrupt handler 2 */

/* save context on stack r /

/ * execu te task 2 * /

/ t r es to re con tex t f r om s tack * /

/ * i h i 6 r , , , ^ r h : h / l l 6 7 I + /

/* save contexf o-nstack */

/ * execu te task 3 * /

/ * r es to re con tex t f r om s tack r / '

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 13/22

196

Figure 8.3 Main and un-time tacksor Example .2.

8.1.6Task-Control lockModel

Chap. 8 I Real-Time Memory Management

I EXAMPLE.2Suppose hreeprocesses re running in an interrupt-only systemwherea single nterrupt basedon

threeprioritized ntenupts is gener4ted. et taskl, task2,and task3 be as follows:

p rocedure task l ;beg fn

appL i c l ;

aPP l c2

end

procedure Lask2 ;

oe g1n

app l i c2 ;appf rc3

en d

procedure task3 ;

beg ln

a p p f i c 3 ;

app l i c4

end

Suppose askl is running when it is interupted by task2 during applic2.Later, task2 s interrupted

by task3 dudng applic3. The main and run time stackswill then ook like Figure 8.3. I

task2sta6li

task3stack

Mainslack

When mplementing he ask-control lock (TCB) model of rcal-time multitaskrn&

the chief memory management ssue s the maintenance of the linked lists for tbeready ald suspendedasks.As shown n Figure8.4, when the currently executingtaskcompletes,s preempted, r is suspended hile waiting for a resource,he ne

highestpriority task in th€ ready list is rernoved andis made the executing one. E

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 14/22

Sec.8.2 I DynamicAllocation

Ready Ljst

1 Exsculinq ask El€as€s ilic€lrcsourcane-€dsd ysuspendsdhigh-prioity ask

2. Ex€culingssk nsened n

3. Suspgnd€daskbegins

4 Dormad ist nolshownSusPendedist

Figure 8.4 Memory managementn the task-controlblock model

the executing ask needs o be added o the suspendedist, that is done. (If the

executing askhascompleted, hen ts TCB is no longer needed.)

Hence,by properlymanaging he inked lists, updating he statusword in theTCBs, and adhering o the appropriate chedulingpolicy by checking hepriority

word n theTCBs, round-robin,preemptive riority,or bothkinds ofschedulingcan

be induced.Othermemory management an nclude the maintenance f reserved

blocksof memory hat areallocated o individual taskapplications s equested.

8.2 DYNAMIC LLOCATION

Dynamic allocation used o satisfy individual task requirements or memory is

accomplishedby using a data structure such as a list or heap. For example,

memory allocationcalls to the procedure malloc" in C are mplemented hough

library calls to the operatingsystem. n Pascal, he NEW function canbe'used o

generatea new record type in a dynamic memory scheme.Ada and Modula-2

provide similar constructs.How these anguagesmplement the ailocation and

deallocationof memory is compiler dependent.And, as we discussedbefore.

languagessuch as FORTRAN and BASIC do not have dynamic allocationconstructs.A good book on data structures e.g., 83l) can be consulted l order

to implementthesedynamicmemory allocation schemes

In this section,however,we ate nterestedn dynamicmemoryallocation or

processcode n main memory,and certdinaspectsof this need to be considered

as they relate to real-time systems. n particular, we are interested n scbemes

where two or more programs cal co-reside n main memory. Severalschemes

. allow this capability,andwe will review someofthem briefly with respect o their

197

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 15/22

Chap. I Real-TimeemoryManagement

real-dme implications.Interested eaderscan consult a good text on operating

systemssuch as [129] for a more detailed coverage. n general, he types of

dynamic allocation that we

embedded eal-timesysbms.

8.2.1Swapping

The simplestscheme hat allows the operatingsystem o allocatememory to two

processes simultaneously"\s swapping' In this case, he operating system s

always memory resident)and oneprocess an co-reside n the memory spacenot

requiredby the operatingsystem,called the user space When a secondprocess

needso run, he rrstprocesss suspendednd henswapped, longwith its contexl

to a secondary toragedevice,usuallya disk. The secondprocess,along with itscontext, s then oaded nto theuserspace nd nitiatedby the dispatcher.

This type of schemecan be used along with round-robin or preemptive

priority systems, ut we would like the execution ime of eachprocess o be long

relative to the swap time. The access ime to the secondary tore s the principal

contributor to the contextswitch overheadand real-time response elays

8.2.2 OverlaysA technique hat allows a single program to be larger than the allowable user

space s called overlaying.In this case he program s brokenup into dependent

code and data sectionscalled overlays,which can fit into available memoq'.

Specialprogramcodemust be included hat permits new overlays o be swaPped

into memory as needed over the existing overlays),and care must be exercised

in the designof such sYstems.

This techniquehas negative real-time implications because he overla;c

must be swapped rom secondarystoragedevices.Nevertheless, verlayingcabe used n conjunctionwith any of the techniquesmentionedater in this chapter

to extend the available addressspace.Many commercial tools are available thr

facilitate overlaid linking and loading in conjunction with commonly used

programming anguagesand machines.

Note that in both swappingand overlaying a portion of memory is never

swapped to disk or overlaid. This memory contains the swap or overlay

manager and in the caseof overlaying any code that is common to all overlayr

is called the root).

8.2.3MFT

are about to discuss are not recommended n

A more elegant chemehansimpleswappingallowsmore hanoneprocesso bc

rnemory-residentt any onetime by dividing he userspacento a numberd

txed-size partitions.This schernes calledMFT (multiprogrammingwith a fixed

numberof tasks)and is useful n systemswhere he numberof tasks o bc

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 16/22

I DynamicAllocation

executed s known and fixed, as in many embeddedappiications. Partitionswapping o disk can occur when a task s preempted. asks,however,mustresidein contiguouspartitions,and the dynamic allocationand deallocationof memorycauseproblems.

In some cases main memory can become checkered with unused butavailablepartitions,as n Figure 8.5. In this case he memory space s said to beexternally ragmented.This typeof liagmentationcauses roblemswhenmemoryrequests annotbe satisfiedbecause contiguousblock of the size requested oesnot exist, even though the actual memory is available.

I EXAMPLE .3In Figure 8.5,even hough40 megabytes f memory are available, hey are n noncottlguousblocks,so the request

cannot be honored.

Figure 8.5 Fragmented emory.

Anotherproblem, nternal ragmentation, occurs n fixed partitionschemeswhen, for example, a process requires 1 megabyte of memory when only2-megabytepartitionsare available.The amountof wasted memory or intemalfragmentation an be reducedby creating ixed partitionsof severalsizesand henallocating he smallestpartition greater han the requked amount

Both intemal and extemal fragmentationhamper efficient memory usageand ultimately degrade eal-timeperformance ecause f the overheadassociated

with their correction.MFT is not particularly desirablen the real-time operatingsystembecause

it usesmemory inefficiently as a result of the overheadassociatedwith fitting aprocess o availablememory and disk swapping.However, n some mplementa-tions, particularly in commercial real-time executives,memory can be dividedinto regions n which each region containsa collection of differenrsized, fxed-sizedpa$itions. For example,one region of memory might consistof 10 blocksof size 16Mb, while another egion might contain 5 blocks of 32Mb and so on.

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 17/22

Chap. 8 I Real-Time Memory Management

The operatingsystem hen tries to satisfya memory request eitherdiiectly from

the program via a systemcall or through the operatingsystem n the assignment

of thatprocess o memory),so that the smallestavailablepartitionsare used This

approach ends o reduce nternal fragmentatlon.

8.2.4MVT

ln MVT (or multiprogramming with a variable number of tasks),memory is

allocated in amounts that are not fixed, but rather are determined by the

requirementsof the process o be loaded nto memory.This technique s more

appropriatewhen the numberof reahime tasks s unknownor varies. n addition'

memory utilization is better or this technique han for MFT becauseittle or no

intemal ragmentation an occur,as he memory s allocated n the amountneededfor eachprocess.Extemal fragmentationcan still occur because f the dynamic

nature of memory allocationand deallocation,and becausememory must still be

allocated o a processcontiguously.

In MVT, however,extemalfragmentation an be mitigatedby a processof

compressingfragmented memory so that it is no longer fragmented.This

technique s calledcompaction seeFigure 8.6). Compaction s a CPU-intensive

processand is not encouragedn hard real-time systems. f compactionmust be

performed, t shouldbe done n the background,and t is imperative hat nterruptsbe disabledwhile memory is being shuffled.

The bottom line is that MVT is useful when the numberof real-timetasks

is unknown or can vary. Unfortunately, ts context-switchingoverhead s much

hieher han n simplerschemes uchasMFT, and hus t is not always appropriate

Belore

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 18/22

I Dynamic Allocation

for embedded eal-time systems. t is more likely to be found in a commercial

real-time operatingsystem.

DemandPaging

In demand pdge systems,program segments are permitted to be loaded in

noncontiguousmemory as hey are requestedn fixed-sizechunkscalledpagesorpage frames. This schemehelps to eliminate extemal fragmentation.Programcode hat s not held n main memory s "swapped" o secondary torage, sually

a disk. When a memory reference s made o a location within a pagenot loaded

in main memory, a page ault exception s raised.The interrupt handler or this

exceptionchecks or a free pageslot in memory. f none s found, a page rame

mustbe selected nd swapped o dis k (i f it has beenaltered)-a process alledpagestealing. aging,which s provided y mostcommercial perating ystems,

is advantageous ecauset allows nonconsecutiveeferences o pagesvia a pd.qe

table. ln addiiion, paging can be used in conjunction wirh bank switching

hardware o extend he virtual address pace. n either case,pointersare used o

accesshe desiredpage(seeFigure 8.7).Thesepointersmay representmemory-

mapped locations to map into the desired hard-wired memory bank; may be

implbmented hrough associativememory; or may be simple offsets nto memory,

in which case he actualaddressn main memory needs o be calculatedwith eachmemory reference.

Paging can lead to problems including very high paging activity called

thrashing, ntemal fragmentation,and the more seriousdeadlock seeChapter7).

But it is unlikely.that you would use so complex a schemeas paging n an

embedded real-time system where the overhead would be too great and the

associated ardwaresupport s not usually available.

Figure8.7 Pagedmemory singpointers.

Chap. 8 I Real-TirneMemory Management

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 19/22

202

To conclude, the overheadfor the LRU schemerests in recording the

8.2.5,1 ReplacementAlgorithms-Least Recently Used Rule Several

methodscan be used o decidewhich pageshouldbe swappedout of memory o

disk, suchas irsrinfirst-out (FIFO).This method s the easiesto implement,and

its overheads only the recordingof the oadingsequence f the pagesAlthough

otheralgorithmsexist, the bestnonpredictivealgorithm s the eastrecentlyused(LRU) rule.

The LRU method simply states hat the least recently used pagewill be

swappedout if a page iault occurs To illustrate the method' consider the

following.

T EXAMPLE.4A pagedmemory system s divided into sixteen256-megabyte agesof which any 4 can b€ loaded

at he same ime. Eachpage s tagged 1, 2, etc ) The operatingsystemkeeps rack of the usageof

eachpage.For examPle, he Page eierencestring

2 3 4 5

indicates hat pages2, 3, 4, and 5 havebeenused n that order' f a requests made or page7' theo

page2 will beswappedout in order o make room for page7, becauset was he east ecentlyused

The loadedpageswould then be 3,4,5' and 7 with referencestdng

2 3 4 5 ' 7

pleasenote that referenceso pagesalready oaded n memory causeno page ault. For instance,f

a reference s now made to page 3, no pages need to be swappedbecausePage3 is loaded D

memory. If this reference s followed by one to page 6, page 4 would have to be swappedou

because t had the least recent reference.The loadedpages would then be 3, 5' 7' and 6 wih

reference string

2 3 4 5 ' 7 3 6

Notethatinapagingmemoryscheme,thewolstpossiblescenarioinvolvespagestealirrgforead

request of memory. This occurs, fol examPle, in a four-page system when five pagesare requested

cyclically as in the page eferencestring

2 4 6 8 9 2 4 6 8 9 " '

You should note that the performance of LRU is the same n this caseasFIFO (in

termsof numberof Page aults).

ln FIFOpage eplacementchemeswhetheror not usedn conjunctionwitl

working sets),we might liink thatby increasing\e numberofpagesnmernoryawindowsn the workingsettwecan educehenumberof page aults Often hisb

thecase,but occasionallyan anomalousonditionoccurswherebyncreasingb

numberof pagesactually ncreaseshe numberof page aults This is Beladyb

Anomaly,whichas t tumsout,does otoccur n LRU replacementchemes'

sequenceo all pages,which canbequite substantial.Therefore' thebenefrtsof usi

LRU need to be weighed against he effort in implernenting it vis-d'vls FIFO'

i : c . X 2 I D lnamicA l l oca t i on

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 20/22

8.2.5.2Memory Locking In addition o thrashing,hechiefdisadvantage

of pageswapping n real-time systemss the ack of predictableexecution imes.

In a real-time system, t is otien dqsirable o lock all or certainpartsof a process

into memory in order to reduce he overhead nvolved in paging and o make the

execution imes more predictable.Cenain commercialreal-tjme kemels provide

this feature, called memorl laclhg. Thesekemels typically allow code or data

segments. r both, for a particularprocess, s well as he run{ime stacksegment,

to be locked into main memory.Any processwith one oi mole locked pages s

then prevented rom being swapped out to disk. Memory locking decreases

executiontimes for the locked modules and. more importantly, can be used to

guarantee xecution imes.At the same ime, it makes ewer pagesavailable or

the applicalon, encouragingorttention.

8.2.5.3Other PointsAbout Paging ln summary,

1. Paging s most efficient when supportedby the appropriatehardware.

2. Paging allows multitaskingand extensionof the address pace.

3. When a page is referenced hat is not in main memory, a page fault

occurs, which usually causesan interrupt.

The hardware egisters hat areused o do page rame addressranslationare part of a task's context and add additional overheadwhen doing a

contextswitch.

If hardware page mapping is not used, then additional overhead s

incurred n the ohvsicaladdress alculations.

6. The least recently used rule is the best nonpredictivepage-swapping

algorithm.

7. In time-critical real+ime systems, we cannot afford the overhead

associated ith disk swapping n simpleswapping,overlays,MFT, MVT,

or paging schemes.

8.2.6WorkingSets

Working setsare based,on he model of localtty-of-reference. he idea is if you

examinea list of recently executedprogram nstructionson a logic analyzer, ou

will note that most of the instructionsare localized to within a small number of

instructions in most cases. (For example, in the absence of lnterrupts and

blanching, the program s executedsequentially.Or the body of a ioop may be

executeda large number of times.)However,when interrupts,procedure alls, or

branchingoccurs, he locality-of-references altered.The idea n workhg sets s

that a set of local code windows is maintained in the cache and that upon

accessing memory ocationnot contained n one of the working sets,one of the

windows n the working set s replaced usinga replacement ule such as FIFO or

,|

5 .

Chap. 8 I Real-TimeMemory Management

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 21/22

LRU). The performance f the scheme s basedentirely on the sizeof the working

set window, the number of windows in the working set, and the locality-of-referenceof the code beins executed.

8.2.7Real-Time arbageCollectionIn a memory-managementontext,garbage s memory hat hasbeenallocatedbutis no longer being usedby a task(that s, the task has abandonedt). Garbage anaccumulatewhen tasks erminate abnormally without releasingmemory resour-cesn441. It can alsooccur n object-oriented ystemsand as a normal byproductof nonproceduralanguages4], [162].

In C, for example, f memory s allocatedusing he mallocprocedure nd hepointer for that memory block is lost, then that block cannotbe usedor properly

freed.The samesituationcan occur n Pascalwhen recordscreatedwith the newstatement re not properly disposedof.

Garbagecollection algorithms generally have unpredictableperformance(althoughaverage erformancemay be known). Garbage an be reclaimedusingthe following procedure.Tag all memory from the heap which is pointed o by avariable (including those variables in procedure activation frames-a non-deterministicdata structure).Then reclaim all nontaggedmemory for the heap.The oss of determinism esults rom the unknown amountof garbage,he taggingtime of the nondeterministic ata structures, nd the fact that many incrementalgarb;gecollectors equire hat every memoryallocationor deallocat ion rom theheap be willing to service a page-fault rap handler

Anothertechnique s to build a heap or table of memory blocks along wirtan associated rocessD for the owner of the memoryblock. This data structurEis thenperiodically checked o determinewhethermemory has beenallocated oa process hat no longer exists. f this is the case, he memory can be releasedBecauseof the overhead nvolved, this method should not be implemented nhigh-frequencycycles, and ideally garbagecollection should be performedas rbackground ctivity or notperformedat all [4]. Nevertheless,esearchn real-ticgarbage ollection s still open.

8.2.8Contiguous ileSystems

Disk I/O is a problem n many real-timesystems hat can be exacerbated y

fragmentation. File fragmentation is analogous o memory fragmentation andthe same associated roblems,only worse. In addition to the logical

incuned in finding thci next allocation unit in the file, the physical overheadofdisk mechanisms a factor.For example, hysical verheadnvolvednthe disk's read/writehead o the desiredsectorcan be sisnificant

To reduce or eliminate this problem aliogether, many commercial real-dsystems, uchas eal-timeUNIX, force all allocatedsectorso follow oneon the disk.-This echnique s called contiguousile allocation.

Sec.8.4 t Exercises 205

8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition

http://slidepdf.com/reader/full/real-time-system-05-philip-a-lapalante-2nd-edition 22/22

8,3 STATIC CHEMES

Static memory issues revolve around the partltioning of memory into the

appropriateamountof RAM, ROM, memory-mapped/O space,and so on. This

problemof resource llocations discussedn Chapter .

8.4 EXERCISES

1. Rewrite the sale and restore outinesassumlng hat eight general egisters R0 R7) and

the paogram ounter are to be savedon a stack. Do this fbr

(a) O-addressmachrne

(b) l-addressmachine

(c) 3-addressmachine2, Rewrite he saveand restore outines n 2-address ode,assuming lock move (BMOVE)

and restore(BRESTORE) instructionsare available Make the necessary ssumptions

about he tormal o[ the.e nstruction:..

3. Rewaife he saveandrestore outinesso that they saveand restote o the headand tail of

a ring buffer, respectively.

4. Rewrite the save and testore routines in Pascal so that they employ push and pop

procequres.

Write a pseudocode lgorithm that allocatespagesof memory on request.Assume hat

100 pages of size I megabyte,2 megabytes, and 4 megabytes are available Thealgorithm should ake size of the page equested s an argument,and retum a pointer to

the desiredpage.The smallestavailablepage should be used,but if the smallestsrze s

unavailable. he next smallestshould be used.

Write a pseudocode lgorithmcompacting64 megabytes f memory that is dividedinto

l-megabytepages Use a pointer scheme.

For a four-pagemerilory systemwith memory referencestring, for example,

6.

7.

2 4 6 8 9 2 4 6 8 9 - . .

show rhat the number or page aults for FIFO replacements lhe sameas for the LRUreplacement cheme.

8. A pagedmemory system s divided into sixteen256-megabyte agesof which any four

can be loaded at the same ime. Each page s tagged(1,2, etc.). Write a pseudocode

algorithm to implement the least recently used rule.

9, Write a heapmanagero handlearbitrary-sized atablocks n a ink list (analogouso the C

malloco routine).Rememberhat the run-time stackcan collide with the heap.Do this n

fa) C(b) Ada

fc) Pascal(d) Modula-2(e) C++

10. Modify the heap manager n the previous exercise so that a table consisting of the

memory block number and process D is stored.Wrire a garbagecollectionroutine lo

accomFany he heapmanagerwhich consults a second able consistingof a list of all

existing process Ds and frees all memory blocks belonging o extinc! processes.