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
22
Embed
Real Time System 05 Philip A Lapalante 2nd Edition
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
8/9/2019 Real Time System 05 Philip A Lapalante 2nd Edition
(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
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
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
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
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
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
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
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
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
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.