Sie sind auf Seite 1von 344

ARM Cortex Embedded ystem M!

ltitas"ing #rogramming $sing FreeRT%


Andre& Elias' Feb 2013

First Technology Transfer - Feb 2013

FreeRT% %(er(ie&

First Technology Transfer - Feb 2013

FreeRT% - The )ho


FreeRT% &as de(elo*ed by a +(ery cle(er, soft&are engineer Richard -arry As it says on the .!l! &ebsite &ho *!blish his boo"s

Richard -arry grad!ated &ith 1st Class /onors in Com*!ting for Real Time ystems0 /e1s been directly in(ol(ed in the start !* of se(eral com*anies2 *rimarily &or"ing in the ind!strial a!tomation and aeros*ace and sim!lation mar"ets0 -arry is c!rrently a director of Real Time Engineers .td0 3o&ners of FreeRT% 4 and /ead of 5nno(ation at )ittenstein /igh 5ntegrity ystems0

5nterestingly the only boo"s on de(elo*ing &ith FreeRT% are those &ritten by Richard 5n this res*ect FreeRT% has something in common &ith Micri!ms1 !C% o*erating system

The boo"s on de(elo*ing &ith !C% 55 6 !C% 555 are &ritten by the de(elo*er of !C% - 7ean .abrosse

-oth FreeRT% and !C% ha(e A#5 3A**lication #rogramming 5nterface4s that are s*ecific to them

First Technology Transfer - Feb 2013

FreeRT% - ome claims

Aims to9

:#ro(ide a free *rod!ct that s!r*asses the ;!ality and ser(ice demanded by !sers of commercial alternati(es:

FreeRT% TM is a mar"et leading RT% from Real Time Engineers .td0 that s!**orts 33 architect!res and recei(ed 103000 do&nloads d!ring 20120 5t is *rofessionally de(elo*ed2 strictly ;!ality controlled2 rob!st2 s!**orted2 and free to embed in commercial *rod!cts &itho!t any re;!irement to ex*ose yo!r *ro*rietary so!rce code FreeRT% has become the de facto standard RT% for microcontrollers by remo(ing common ob<ections to !sing free soft&are2 and in so doing2 *ro(iding a tr!ly com*elling free soft&are model =!estion9 )hich other o*erating systems !se the FreeRT% A#5 > =!estion9 Are there any embedded o*erating systems that !se the #osix A#5 3 or a s!bset of the #osix A#5 4 > =!estion9 /o& is FreeRT% tested >

First Technology Transfer - Feb 2013

FreeRT% - More Technical Claims

FreeRT% ne(er *erforms a non-deterministic o*eration2 s!ch as &al"ing a lin"ed list2 from inside a critical section or interr!*t

=!estion9 )hat does this mean >

FreeRT% !ses an efficient soft&are timer im*lementation that does not !se any C#$ time !nless a timer act!ally needs ser(icing

oft&are timers do not contain (ariables that need to be co!nted do&n to 'ero =!estion9 Timers are2 essentially2 co!nters that generate a time e(en &hen the timer o(erflo&s6reaches 0 @de*ending on &hether it co!nts !* or do&nA =!estion9 )hat does this mean >

.ists of -loc"ed 3*ended4 tas"s do not re;!ire time cons!ming *eriodic ser(icing0

The FreeRT% ;!e!e !sage model manages to combine sim*licity &ith flexibility 3in a tiny code si'e4 - attrib!tes that are normally m!t!ally excl!si(e

=!estion9 /o& is this *ossible >

FreeRT% ;!e!es are base *rimiti(es on-to* of &hich other comm!nication and synchronisation *rimiti(es are b!ild

The code re-!se o**ort!nities that res!lt red!ce o(erall code si'e

This2 in t!rn2 assists testing and hel*s ens!re rob!stness =!estion9 /o& &o!ld yo! test this claim >
?

First Technology Transfer - Feb 2013

FreeRT% - Technology /ighlights

FreeRT% contains some (ery interesting feat!res 9

First Technology Transfer - Feb 2013

)i"i*edia - FreeRT% Descri*tion

FreeRT% *ro(ides methods for m!lti*le threads or tas"s2 m!texes2 sema*hores and soft&are timers0

A tic"-less mode is *ro(ided for lo& *o&er a**lications0 Thread *riorities are s!**orted0 5n addition there are fo!r schemes of memory allocation *ro(ided

Allocate only Allocate and free - !sing sim*le b!t fast2 algorithm A more com*lex fast allocate and free algorithm &ith memory coalescenceE A C library s!**orting allocate and free &ith some m!t!al excl!sion *rotection

FreeRT% has none of the feat!res ty*ical of o*erating systems s!ch as .in!x or Microsoft )indo&s i0e0 no s!**ort for

De(ice dri(ers Firt!al memory management2 !ser acco!nts2 and net&or"ing


C

First Technology Transfer - Feb 2013

)i"i*edia - FreeRT% Descri*tion ctd0

FreeRT% can be tho!ght of as a 1thread library1 rather than an 1o*erating system1

Command line interface and #% 5H li"e 5% abstraction add-ons are a(ailable

FreeRT% I5% *ro(ides a .in!x6#% 5H li"e open(), read(), write(), ioctl() ty*e interface to *eri*heral dri(er libraries

Fx)or"s from )ind Ri(er ystems has a *ro*rietary A#5 and also s!**orts a #osix A#5 3i0e0 the soft&are &as not designed &ith a #osix A#5 in mind4 The Ro&ebots RT% &as im*lemented &ith a #osix A#5 in mind

FreeRT% im*lements m!lti*le threads by

/a(ing the host *rogram call a thread tic" method at reg!lar short inter(als The thread tic" method s&itches tas"s de*ending on *riority and a ro!nd-robin sched!ling scheme

&itching is dri(en (ia a hard&are timer interr!*t The time inter(al is config!rable2 ty*ically from 1 to 10 msec
G

First Technology Transfer - Feb 2013

Mastering FreeRT% - #lan of Action


FreeRT% 2 altho!gh a tiny o*erating system2 is far from sim*le Mostly &ritten in generic C code2 b!t2 also some *latform s*ecific C and assembler This co!rse is foc!sed on ARM Cortex M36M8 *rocessors /o& m!ch of the M36M8 *rocessor architect!re do yo! need to !nderstand > )hich com*ilers and 5DEs can yo! !se for de(elo*ing a**lications > - e0g0 Keil 3no& o&ned by ARM4 5DE 5AR Code o!rcery 3.ite 6 commercial Ecli*se based4 - com*iler is LCC Code Red 3&idely fa(o!red by MH#4 )hich dri(ers and *rotocols stac"s &ill yo! be !sing > %*en so!rce > Commercial > De(elo*ed in ho!se > Com*lex systems and *rotocols $ -> Ethernet and TC#65# > CAM 3Controller Area Met&or"4 > Rich L$5s >
J

First Technology Transfer - Feb 2013

Mastering FreeRT% - #lan of Action - ctd0

tart off &ith something that &or"s e0g0 E(al!ation board a**roximating the ca*abilities yo!r *ro<ect &ill need and for &hich a *ort of FreeRT% exists and for &hich there are some demonstrator *rograms that &or"

5deally there is a *ort that !ses the 5DE yo! &ill be !sing in yo!r *ro<ect

E(al!ate and organise the a(ailable doc!mentation and for!m disc!ssions The *!blished FreeRT% boo"s are good2 b!t only ta"e yo! so far Areas of +obsc!rity,

Architect!re s*ecific details Com*lex libraries and *eri*herals are not *art of the *ac"age $ -> TC#65# > .CD gra*hics libraries > CAM b!s s!**ort > .ibraries s!**lied &ith yo!r 5DE and Microcontroller (endor >

/a(e these libraries been integrated &ith FreeRT% > 5f not 000 then &ho &ill integrate them >
10

First Technology Transfer - Feb 2013

FreeRT% - Analysis and Design 5ss!es

/o& to *rogress from initial re;!irements analysis and design to code s*ecification and im*lementation

$M. based re;!irements analysis and desing /atley-#irbhai or )ard-Mellor analysis and design /o& might yo! realise an ob<ect oriented design in C > /o& is code to be +s*lit !* into mod!les, /o& is code to be *artitioned into tas"s >

Testing and integration

M5 RA g!idelines $nit testing Code tracing and deb!gging

/o& &ill the embedded systems targets be !*graded >

#atches and -!g fixes > Enhancements > Additional mod!les and feat!res >
11

First Technology Transfer - Feb 2013

CM 5 -RT%

tandard

-ased on ARM Technical Doc!mentation as &ell as a /itex #resentation by Miall Cooling of Feabhas

First Technology Transfer - Feb 2013

12

CM 5

CM 5 re*resents an attem*t by ARM to standardise many as*ects of de(ice dri(er and associated library im*lementation across m!lti*le *rocessors and m!lti*le 5DEs The areas of standardi'ation incl!des9

/ard&are Abstraction .ayer 3/A.4 for Cortex-M *rocessor registers

tandardi'ed definitions for the ysTic"2 MF5C2 ystem Control -loc" registers2 M#$ registers2 and core access f!nctions0

tandardi'ed system exce*tion namesso that RT% and middle&are com*onents can !se system exce*tions &itho!t r!nning into com*atibility iss!es0 tandardi'ed methods to organi'e header files- to facilitate learning ho& to *rogram ne& Cortex-M microcontroller *rod!cts and im*ro(e soft&are *ortability0
13

First Technology Transfer - Feb 2013

CM 5 - ctd0

Common methods for system initiali'ation to be !sed by each MC$ (endor e0g0

tandardi'ed SystemInit() f!nction2 *ro(ided in each de(ice dri(er library2 for config!ring the cloc"0

tandardi'ed intrinsic f!nctions - normally !sed to *rod!ce instr!ctions that cannot be generated by 5EC65 % C

tandardi'ed intrinsic f!nctions2 im*ro(e soft&are re-!sability and *ortability

tandardi'ed &ays to determine the system cloc" fre;!ency thro!gh a soft&are (ariable ystemFre;!ency2 defined in the de(ice dri(er0 Allo&s RT% to set!* the ysTic" !nit based on the system cloc" fre;!ency

First Technology Transfer - Feb 2013

18

CM 5 - Fersions

(1 - Core (2 - D # (3 - RT% =!asi Conc!rrent #rogramming 9

First Technology Transfer - Feb 2013

1?

CM 5 - %rganisation

The CM 5 follo&s a layered architect!re a**roach

Core #eri*heral Access .ayer

#ro(ides name definitions2 address definitions2 and hel*er f!nctions to access core registers and core *eri*herals0 Deals &ith name definitions2 address definitions2 and dri(er code to access *eri*herals0 5m*lements additional hel*er f!nctions for *eri*herals as necessary

De(ice #eri*heral Access .ayer 3MC$ s*ecific4

Access F!nctions for #eri*herals 3MC$ s*ecific and o*tional4

First Technology Transfer - Feb 2013

1B

CM 5 - %rganisation - ctd0

%!tline of CM 5 architect!re

First Technology Transfer - Feb 2013

1C

CM 5 - RT% Architect!re

Kernel 3RTK4

ched!ling M!t!al excl!sion 5nter-tas" comm!nication N synchronisation Memory management File management ystem

Exec!ti(e 3RTE4

RT%

CMSIS - RTOS

FAT file system E0g0 TC#65#2 CAM E0g0 %*enL. E 2 Embedded =t

Met&or"ing

Lra*hical $ser 5nterface s!**ort

First Technology Transfer - Feb 2013

1G

CM 5 Com*onents

The CM 5 consists of the follo&ing com*onents9

CM 5 -C%RE9 *ro(ides an interface to Cortex-M02 Cortex-M32 Cortex-M82 C0002 and C300 *rocessors and *eri*heral registers CM 5 -D #9 D # library &ith o(er B0 f!nctions in fixed-*oint 3fractional ;C2 ;1?2 ;314 and single *recision floating-*oint 332-bit4 im*lementation CM 5 -RT% A#59 standardi'ed *rogramming interface for realtime o*erating systems for thread control2 reso!rce2 and time management CM 5 - FD9 ystem Fie& Descri*tion HM. files that contain the *rogrammer1s (ie& of a com*lete microcontroller system incl!ding *eri*herals

The standard is f!lly scalable across the Cortex-M *rocessor series of microcontrollers
1J

First Technology Transfer - Feb 2013

CM 5 (3 Architect!re

The CM 5 architect!re as it c!rrently stands 9

First Technology Transfer - Feb 2013

20

CM 5 - RT% - er(ices

The ser(ices 3feat!res4 *ro(ided (ia CM 5 -RT%

First Technology Transfer - Feb 2013

21

M!t!al Excl!sion

!**ort for m!t!al excl!sion comes from the im*lementation of m!texes and sema*hores

First Technology Transfer - Feb 2013

22

5nterthread Comm!nication

M!ltithreading interthread comm!nication and synchronisation is *ro(ided by the im*lementation of *rimiti(es s!ch as ignals Message ;!e!es Mailboxes 5 R comm!nication - Comm!nication65nteraction &ith 5nterr!*t er(ice Ro!tines

First Technology Transfer - Feb 2013

23

CM 5 - D # .ibrary

The CM 5 -D # library *ro(ides f!nctions s!**orting

Fector o*erations Matrix com*!ting Com*lex arithmetic Filter f!nctions Control f!nctions #5D controller Fo!rier transforms

Most algorithms are a(ailable in floating-*oint and (ario!s fixed-*oint formats and are o*timi'ed for the Cortex-M series *rocessors0 The Cortex-M8 *rocessor im*lementation !ses the ARM D # 5MD 3 ingle 5nstr!ction M!lti*le Data4 instr!ction set and floating-*oint hard&are

The CM 5 -D # library2 is &ritten entirely in C

The so!rce code is *ro(ided and the algorithms can be ada*ted for s*ecific a**lication re;!irements0

First Technology Transfer - Feb 2013

28

CM 5

FD

The CM 5 - FD ystem Fie& Descri*tion HM. s*ecification Describes the *rogrammer1s (ie& of the microcontroller system incl!ding the *eri*heral registers FD files can be !sed to create the CM 5 -C%RE header files &hich &ill incl!de *eri*heral register and interr!*t definitions0 CM 5 -DFD files can also be !sed to create *eri*heral a&areness dialogs for deb!ggers ARM *ro(ides do&nloadable FD files for many de(ices

http:/ /www.arm.com/prod cts/processors/corte!-m/corte!microcontroller-so"tware-inter"ace-standard.php

First Technology Transfer - Feb 2013

2?

CM 5 (3 Ada*tation to some RT%

The CM 5 A#52 in general2 has to be ada*ted to a *artic!lar RT% e0g0

First Technology Transfer - Feb 2013

2B

ome RT% es and 5DEs to Consider

RT% es

Free RT% Chibi% 6RT Keil RTH 5AR Keil Atollic Tr!e t!dio Ro&ley Associates - Cross )or"s Code o!rcery

5DEs

First Technology Transfer - Feb 2013

2C

CM 5 - De(ice Dri(er Architect!re

For each de(ice2 the MC$ (endor sho!ld *ro(ide a header file that *!lls-in additional header files re;!ired by the de(ice dri(er library and the Core #eri*heral Access .ayer 5ncl!de the file de(iceOfamily0h into the so!rce code0 5n order to be CM 5 -com*liant2 the (endor im*lementation m!st !se the *redefined exce*tion and interr!*t constants2 core f!nctions2 and middle&are f!nctions for accessing de(ice *eri*herals CM 5 -com*liant de(ice dri(ers &ill contain a start!*-code file2 &hich &ill incl!de the (ector table for (ario!s s!**orted com*ilers Ty*ical CM 5 -com*liant so!rce code files

de#ice$"amily.h - the header file defining the de(ice0 core$cm%.h - the header file defining the de(ice core0 core$cm%.c - im*lements core intrinsic f!nctions0 system$de#ice$"amily.h - im*lements de(ice s*ecific interr!*t and *eri*heral register definitions0 system$de#ice$"amily.c - im*oements system f!nctions and the initiali'ation code0 start p$de#ice$"amily.s - im*lements the start-!* code0

First Technology Transfer - Feb 2013

2G

CM 5 - De(ice Dri(er Architect!re

Ty*ical CM 5 com*liant code str!ct!re 9

First Technology Transfer - Feb 2013

2J

FreeRT% Fie& on CM 5 -RT%

http:/ /www.em&edded.com/electronics-&lo's/ind stry-comment/ 2 March B 2012 )hile the hard&are interface to a Cortex-M core is common across all Cortex-M microcontrollers2 the soft&are interface to an RT% is different in e(ery case0

#% 5H2 a common o*erating system interface in !se for many years2 is generally not regarded as an o*timal sol!tion for smaller de(ices2 s!ch as Cortex-M3 microcontrollers2 so &ill CM 5 be a better choice>

The cynic might say that ARM has s!ch a strong *osition in the microcontroller mar"et that2 if it *!t its &eight behind it2 CM 5 RT% &ill be s!ccessf!l &hether it technically merits the s!ccess or not0

$ltimately2 ho&e(er2 its s!ccess 3or other&ise4 &ill de*end on &hether c!stomers &ant it0 For c!stomers to &ant it2 they ha(e to see a benefit0 %ne clear benefit is that of ha(ing a single A#5 for a set of t&o or more RT% es0 5s this benefit alone eno!gh to ma"e CM 5 RT% a s!ccess>
30

First Technology Transfer - Feb 2013

FreeRT% Fie& on CM 5 -RT%

The end-!ser *ers*ecti(e 9 A common interface to m!lti*le RT% sol!tions &ill ma"e soft&are more *ortable and facilitate migrating a**lication code bet&een different RT% s!**liers0 From the engineering *oint of (ie&2 es*ecially for high-(ol!me *rod!cts2 the selected microcontroller &ill be the lo&est cost and smallest *ossible for the tas" in hand0

The soft&are r!nning on the microcontroller &ill be trimmed do&n0 )here s*ace2 time2 or res*onsi(eness are at a *remi!m2 any soft&are that is not adding (al!e to that a**lication &ill be remo(ed0 An RT% abstraction layer &ill2 by its (ery nat!re2 not add to the RT% f!nctionality2 b!t &ill ma"e the code bigger and slo& do&n the exec!tion s*eed0

The RT% abstraction layer &ill 2 therefore2 al&ays be a *rime candidate for remo(al0

A commercial RT% is a financial in(estment and it is !nli"ely that de(elo*ers &ill s&itch bet&een different RT% es that fre;!ently
31

First Technology Transfer - Feb 2013

FreeRT% Fie& on CM 5 -RT%

%*en-so!rce RT% (endor *ers*ecti(e

-eca!se of the financial in(estment re;!ired to select a ne& commercial RT% 2 CM 5 RT% com*liance &ill *ro(ide more mobility to2 and bet&een2 free o*en-so!rce RT% *rod!cts0

#otentially a big benefit to o*en-so!rce s!**liers0 The *otential in(estment made by commercial silicon2 RT% 2 and tool (endors in CM 5 -RT% -com*liant infrastr!ct!re &ill be e;!ally a**licable to o*en-so!rce-com*liant *rod!cts

/o&e(er2 by its (ery nat!re2 an RT% abstraction layer &ill ma"e the RT% larger and less res*onsi(e0

Co!nter *rod!cti(e as an RT% sho!ld be designed to be small or fast 3or both40 $sing the abstraction layer &ill not allo& the RT% to be !sed to its f!ll *otential2 or *ro(ide the maxim!m *otential benefit to the end !ser0 Maybe the abstraction layer &ill be remo(ed in end *rod!cts that ma"e it to mar"et as a final de(elo*ment *hase
32

First Technology Transfer - Feb 2013

FreeRT% Fie& on CM 5 -RT%

Commercial RT% (endor *ers*ecti(e

The *l!s *oints listed abo(e for an o*en-so!rce RT% (endor may (ery &ell be negati(e *oints for a commercial (endors0 Commercial RT% (endors in(est in their *rod!cts to differentiate them in a n!mber of different &ays0

#erformance2 si'e2 *rice2 s!**ort2 etc0 are all attrib!tes !sed to *osition an RT% 0 Anything that homogeni'es RT% offerings in the mar"et2 and in so doing red!ces any differentiation gained by technical and6or mar"eting in(estments2 ma"es the RT% mar"et a to!gher mar"et in &hich to &or"0

5t may also ma"e f!t!re in(estment harder to <!stify0 Tools and middle&are &ill become the "ey differentiator2 !ntil they2 too become commoditi'ed0

First Technology Transfer - Feb 2013

33

FreeRT% Fie& on CM 5 -RT%

The non-RT% -affiliated middle&are s!**lier

!**ly soft&are that m!st &or" &ith any RT% their c!stomers might be !sing0

Meed to *ro(ide their o&n abstraction layer to2 and test &ith2 a n!mber of different RT% sol!tions0 Re*lacing these m!lti*le abstraction layers &ith a single abstraction layer is a benefit0 The benefit &ill only become a reality ho&e(er if the end !sers are act!ally !sing CM 5 RT% in the *rod!cts they are designing and shi**ing0

First Technology Transfer - Feb 2013

38

FreeRT% Fie& on CM 5 -RT%

The microcontroller (endor Ty*ically2 *ro(ides soft&are 3*redominantly dri(ers4 that m!st interface &ith any system their c!stomers are !sing - a standard s!ch as CM 5 - RT% is beneficial es*ecially &hen dri(ers other than those based on a sim*le model need to be *ro(ided The tool (endor #ro(ides *rod!cts s!ch as exec!tion trace and *rofiling tools2 as &ell as "ernel a&are deb!gger *l!g-ins0 Lenerally s!ch tools do not access the RT% thro!gh the RT% 1s A#52 so &ill largely be !naffected0 Also2 these tools are *redominantly s!**lied by the RT% (endors themsel(es /ence !nli"ely to &ant their tools to be !sed &ith any com*etiti(e *rod!cts0
3?

First Technology Transfer - Feb 2013

#atterns of 5nter-*rocess Comm!nication and ynchronisation A Leneric A**roach

First Technology Transfer - Feb 2013

3B

Rationale

There are a n!mber of *atterns for inter-*rocess 6 inter-tas" comm!nication These *atterns a**ly to most *re-em*ti(e m!lti-tas"ing o*erating systems Kno&ing these *atterns ma"es it easier to str!ct!re code de(elo*ment for a (ariety of o*erating system A#5s 5n this co!rse the target % A#5 is the FreeRT% A#5 The FreeRT% s*ecific exam*les and code sni**ets &ill be co(ered in a follo& on section The exam*les in this section &ill be gi(en in *se!do-code and C0 The exam*les &ill be general in the sense that they &ill not be targeted at any *artic!lar o*erating system 3 real time or other&ise 40 From time to time s*ecific o*erating system A#5 interfaces &ill be mentioned to ill!strate real &orld code exam*les0 The most im*ortant thing is to !nderstand the !nderlying mechanisms2 as &ell as the (ario!s *atterns of *rogramming &ith the (ario!s o*erating system intertas" comm!nication *rimiti(es0

First Technology Transfer - Feb 2013

3C

Tas"s

Real time and embedded systems need to be able to handle m!lti*le in*!ts and m!lti*le o!t*!ts &ithin relati(ely tight time constraints0 A *ractical conc!rrent design decom*oses the a**lication into

mall e;!ential ched!lable *rogram !nits0

The design and im*lementation ob<ecti(e is to do this in s!ch a &ay that &hen the system is m!lti-tas"ing the design *erformance and timing re;!irements are satisfied0 A ty*ical RT% "ernel *ro(ides

Tas" ob<ects Tas" management ser(ices That facilitate the tas" of designing conc!rrency into the a**lication0

First Technology Transfer - Feb 2013

3G

Definition of a Tas"

Formally a tas" is

An inde*endent thread of exec!tion Com*etes &ith other conc!rrent tas"s for *rocessor exec!tion time 5s sched!lable - com*etes for exec!tion time based on some *re-determined sched!ling algorithm $*on creation is gi(en a distinct set of *arameters and s!**orting data str!ct!res

Mame $ni;!e id #riority 3 if associated &ith a *reem*ti(e sched!ler4 Tas" control bloc" tac" Tas" ro!tine

Ty*ically2 &hen a "ernel starts2


5t creates its o&n set of system tas"s and Allocates a s!itable *riority to each tas" The *riorities are from a set of *riority le(els reser(ed for RT% system tas"s
3J

First Technology Transfer - Feb 2013

ystem Tas"s

Ty*ical system tas"s incl!de


tart!* 3 initialisation 4 tas" 5dle tas" - !ses !* C#$ idle cycles &hen there is nothing else to do .ogging tas" - logs system messages Exce*tion-handling tas" Deb!g agent tas"

First Technology Transfer - Feb 2013

80

Finite tate Machine A**roach to Tas" ched!ling

A common *attern &hen designing sched!lers is to s*ecify a n!mber of *ossible states any gi(en tas" can be in0 A sim*le *attern2 ty*ical of many *re-em*ti(e sched!ling "ernels en(isions the follo&ing states

Ready state - tas" eligible to r!n2 b!t cannot r!n beca!se a higher *riority tas" is exec!ting -loc"ed state - occ!rs &here the tas"

/as re;!ested a reso!rce that is not immediately a(ailable /as re;!ested to &ait !ntil some e(ent occ!rs /as (ol!ntarily delayed itself for some d!ration

R!nning state - the tas" is c!rrently the one &ith the highest *riority and is r!nning

First Technology Transfer - Feb 2013

81

Finite tate Machine A**roach to Tas" ched!ling

First Technology Transfer - Feb 2013

82

#riority .e(els

)here a "ernel s!**orts more than one tas" *er *riority le(el

The "ernel maintains a tas"-ready list

%ne *er *riority le(el or A single combined list )itho!t bloc"ed states lo&er *riority tas"s co!ld not r!n0 A tas" can only mo(e to the bloc"ed state by ma"ing a bloc"ing call - re;!esting that some bloc"ing condition be met0 5f higher *riority tas"s are not designed to bloc" then C#$ star(ation may occ!r A bloc"ed tas" remains bloc"ed !ntil the bloc"ing condition is met

First Technology Transfer - Feb 2013

83

#riority .e(els

Common bloc"ing conditions incl!de

A sema*hore to"en for &hich a tas" is &aiting being released A message on &hich a tas" is &aiting arri(ing in a message ;!e!e A time delay im*osed on the tas" ex*iring 5t &ill mo(e from the bloc"ed state to the ready state if it is not the highest *riority tas" 5f it is the highest *riority tas" it mo(es directly to the r!nning state and *reem*ts the c!rrently r!nning tas" The *reem*ted tas" is itself mo(ed into the a**ro*riate *osition in the tas"-ready list
88

)hen a tas" becomes !nbloc"ed

First Technology Transfer - Feb 2013

Tas" Creation and Tas" Management er(ices

Ty*ically2 a "ernel &ill *ro(ide a tas"-management ser(ices A#5 for mani*!lating tas"s &ith methods for Creating and deleting tas"s Controlling tas" sched!ling %btaining information abo!t tas"s ome "ernels allo& a *rogram to First create the tas" Then start the tas" ome "ernels *ro(ide !ser-config!rable hoo"s &hich Ma"e it *ossible to r!n *rogrammer-s!**lied f!nctions &hen some s*ecific "ernel e(ent occ!rs The *rogrammer registers the f!nction &ith the "ernel - by *assing in the corres*onding f!nction *ointer as one of the arg!ments to the rele(ant "ernel A#5 f!nction #ossible "ernel e(ents )hen a tas" is first created )hen a tas" is s!s*ended and a context s&itch occ!rs )hen a tas" is deleted

First Technology Transfer - Feb 2013

8?

Tas" Deletion

Deletion of tas"s in embedded a**lications needs to be tho!ght abo!t0 An exec!ting tas"

Can ac;!ire memory Access reso!rces !sing other "ernel ob<ects

5f a tas" is not deleted correctly its reso!rces may not be released correctly and this may res!lt in !nfort!nate system beha(io!r e0g0

A tas" obtains a sema*hore to obtain excl!si(e access to a shared data str!ct!re The tas" is deleted &hile o*erating on this data str!ct!re The abr!*t deletion of the tas" may res!lt in

A corr!*t data str!ct!re - beca!se the &rite o*eration did not com*lete An !nreleased sema*hore - &hich means that other tas"s &ill not be able to ac;!ire the reso!rce A data str!ct!re that is inaccessible - beca!se of the !nreleased sema*hore

i0e0 the *remat!re deletion of a tas" can res!lt in memory or reso!rce lea"s
8B

First Technology Transfer - Feb 2013

Tas" ched!ling A#5 F!nctionality

Many "ernels *ro(ide an A#5 that *ermits man!al sched!ling0 A ty*ical set of o*erations s!**orted by s!ch an A#5 might incl!de the follo&ing 9

!s*end - to s!s*end a tas" Res!me - to res!me a tas" Delay - to delay a tas" Restart - to restart a tas" Let#riority - to get the *riority of the c!rrent tas" et#riority - to dynamically set the *riority of some tas" #reem*tion loc" - to loc" o!t higher *riority tas"s from *reem*ting the c!rrent tas" #reem*tion !nloc" - !ndoes a *reem*tion loc" o*eration

First Technology Transfer - Feb 2013

8C

%btaining Tas" 5nformation

Kernel A#5 F!nctionality for %btaining Tas" 5nformation is !sef!l e0g0 &hen monitoring or deb!gging an a**lication 5nformation ty*ically retrie(ed incl!des details s!ch as

The 5Ds of the installed tas"s The Tas" Control -loc" of the c!rrent tas" The reso!rces o&ned by the tas"

The state of the reso!rce The attrib!tes of the reso!rce

First Technology Transfer - Feb 2013

8G

Farieties of Tas"s

A common classification of tas"s in(ol(es classifying them as either

R!n to com*letion tas"s2 or 5nfinite loo* tas"s

First Technology Transfer - Feb 2013

8J

R!n-to-com*letion tas"s

The *se!docode demonstrating a r!n-to-com*letion tas" might loo" as follo&s (R nToCompletionTas)() * Initialisation(pplication+ Create a n m&er o" in,nite loop tas)s+ Create re- ired )ernel o&.ects/reso rces+ /elete/S spend this tas) 0

5n this exam*le of a r!n-to-com*letion tas"

A high *riority tas"


5nitialises and starts !* !* a collection of tas"s associated &ith the a**lication and then Ends itself0
?0

First Technology Transfer - Feb 2013

5nfinite .oo* Tas"s

5nfinite loo* tas"s m!st incl!de bloc"ing calls if other tas"s are to ha(e a chance of r!nning0

The *se!docode for an infinite loo* tas" might loo" as follo&s In,nite1oopTas)() * Initialisation steps 1oop 2ore#er * &ody o" loop code - incl des one or more &loc)in' calls 0 0

The im*ortant *oint to bear in mind &ith the abo(e exam*les is that they are based on a co-o*erati(e m!lti-tas"ing model

At the highest *riority le(el a tas" r!ns to com*letion or till it (ol!ntarily ma"es a bloc"ing call0
?1

First Technology Transfer - Feb 2013

5ntertas" Comm!nication

Ty*ical "ernel ob<ects for inter*rocess comm!nication and synchronisation incl!de

ema*hores Message ;!e!es ignals #i*es

First Technology Transfer - Feb 2013

?2

ema*hores

Formally - A sema*hore is a "ernel ob<ect that one or more threads of exec!tion 3tas"s4 can ac;!ire or release for the *!r*oses of synchronisation or m!t!al excl!sion0

)hen a sema*hore ob<ect is created the "ernel assigns a data str!ct!re - a sema*hore control bloc" 3 C-4 to it0 The "ernel also assigns a !ni;!e 5D2 a co!nt (al!e and a tas"-&aiting list0
?3

First Technology Transfer - Feb 2013

ema*hores

ema*hore A sema*hore can be tho!ght of as a "ey &hich a tas" m!st ha(e in order to access some reso!rce

5f the tas" can ac;!ire the sema*hore then it can access the reso!rce 5f a tas" cannot ac;!ire the sema*hore it m!st &ait till some other tas" releases it0 -inary Co!nting

There are t&o main "inds of sema*hore


First Technology Transfer - Feb 2013

?8

-inary ema*hores

A binary sema*hore can ha(e only t&o *ossible (al!es 0 and 10 )hen a sema*hore is not held by any tas" it has the (al!e 10 )hen a tas" ac;!ires a sema*hore its (al!e is set to 00 Mo other tas" can ac;!ire the sema*hore &hilst its (al!e is 00 A binary sema*hore is a global reso!rce - shared by all tas"s that need it /ence2 it is *ossible for a tas" other than the tas" that initially ac;!ired the sema*hore to release the sema*hore 5t is the choreogra*hy of sema*hore !sage amongst tas"s that ma"es sema*hores effecti(e0

First Technology Transfer - Feb 2013

??

Co!nting ema*hores

A co!nting sema*hore can be ac;!ired or released m!lti*le times0 5t does this (ia a co!nter0 5f the co!nt (al!e is 0 the co!nting sema*hore is in the !na(ailable state0 5f the co!nt is greater than 1 then the sema*hore is a(ailable0 )hen a co!nting sema*hore is created its initial co!nt can be s*ecified0 5n some o*erating systems the maxim!m co!nt (al!e can also be s*ecified - i0e0 the co!nting sema*hore is a bo!nded sema*hore 3 the co!nt is bo!nded 40 5n other o*erating systems the co!nt may be !nbo!nded0 Ac;!iring a co!nting sema*hore red!ces the co!nter (al!e by 12 and releasing the co!nting sema*hore increases the co!nter (al!e by 10

First Technology Transfer - Feb 2013

?B

M!t!al Excl!sion ema*hores 3M!texes4

A m!tex is a binary sema*hore - that may2 in some im*lementations2 ha(e additional feat!res s!ch as

%&nershi* Rec!rsi(e loc"ing Tas" deletion safety #riority in(ersion a(oidance *rotocol A m!tex is initially created in the !nloc"ed state - and can be ac;!ired by a tas"0 )hen a m!tex is ac;!ired its state becomes the loc"ed state0 )hen a m!tex is released 3by the tas" that o&ns it4 its state becomes the !nloc"ed state0 @ 5n some im*lementations the (erbs loc" and !nloc" are !sed in *lace of ac;!ire and release A )hen a tas" ac;!ires a m!tex it is said to ac;!ire o&nershi* )hen a tas" releases a m!tex that m!tex can be ac;!ired by another tas"0
?C

The m!tex can be in one of t&o states loc"ed 3042 or !nloc"ed 3140

%&nershi*

First Technology Transfer - Feb 2013

Rec!rsi(e .oc"ing

Rec!rsi(e loc"ing means that a tas" that o&ns a m!tex can ac;!ire it m!lti*le times in the loc"ed state0

!ch a m!tex is called a rec!rsi(e m!tex0

5n some im*lementation rec!rsi(e loc"ing may be a!tomatically b!ilt into the m!tex 2 in others it may be a *ro*erty that can be ex*licitly enabled0

A rec!rsi(e m!tex *ermits nesting of attem*ts to loc" the m!tex0 A f!nction that ac;!ires the m!tex can call another f!nction that can ac;!ire the m!tex again2 and can release the m!tex <!st before it ret!rns0

Tas" Deletion afety #remat!re tas" deletion can be a(oided by !sing a tas" deletion loc" &hen a tas" loc"s and !nloc"s the m!tex0

The tas" cannot be deleted &hile it o&ns the m!tex0 The m!tex is said to ha(e b!ilt-in tas" deletion safety0

First Technology Transfer - Feb 2013

?G

#riority 5n(ersion A(oidance

#riority in(ersion occ!rs &hen

A higher *riority tas" is bloc"ed beca!se it is &aiting for a lo&er *riority tas" to release a needed m!tex2 and &here The lo&er *riority tas" has itself been *reem*ted by an intermediate le(el *riority tas"0 Effecti(ely the *riority of the high *riority tas" has been in(erted to that of the lo& *riority tas"0

#rotocols associated &ith m!tex im*lementation ha(e been de(ised to a(oid *riority in(ersions

#riority inheritance *rotocol - the *riority of the lo&er *riority tas" that has ac;!ired the m!tex is raised to the *riority le(el of the tas" that re;!ested the m!tex &hen in(ersion ha**ens0

%nce the lo& *riority tas" releases the m!tex its *riority re(erts to the lo& le(el0

Ceiling *riority *rotocol - the *riority le(el of the tas" that ac;!ires the m!tex is a!tomatically set to the highest *riority of all *ossible tas"s the might re;!est that m!tex &hen the tas" ac;!ires the m!tex2 and

Re(erts to its reg!lar *riority &hen it releases the m!tex0


?J

First Technology Transfer - Feb 2013

M!tex tate Diagram

First Technology Transfer - Feb 2013

B0

Ty*ical ema*hore %*erations

Ty*ical sema*hore o*erations are


Creating and deleting a sema*hore Ac;!iring and releasing a sema*hore Clearing the tas"-&aiting list associated &ith a sema*hore %btaining information abo!t a sema*hore

Calls for im*lementing different "inds of sema*hores 3&here a "ernel s!**orts m!lti*le sema*hores4 may *ro(ide extra f!nctionality e0g0

-inary sema*hore - s*ecify initial sema*hore state and tas"&aiting order Co!nting sema*hore - s*ecify initial sema*hore (al!e2 bo!nd on the co!nt and the tas"-&aiting order M!tex - s*ecify the tas"-&aiting order2 enable tas" deletion safety2 rec!rsion2 *riority in(ersion *rotocols

First Technology Transfer - Feb 2013

B1

ema*hore %*erations

Deleting a ema*hore

)hen a sema*hore is deleted

Any bloc"ed tas"s in the tas"-&aiting list are !nbloc"ed and mo(ed into the ready state 3 or into the r!nning state if they are the highest *riority tas"s 4 Any tas" attem*ting to ac;!ire a deleted sema*hore ret!rns &ith an error message

M0-0 - a sema*hore sho!ld not be deleted if it is ac;!ired0 Ty*ical &ays of ac;!iring sema*hore

Ac;!iring and Releasing ema*hores

)ait fore(er - tas" remains bloc"ed !ntil it is able to ac;!ire the sema*hore )ait &ith a timeo!t - tas" remains bloc"ed !ntil it can ac;!ire the sema*hore2 or till the time-o!t *eriod s*ecified ex*ires 3 in &hich case the tas" is *laced on the ready list 4 Do not &ait - if a sema*hore to"en is not a(ailable then the tas" does not bloc" - it sim*ly ret!rns 3 !s!ally ret!rning some (al!e 6 setting some (ariable 4 indicating it &as not able to ac;!ire the sema*hore0
B2

First Technology Transfer - Feb 2013

ema*hore %*erations - ctd0

5nterr!*t er(ice Ro!tines 35 Rs4 and ema*hores

5 Rs may release binary and co!nting sema*hores0 5t is not 3in general4 meaningf!l to ac;!ire a binary or co!nting sema*hore inside an 5 R .oc"ing and !nloc"ing of m!texes inside an 5 R is also not meaningf!l 3 and most "ernels do not s!**ort s!ch an action 4 Any tas" can release a binary or co!nting sema*hore A m!tex can only be release by the tas" that ac;!ired it ome "ernels *ro(ide a fl!sh o*eration for clearing all tas"s on a sema*hore tas"-&aiting list0 The fl!sh o*eration can be !sed as a mechanism for broadcast 3 more s*ecifically m!lticast 4 signaling0

-inary and Co!nting ema*hores and M!texes

Clearing ema*hore Tas" )aiting .ists

First Technology Transfer - Feb 2013

B3

Thread Rende'(o!s

A *ossible !se of the fl!sh mechanism

A set of tas"s need to finish their *artic!lar o*erations2 and then to bloc" by trying to ac;!ire a common sema*hore that is made !na(ailable )hen the last tas" has finished its *artic!lar o*erations it can exec!te a sema*hore fl!sh o*eration on the common sema*hore This &ill free all the tas"s &aiting on the sema*hore1s &aiting list

First Technology Transfer - Feb 2013

B8

Letting ema*hore 5nformation

Meeded in monitoring and deb!gging sit!ations Ty*ical sema*hore information o*erations are

ho& information - *ro(ides general information abo!t the sema*hore ho& bloc"ed tas"s - gets a list of 5Ds of tas"s bloc"ed on the sema*hore

First Technology Transfer - Feb 2013

B?

ema*hore $sage #atterns

Ty*ical ema*hore $sage #atterns

)ait and signal synchronisation M!lti*le tas" &ait and signal synchronisation Credit trac"ing synchronisation ingle shared reso!rce access synchronisation Rec!rsi(e shared reso!rce access synchronisation M!lti*le shared reso!rce access synchronisation

First Technology Transfer - Feb 2013

BB

)ait and ignal ynchronisation

/ere t&o tas"s comm!nicate for the *!r*ose of synchronisation &itho!t the exchange of information0

)ait and ignal ynchronisation can be accom*lished !sing a binary sema*hore


5nitially the binary sema*hore is !na(ailable 3 (al!e P 0 4 The higher *riority tas" 3the &ait tas"4 r!ns first At some *oint it ma"es a re;!est for the sema*hore -!t is bloc"ed beca!se the sema*hore is not a(ailable This gi(es the lo&er *riority tas" 3 the signal tas"4 an o**ort!nity to r!n At some *oint the lo&er *riority tas" releases the sema*hore th!s

$nbloc"ing the higher *riority tas" &hich Then *re-em*ts the lo&er *riority tas"

First Technology Transfer - Feb 2013

BC

M!lti*le Tas" )ait and ignal ynchronisation

5n this *attern there are se(eral higher *riority tas"s 3 the &ait tas"s 4

5nitially the binary sema*hore is !na(ailable 3 (al!e P 0 4 The higher *riority tas"s 3the &ait tas"s4 r!n first At some *oint each ma"es a re;!est for the sema*hore -!t is bloc"ed beca!se the sema*hore is not a(ailable This gi(es the lo&er *riority tas" 3 the signal tas"4 an o**ort!nity to r!n

At some *oint the lo&er *riority tas" fl!shes the sema*hore th!s

$nbloc"ing the higher *riority tas"s &hich then *re-em*t the lo&er *riority tas"

First Technology Transfer - Feb 2013

BG

Credit Trac"ing ynchronisation

5n this *attern - the signaling tas" exec!tes at a higher rate than the signaled tas" 3 the &ait tas" 42 and the signaling tas" r!ns at a higher *riority than the signaled tas"

ome mechanism is needed to co!nt signalling occ!rrences This can be done !sing a co!nting sema*hore

)hen a signaling tas" signals the sema*hore co!nt is 3 atomically 4 incremented 3 a release o*eration is *erformed on it 4 )hen the signaled tas" is able to r!n it tries to ac;!ire the co!nting sema*hore - and either bloc"s 3 if the sema*hore co!nter is at 'ero 4 or s!cceeds and decrements the sema*hore co!nt 3 atomically 4 by one The !nderlying ass!m*tion is that the signaling tas" may signal in b!rsts and the signaled tas" has a chance to :catch !*: in bet&een b!rsts

Exam*le scenario9

An 5nterr!*t er(ice Ro!tine 35 R4


Exec!tes at high *riority &hen the interr!*t is triggered %ffloads remaining *rocessing to a lo&er *riority tas" &aiting on a sema*hore

First Technology Transfer - Feb 2013

BJ

Credit Trac"ing ynchronisation - ctd0

#se!do code for credit trac"ing synchronisation t3aitTas) () * .. (c- ire co ntin' semaphore .. 0 tSi'nalTas) () * .. Release co ntin' semaphore .. 0

First Technology Transfer - Feb 2013

C0

ynchronising Access to a hared Reso!rce

A sema*hore can be !sed to ynchronise Access to a hared Reso!rce

The ob<ecti(e is to ens!re that only one tas" 6 conc!rrent thread of exec!tion at a time can access the shared reso!rce0 Create a binary sema*hore - initially in the a(ailable state 5n order to access the shared reso!rce a tas" m!st first ac;!ire the sema*hore Any other tas" attem*ting to ac;!ire this sema*hore &ill no& bloc" )hen a tas" has finished &ith the shared reso!rce it releases the sema*hore A tas" that &as bloc"ed in its attem*t to ac;!ire the sema*hore is no& !nbloc"ed and can *roceed to ma"e !se of the shared reso!rce
C1

The strategy is as follo&s9


First Technology Transfer - Feb 2013

ynchronising Access to a hared Reso!rce

#se!do code for shared reso!rce access synchronisation t(ccessTas) () * .. (c- ire &inary semaphore Ma)e se o" the shared reso rce ( e.'. read or write to it ) Release the &inary semaphore .. 0

=!estions9

)hat if a tas" accidentally releases the sema*hore - e0g0 a tas" that did not ac;!ire the sema*hore in the first *lace > )hat if there is more than one tas" bloc"ing on the sema*hore &hen the sema*hore is released > /o& might the !se of a m!tex sema*hore 3 a sema*hore that s!**orts the conce*t of o&nershi* &herein only the tas" that s!ccessf!lly ac;!ired the m!tex can release it 4 hel* >

First Technology Transfer - Feb 2013

C2

ynchronising Rec!rsi(e Access to a hared Reso!rce

The scenario is as follo&s

A tas"2 tAccessTask2 calls routine A &hich in t!rn calls routine B and all three need access to the same shared reso!rce
t(ccessTas)() * .. (c- ire m te! (ccess shared reso rce Call Ro tine ( Release m te! .. 0 Ro tine (() * .. (c- ire m te! (ccess shared reso rce Call Ro tine 4 Release m te! .. 0 Ro tine 4() * .. (c- ire m te! (ccess shared reso rce Release m te! .. 0

The *se!do code for s!ch a scenario might be 5n this scenario 2 !sing a reg!lar m!tex 2 - Ro!tine A &o!ld end !* bloc"ing on a sema*hore that the tas" it is r!nning in already o&ns0 %ne sol!tion to s!ch a *roblem &o!ld be to !se a rec!rsi(e m!tex - here once a tas" has ac;!ired a m!tex then additional attem*ts from the tas" itself2 or from ro!tines called by that tas" to ac;!ire the m!tex &ill s!cceed

First Technology Transfer - Feb 2013

C3

Controlling Access to M!lti*le E;!i(alent hared Reso!rces

The strategy here is to !se a co!nting sema*hore

5nitialise the co!nt of the sema*hore to the n!mber of e;!i(alent shared reso!rces

)hen a tas" re;!ests the sema*hore The sema*hore co!nt &ill be decremented by one if it is greater than 'ero The tas" &ill bloc" if the sema*hore co!nt is 'ero #roblems can arise if a tas" releases a sema*hore it did not first ac;!ire

First Technology Transfer - Feb 2013

C8

Message =!e!es

A message ;!e!e can be !sed by tas"s and 5 Rs to comm!nicate and to synchronise &ith data - it

$tilises a b!ffer li"e ob<ect - a *i*eline that2 tem*orarily2 holds messages from a sender3s4 till the target recei(er is able to read them Deco!*les sending and recei(ing tas"s An associated =!e!e Control -loc" 3=C-4 is assigned to it A message ;!e!e name and a !ni;!e 5D are assigned to it Memory b!ffers are assigned to it - based on *ro*erties s!ch as ;!e!e length and maxim!m message length %ne or more tas" &aiting lists may be associated &ith it - ty*ically

)hen a message ;!e!e is created2 then2 ty*ically2

A sending tas" - bloc"s &hen the message ;!e!e is f!ll A reading tas" - bloc"s &hen the message ;!e!e is em*ty

First Technology Transfer - Feb 2013

C?

Message =!e!es - ctd0

Messages are read from the head of the message ;!e!e and added to the tail of the message ;!e!e

First Technology Transfer - Feb 2013

CB

Message =!e!e - tate -eha(io!r


)hen a message ;!e!e is created its initial state &ill be the em*ty state 5f a tas" attem*ts to recei(e messages from an em*ty message ;!e!e it &ill bloc" if the tas" &ishes to it is held in the tas" &aiting list 3 in e0g0 a F5F% or *riority-based order 4 5f a message is sent to a tas" bloc"ing on an em*ty message ;!e!e then it &ill be deli(ered directly to the bloc"ed tas"

The tas" &ill be remo(ed from the tas"-&aiting list and mo(ed to either the ready state or to the r!n state The message ;!e!e remains in the em*ty state

5f a message is sent to an em*ty message ;!e!e and there is no bloc"ed tas" then the message ;!e!e is in the non-em*ty state

Additional messages &ill be ;!e!ed !* till the n!mber of messages reaches the maxim!m n!mber the ;!e!e can hold 3 the ;!e!e length 4 )hen the ;!e!e is in the f!ll state then any tas"ing sending a message to that ;!e!e &ill fail

Fail!re may be indicated 3 de*ending on "ernel im*lementation details 4 e0g0 by


Letting the sending f!nction to ret!rn an error code to that tas" Allo&ing the tas" to bloc" and mo(ing it to the sending-tas"-&aiting-list
CC

First Technology Transfer - Feb 2013

Message =!e!e - tate Diagram

First Technology Transfer - Feb 2013

CG

Message ending Mechanisms

The details are de*endent on

The im*lementation of the "ernel2 and also2 on &hether Firt!al memory management is in o*eratio and

The (ario!s tas"s are r!nning in their o&n (irt!al address s*aces0

/ere are some *ossibilities9

The message is co*ied t&ice


Firstly from the tas"1s memory area to the message ;!e!e1s memory area econdly from the message ;!e!e1s memory area to the recei(ing tas"1s memory area2 ho&e(er2

5f there is a recei(ing tas" already bloc"ed on the message ;!e!e then 3 in some "ernel im*lementations 4 the message may be co*ied directly from the sending tas"1s memory are to the recei(ing tas"1s memory area 5n real time embedded systems the cost in terms of C#$ cycles and memory re;!irements in(ol(ed in co*ying may be red!ced by !sing *ointers instead
CJ

First Technology Transfer - Feb 2013

Memory Allocation for Message =!e!es

Memory locations for message ;!e!es are also "ernel im*lementation de*endent

The "ernel may *ro(ide a system memory *ool


All ;!e!es share this common memory area /el*s red!ce memory re;!irements if it is reasonable to ass!me that it &ill be rare for all message ;!e!es to be f!ll to ca*acity at the same time #roblems may arise in the case of message ;!e!es needing to hold large messages &hich !se !* 3 on occasions 4 a large share of the a(ailable system memory

Th!s ca!sing other message ;!e!es to fail beca!se there is not eno!gh a(ailable memory )hen a message ;!e!e is created a *ri(ate b!ffer is allocated to it

$ses !* more memory More reliable - as ens!res there is ade;!ate memory a(ailable for all messages
G0

First Technology Transfer - Feb 2013

%*erations on Message =!e!es


Create message ;!e!e Delete message ;!e!e end message to message ;!e!e -loc"ing *olicy

Mon-bloc"ing - 5 Rs and tas"s -loc"ing &ith timeo!t - tas"s only -loc"ing for e(er - tas"s only F5F% .5F%

=!e!eing disci*line

-roadcast a message M!lticast a message =!ery message ;!e!e for stat!s information Let information abo!t the message ;!e!e 3 e0g0 ;!e!e 5D2 ;!e!ing order 3 e0g0 F5F% or *riority based 42 n!mber of ;!e!ed messages 4 Let list of tas"s in the ;!e!e1s tas" &aiting list
G1

First Technology Transfer - Feb 2013

%*erations on Message =!e!es - ctd0

Recei(e message from message ;!e!e -loc"ing *olicy - on an em*ty message ;!e!e - bloc"ed recei(ing tas"s fill the tas" list

-loc"ing &ith timeo!t -loc"ing for e(er

Message reading *olicy

Destr!cti(e read - message *ermanently remo(ed from message ;!e!e1s storage b!ffer Mon-destr!cti(e read - recei(ing tas" :*ee"s: at message at head of ;!e!e b!t does not remo(e it

=!e!ing order

F5F% #riority based

First Technology Transfer - Feb 2013

G2

Message =!e!e - $se #atterns

Ty*ical #atterns for $sing Message =!e!es

Mon-interloc"ed 2 one-&ay data comm!nication 5nterloc"ed 2 one-&ay data comm!nication 5nterloc"ed 2 t&o-&ay data comm!nication -roadcast comm!nication

)hat other *atterns of message ;!e!e !sage ha(e yo! come across > )hat ha**ens &hen message ;!e!eing is to be attem*ted on distrib!ted systems >
G3

First Technology Transfer - Feb 2013

.oosely Co!*led Data Comm!nication

Mon-5nterloc"ed2 %ne-)ay 3 .oosely Co!*led 4 Data Comm!nication in(ol(es

A sending tas" - &hich so!rces messages A message ;!e!e A recei(ing tas" - &hich acts as a sin" for messages

Details of beha(io!r &ill de*end on the relati(e *riorities of the sending and recei(ing tas"s

)here the recei(ing tas" has higher *riority it &ill r!n first !ntil it bloc"s on an em*ty message ;!e!e

)hen the sending tas" sends a message the recei(ing tas" &ill !nbloc" and r!n again

)here the recei(ing tas" has the lo&er *riority then the sending tas" &ill fill the message ;!e!e &ith messages till it bloc"s 3 or s!s*ends itself 4

The recei(ing tas" &ill :&a"e !*: and start *rocessing the recei(ed messages

First Technology Transfer - Feb 2013

G8

5 Rs and Message =!e!es

5nterr!*t er(ice Ro!tines 35 Rs4 ty*ically !se the noninterloc"ed2 one-&ay data comm!nication *attern

The recei(ing tas" r!ns and &aits on a message ;!e!e )hen triggered2 the 5 R *laces one or more message on the message ;!e!e 5f the message ;!e!e if f!ll then messages may be lost or o(er&ritten

5 Rs m!st send messages in a non-bloc"ing &ay

5m*lementation de*endent

First Technology Transfer - Feb 2013

G?

5nterloc"ed2 %ne-)ay Data Comm!nication

5n this *attern the sending tas" sends a message and &aits to see if the message has been recei(ed

5f the message is2 for some reason2 not recei(ed correctly then it can be re-transmitted The *attern can be !sed as means of closing a synchronisation loo* so that the sending and recei(ing tas"s o*erate in loc"ste* &ith one another

*ossible im*lementation of loc"ste* - in(ol(ing a sending tas"2 a message ;!e!e 3 &ith a length of 1 4 2 a recei(ing tas" and a binary sema*hore

The initial (al!e of the binary sema*hore is 0 The sending tas" sends a message to the message ;!e!e and bloc"s on the binary sema*hore The recei(ing tas" recei(es the message and increments the binary sema*hore The sending tas" !nbloc"s and sends the next message The sema*hore is2 in effect2 acting as a sim*le ac"no&ledgement to the sender that it is %K to send the next message
GB

First Technology Transfer - Feb 2013

%ne-)ay Data Comm!nication exam*le

#se!docode for 5nterloc"ed2 %ne-)ay Data Comm!nication exam*le tSenderTas)() * ... Send messa'e to messa'e - e e (c- ire &inary semaphore ... 0 tRecei#erTas)() * ... Recei#e messa'e "rom messa'e - e e Release &inary semaphore ... 0

First Technology Transfer - Feb 2013

GC

5nterloc"ed2 T&o-)ay Data Comm!nication

5nterloc"ed2 T&o-)ay Data Comm!nication in(ol(es t&o tas"s and t&o message ;!e!es

ynchronisation details de*end on the "ind of data that needs to be exchanged


For t&o &ay exchange of data t&o message ;!e!es are re;!ired For sim*le ac"no&ledgement a sema*hore can be !sed

tClientTas)() * ... Send messa'e to ser#er5s re- ests messa'e - e e (c- ire &inary semaphore ... 0 tSer#erTas)() * ... Recei#e messa'e "rom ser#er5s responses messa'e - e e Release &inary semaphore ... 0
First Technology Transfer - Feb 2013 GG

-roadcast Comm!nication

A broadcast comm!nication *attern in(ol(es

A broadcast sending tas"2 a message ;!e!e2 a n!mber of recei(ing tas"s

The broadcast sender sends a message to the message ;!e!e

Each of the recei(ing tas"s recei(es the message from the message ;!e!e

=!estions9

/o& might a "ernel im*lementation s!**ort broadcast comm!nication in(ol(ing a message ;!e!e /o& &o!ld a recei(er tas" associate itself &ith a message ;!e!e> )o!ld it ma"e sense for recei(er tas"s to bloc" on an em*ty message ;!e!e> )hat if a res*onse &as ex*ected from 0 or 1 recei(er tas"s only - and a res*onse from t&o or more recei(er tas"s &as an error > /o& &o!ld the abo(e scenarios be modified 6 extended if sender and recei(er tas"s &ere r!nning on different machines 6 *rocessors> !**ose it &as necessary to disting!ish bet&een ordinary messages and !rgent messages>

First Technology Transfer - Feb 2013

GJ

#5#E

#i*es are "ernel ob<ects *ro(ided by o*erating systems s!ch as $nix6.in!x and )indo&s A *i*e

!**orts !nidirectional stream oriented data exchange 5s made !* of t&o descri*tors - that are ret!rned &hen an instance of the *i*e is created

%ne for the reading end - data is read from the read descri*tor %ne for the &riting end - data is &ritten to the &rite descri*tor

Data is held 3 b!ffered 4 in the *i*e as an !nstr!ct!red byte stream Data is read from the *i*e in fifo order The reader *rocess bloc"s &hen the *i*e is em*ty The &riter *rocess bloc"s &hen the *i*e is f!ll Cannot store m!lti*le messages The data in the *i*e is not str!ct!red The data in the *i*e cannot be *rioritised Fia the select o*eration a tas" can bloc" an &ait for a s*ecified condition to become tr!e on one or more *i*es
J0

$nli"e a message ;!e!e a *i*e


First Technology Transfer - Feb 2013

#5#E - 5#C

First Technology Transfer - Feb 2013

J1

#5#E - Control -loc" - Creation

#i*e Creation and #i*e Control -loc"s


#i*es can be created and destroyed dynamically )hen a *i*e instance is created the "ernel creates a *i*e control bloc" A *i*e control bloc" contains *i*e s*ecific information 3 maintained by the "ernel 4 e0g0

i'e of *i*e b!ffer - s*ecified at creation time and then remains fixed C!rrent data byte co!nt 5n*!t and o!t*!t *osition indicators T&o descri*tors in file i6o s*ace - &hich &ill be !ni;!e

These descri*tors are ret!rned to the tas" creating the *i*e Details (ary from "ernel to "ernel

There are t&o tas" &aiting lists associated &ith a *i*e


.ist of tas"s &aiting to &rite to the *i*e 3 bloc"ed &hen *i*e b!ffer is f!ll 4 .ist of tas"s &aiting to read from the *i*e 3 bloc"ed &hen the *i*e b!ffer is em*ty 4
J2

First Technology Transfer - Feb 2013

#5#E tate Diagram

First Technology Transfer - Feb 2013

J3

#5#E %*erations

Create *i*e Destroy *i*e Read from *i*e


Ret!rns data to calling tas" Calling tas" s*ecifies ho& m!ch data to read Tas" may o*t to bloc" - &aiting for remaining data to arri(e - if amo!nt of data re;!ested is greater than &hat is a(ailable in the *i*e #i*e reads are destr!cti(e - data 5 REM%FED FR%M T/E #5#E %nce data has been read it is not a(ailable to other readers A**ends ne& data to existing byte stream in the *i*e Tas" may choose to bloc" - &aiting for additional b!ffer s*ace to become a(ailable - if the amo!nt of data to be &ritten is greater than the s*ace a(ailable c!rrently in the *i*e b!ffer -eca!se there are no message bo!ndaries in a *i*e it is not *ossible to determine the original *rod!cer of the data bytes Data &ritten to a *i*e CAMM%T -E #R5%R5T5 ED - D% M%T $ E A #5#E 5F $RLEMT DATA MEED T% -E EHC/AMLED -ET)EEM TA K QQQ
J8

)rite to *i*e

First Technology Transfer - Feb 2013

#5#E %*erations - ctd0

#i*e Control2 Fl!sh and elect %*erations 3 Ty*ical 4

Control - the fcntl o*eration - !sed to alter the beha(io!r 6 attrib!tes of the *i*e e0g0 - &hether a tas" sho!ld bloc" if a read o*eration is attem*ted on an em*ty *i*e or a &rite o*eration is attem*ted on a f!ll *i*e Fl!sh

This command remo(es all data from the *i*e and clears all conditions in the *i*e so that the *i*e re(erts to the state it had &hen it &as created $sef!l for e0g0 remo(ing data that has been "e*t in the *i*e for too long and is no& o!t of date $sed to *ermit a tas" to bloc" for some s*ecified condition to occ!r in one or more *i*es e0g0

elect - *robably the main ad(antage of a *i*e o(er a message ;!e!e

)aiting for data to become a(ailable in a *i*e3s4 )aiting for data to be em*tied from a *i*e3s4 Exam*le - !sing select a tas" may be &aiting to read from one of t&o *i*es and &rite to a third

elect ret!rns &hen data becomes a(ailable in one or other of the t&o *i*es being read from2 or &hen s*ace becomes a(ailable in the *i*e being &ritten to
J?

First Technology Transfer - Feb 2013

#5#E - Exam*le

Exam*le - !sing *i*es for inter-tas" synchronisation T&o tas"s 3 A and - 4 and t&o *i*es

%ne *i*e o*ened so that it is &ritten to by A and read from by %ther *i*e o*ened so that it is read from by A and &ritten to by A and - both iss!e a select o*eration on the *i*es

Tas" A can iss!e a non-bloc"ing call to &rite to the *i*e and *erform other o*erations !ntil the *i*e becomes &riteable 3 beca!se tas" has read some data from the *i*e 3 i0e0 tas" A can &ait asynchrono!sly for the data *i*e to become &riteable 4 Tas" A can &ait asynchrono!sly for arri(al of a transfer ac"no&ledgement from tas" Tas" - can &ait asynchrono!sly for the arri(al of a transfer ac"no&ledgement from tas" A Tas" - can &ait for the other *i*e to become &riteable before sending an ac"no&ledgement

First Technology Transfer - Feb 2013

JB

E(ent Registers

An e(ent register

5s associated &ith a tas" Details are hard&are and "ernel s*ecific 5s a collection or binary e(ent flags Ty*ically G2 1B or 32 bits

Each bit in the e(ent register is associated &ith some s*ecific e(ent Each bit can either be set or cleared

$sed by a tas" to chec" for the occ!rrence 6 non-occ!rrence of a *artic!lar e(ent Can be !sed by an 5 R to inform a tas" that a *artic!lar e(ent has occ!rred A tas" *erforms conditional chec"s s*ecified by a combination 3 !sing AMDs and %Rs 4 of the e(ent register bit flags

E(ent chec"ing strategies can be

Mo &ait )ait indefinitely )ait &ith timeo!t


JC

First Technology Transfer - Feb 2013

E(ent Registers - ctd0

The e(ent register control bloc" is 3ty*ically4 *art of the tas" control bloc" and 3ty*ically4 contains the follo&ing fields

)anted e(ents register E(ents the tas" &ishes to recei(e Recei(ed e(ents

E(ents that ha(e :arri(ed: are recorded here et by tas" to indicate ho& long it &ishes to &ait for the arri(al of the e(ents it is :interested in: *ecify 3to the "ernel4 the conditions 3occ!rring as a res!lt of e(ent arri(als4 !nder &hich the tas" &ishes to be &o"en !*

Timeo!t (al!e

Motification conditions

The main e(ent register o*erations 3 ty*ically 4 are


end - an e(ent is sent to a tas" Recei(e - !sed by a calling tas" to recei(e e(ents from external so!rces

A tas" can s*ecify &hether or not it &ishes to &ait2 and2 5f &aiting2 &hether it &ishes to &ait indefinitely or only for a s*ecified timeo!t *eriod
JG

First Technology Transfer - Feb 2013

$sing E(ent Registers

Mo data is associated &ith an e(ent &hen an e(ent is sent thro!gh an e(ent register #ending e(ents in the e(ent register do not change the exec!tion state of the recei(ing tas" There is no mechanism for identifying the so!rce of an e(ent

5dentifying *rotocols need to be agreed !*on bet&een senders and recei(ers - e0g0

A *artic!lar tas" sends a *artic!lar e(ent by setting a *artic!lar bit in the e(ent register 4

E(ents in the e(ent register are not ;!e!ed An e(ent register cannot co!nt the n!mber of occ!rrences of an e(ent &hile it is *ending

First Technology Transfer - Feb 2013

JJ

ignals

A signal is a soft&are interr!*t

Lenerated in res*onse to some e(ent occ!rring Triggers the asynchrono!s exec!tion 3 in the target tas" 4 of the associated signal handler ro!tine 3 as s*ecified by the tas" for dealing &ith that signal 4

The n!mbers and ty*es of a(ailable signals are system and o*erating system de*endent Ty*ical ty*es of e(ents associated &ith signals

An attem*t to *erform an illegal o*eration d!ring *rogram exec!tion

e0g0 a di(ide by 'ero

Motification from a tas" to another tas" that it is abo!t to terminate ome !ser gest!re - e0g0 ty*ing in a combination of characters corres*onding to a :;!it: command

A signal is identified by a signal n!mber 3 (ector n!mber 4 - &hich is its *osition in the ignal Register 6 Fector Table
100

First Technology Transfer - Feb 2013

ignal Control -loc"

The signal control bloc" is 3 ty*ically 4 *art of the tas" control bloc"

Maintains a list of signals the tas" is *re*ared to handle 3 catch 4 A tas" can s*ecify a signal handler for each signal it &ishes to *rocess2 or2 sim*ly rely on a defa!lt handler A signal interr!*t is often referred to as :raising a signal in the interr!*ted tas":

5f a signal arri(es &hile a tas" is *rocessing another signal The additional signal is *laced in a signals *ending list As soon as a tas" finishes *rocessing a signal the next signal in the signals *ending list can :raise a signal: on that tas"

5t is *ossible for a tas" to *artially *rocess a signal and then to *ass the signal on for f!rther *rocessing by the defa!lt handler 5t is *ossible for a tas" to bloc" the deli(ery of a signal d!ring certain :critical: stages in that tas"1s *rocessing

The tas" tells the "ernel to bloc" certain signals by setting the a**ro*riate (al!es in the :bloc"ed signals set:

The "ernel &ill not deli(er a signal listed in the :bloc"ed signals set: !ntil that signal is cleared from the set
101

First Technology Transfer - Feb 2013

Ty*ical %*erations on ignals

Catch - installs a handler for a s*ecified signal The f!nction *ointer or offset to the asynchrono!s signal handler ro!tine is entered into the corres*onding element in the (ector table Release - remo(es a *re(io!sly installed handler A common *ractice is to restore the *re(io!s 3 defa!lt 4 handler in *lace of the handler that has been released end - !sed by one tas" or 5 R to send a signal to another tas" This is an ex*licit tas" le(el o*eration ome signals are sent a!tomatically 3 (ia the "ernel 4 &hen e(ents s!ch as memory access (iolations or floating *oint exce*tions occ!r 5gnore - !sed to instr!ct the "ernel to not deli(er certain signals to the tas" ome signals cannot be ignored and &hen they occ!r the "ernel &ill call the defa!lt handler -loc" - !sed to *rotect critical sections of code by *re(enting signals from being deli(ered to the tas" The signal is not ignored -loc"ing can also be !sed to a(oid nesting of signal *rocessing e0g0 &hen a signal arri(es in the midst of ongoing signal *rocessing $nbloc" - allo&s a *re(io!sly bloc"ed signal to *ass - signal deli(ered immediately if already *ending
102

First Technology Transfer - Feb 2013

$sing ignals

ignals can be !sed

-y an 5 R To carry o!t less !rgent *rocessing associated &ith an interr!*t e(ent To inform a tas" that some s*ecific hard&are e(ent has occ!rred For synchronisation bet&een tas"s - b!t sho!ld be !sed s*aringly2 beca!se

%f o(erheads associated &ith the com*lexity of the signaling facility The signal alters the exec!tion state of the target tas" -eca!se signals occ!r asynchrono!sly - a tas" that handles signals becomes non-deterministic

First Technology Transfer - Feb 2013

103

$sing ignals - ctd0

Things to be a&are of 9

)here an im*lementation does not s!**ort ;!e!ing or co!nting of signals - m!lti*le occ!rrences of a signal &ill o(er&rite each other ome im*lementations do not s!**ort deli(ery of information &ith the signal ome im*lementations do not s!**ort *rioritisation of signals so that a more im*ortant signal may not necessarily be dealt &ith !rgently ome im*lementations do not g!arantee &hen an !nbloc"ed *ending signal &ill be deli(ered to the target tas" Real- time signal handling extensions - im*lemented by some "ernels #rioritised deli(ery of signal - *riority determined by signal n!mber ignal can carry additional information M!lti*le occ!rrences of the same signal &ill be ;!e!ed
108

First Technology Transfer - Feb 2013

Condition Fariables

A condition (ariable

5s a "ernel ob<ect associated &ith some shared reso!rce $sed to allo& one tas" to &ait till some other tas" sets the shared reso!rce to some re;!ired condition Ty*ically ded!ced by e(al!ating some "ind of *redicate

)hen a tas" examines a condition (ariable it m!st ha(e excl!si(e access to that (ariable

A m!tex is therefore !sed in con<!nction &ith a condition (ariable The tas" m!st first ac;!ire the m!tex before e(al!ating the *redicate 5f the *redicate e(al!ates to false the tas" bloc"s till the desired condition is attained

The o*eration of releasing the m!tex and bloc"-&aiting for the condition is g!aranteed by the "ernel to be an atomic o*eration
10?

First Technology Transfer - Feb 2013

Condition Fariable -loc"

A condition (ariable bloc"

5s set !* &hen the condition (ariable is created

tores 5nformation associated &ith the condition (ariable Reference to the g!arding m!tex Reference to the tas"-&aiting list Tas" a&a"ening may be

%n a F5F% or #riority based or ome other "ernel defined *rotocol

First Technology Transfer - Feb 2013

10B

Condition Fariable %*erations

Create - create and initialise the condition (ariable )ait - &ait on a condition (ariable

To &ait a tas" m!st first s!ccessf!lly ac;!ire the g!arding m!tex

#!ts tas" into the tas"-&aiting ;!e!e and releases the associated m!tex in a single atomic o*eration

ignal - signal the condition (ariable

Modify the condition (ariable to indicate some *artic!lar condition has been realised in the shared reso!rce

$nbloc"s one of the tas"s &aiting on the condition (ariable

)hen the signal o*eration has com*leted the "ernel reac;!ires the m!tex associated &ith the condition (ariable on behalf of the !nbloc"ed tas" in one atomic o*eration

-roadcast - &a"es !* e(ery tas" on the condition (ariable1s tas"-&aiting list

%ne tas" is chosen by the "ernel and gi(en the g!arding m!tex %ther tas"s are remo(ed from the condition (ariable1s tas"-&aiting list and *!t on the tas"-&aiting list of the condition (ariable1s associated g!arding m!tex
10C

First Technology Transfer - Feb 2013

$sage of Condition Fariables

#se!do Code Exam*le - $sing Condition Fariables


/ /Tas) 6: 1oc) M te! 7!amine shared reso rce 3hile ( shared reso rce is & sy ) 3(IT ( condition #aria&le ) Mar) shared reso rce as 4 sy 8nloc) M te! / /Tas) 9: 1oc) M te! Mar) shared reso rce as 2ree SI:;(1 ( condition #aria&le ) 8nloc) M te!

Mote9

A signal on a condition (ariable is lost &hen there is nothing &aiting on it - hence


A tas" sho!ld chec" for *resence of desired condition before &aiting on it A tas" sho!ld chec" for *resence of desired condition after a &a"e!*

First Technology Transfer - Feb 2013

10G

5nterr!*ts and Exce*tions

An exce*tion is an e(ent that


Disr!*ts the normal exec!tion of the *rocessor Forces the *rocessor into exec!tion of s*ecial instr!ctions in a *ri(ileged state ynchrono!s exce*tions

Exce*tions may be

Lenerated as a res!lt of exec!tion of *rocessor instr!ctions 3e0g0 memory alignment exce*tion2 di(ide by 'ero exce*tion4 Raised by external e(ents not directly related to the exec!tion of *rocessor instr!ctions

Asynchrono!s exce*tions 3 normally called interr!*ts 4

Lenerally associated &ith hard&are signals 3e0g0 *rocessor reset2 recei*t of a *ac"et by some net&or" interface de(ice4

#ro(ide a comm!nication mechanism bet&een the hard&are and an a**lication c!rrently r!nning on the *rocessor - !sed in the follo&ing contexts

/andling of internal errors and s*ecial conditions Dealing &ith hard&are conc!rrency /andling of ser(ice re;!ests
10J

First Technology Transfer - Feb 2013

/andling *ecial Conditions and 5nternal Errors


Exce*tions - error conditions or s*ecial conditions *ecial conditions

Exce*tions generated by s*ecial instr!ctions e0g0 a TRA# instr!ction on some *rocessors Allo& a *rogram to force the *rocessor to mo(e into a *ri(ileged exec!tion mode in &hich it has access to a *ri(ileged instr!ction set e0g0

5nstr!ctions to disable external interr!*ts

Trace exce*tion - generated by a brea" *oint feat!re 3 on an architect!re ha(ing s!ch a feat!re 4 - this exce*tion is handled by the deb!gger agent

Enables soft&are brea"*oints &hen !sing a host deb!gger and ste**ing thro!gh the code An external interr!*t can be !sed to inform the core *rocessor &hen that de(ice has finished a *artic!lar *iece of &or" and is ready for additional &or" to be gi(en to it An external interr!*t can be !sed to alert6signal the core *rocessor that the external hard&are is re;!esting some ser(ice 3 e0g0 a net&or" interface de(ice has ac;!ired a *ac"et6frame that needs *rocessing 4
110

For de(ices that *erform de(ice-s*ecific o*erations in *arallel &ith the core *rocessor

First Technology Transfer - Feb 2013

#rogrammable 5nterr!*t Controllers

Many ty*es #rogrammable 5nterr!*t Controller 3#5C4 exist

All ha(e the follo&ing common characteristics

#rioritisation of m!lti*le interr!*t so!rces Ens!ring the highest *riority interr!*t is *resented to the C#$ for *rocessing %ffloading the core C#$ &ith the *rocessing needed to determine the exact so!rce of the interr!*t

A ty*ical #5C has

ome external interr!*t re;!est lines to &hich (ario!s de(ices and sensors can be attached The external so!rce6de(ice6sensor generates an interr!*t by asserting a *hysical signal on its interr!*t re;!est line

Each interr!*t re;!est line has a *riority assigned to it

5m*ortant &hen designing and im*lementing 5 Rs that allo& for nested interr!*ts

First Technology Transfer - Feb 2013

111

#rogrammable 5nterr!*t Controllers - ctd0

A ty*ical #5C has2 also

A *in that is connected to one of the micro-*rocessor1s interr!*t line %ne or more *ins that can be !sed by the micro*rocessor to set or read (al!es in the #5C registers )hen the micro*rocessor interr!*t line is enabled

The micro*rocessor obtains from the #5C the id of the interr!*t re;!est line that triggered the interr!*t $ses that id to in(o"e the corres*onding interr!*t handler by *erforming a loo"!* in the interr!*t table

Details of ho& the interr!*t entry *oint or offset are obtained are *rocessor and hard&are s*ecific

The interr!*t handler can obtain de(ice 6 sensor s*ecific information by accessing the a**ro*riate registers in the de(ice 6 sensor
112

First Technology Transfer - Feb 2013

Leneral Exce*tion Ty*es

Exce*tions can be classified as

Asynchrono!s

Mas"able - can be bloc"ed or enabled by soft&are Mon-mas"able - cannot be bloc"ed by soft&are and &ill al&ays be ac"no&ledged by the *rocessor A hard&are reset exce*tion is al&ays non-mas"able A *rocessor may also ha(e a non-mas"able interr!*t re;!est line 3MM54 #recise exce*tion - here the *rocessor1s *rogram co!nter *oints to the exact offending instr!ction that ca!sed the exce*tions 5m*recise exce*tion - the *rogram co!nter does not *oint to the *recise instr!ction that ca!sed the exce*tion - fo!nd e0g0 in architect!res that ma"e !se of hea(y *i*elining or !se *re-fetch algorithms

ynchrono!s

Kno&ing the ty*e of an exce*tion hel*s &hen im*lementing the exce*tion handler e0g0

/o& the system can reco(er from the exce*tion )hether it is at all *ossible to reco(er from the exce*tion

First Technology Transfer - Feb 2013

113

Exce*tions - ctd0

Ty*ically exce*tions are *rioritised 3 from highest to lo&est *riority 4


Asynchrono!s - non mas"able ynchrono!s - *recise ynchrono!s - im*recise Asynchrono!s - mas"able

Exce*tions ha(e *rocessing *riority o(er o*erating system ob<ects - incl!ding


Tas"s =!e!es ema*hores

First Technology Transfer - Feb 2013

118

#rinci*les of Exce*tion /andling

5n general2 &hen an exce*tion or external interr!*t is raised the *rocessor

a(es the c!rrent *rocessor state information .oads the exce*tion or interr!*t handling f!nction address into the *rogram co!nter Transfers control to the handler f!nction - &hich begins exec!tion Restores the *rocessor state information after the handler f!nction com*letes Ret!rns from the exce*tion or interr!*t and res!mes *re(io!s exec!tion

Ty*ically - an interr!*t handler

&itches to some exce*tion frame or interr!*t stac" a(es additional *rocessor state information - as a**ro*riate Mas"s the c!rrent interr!*t le(el - b!t still allo&s higher *riority interr!*ts to occ!r #erforms 3 the minimal amo!nt necessary 4 of *rocessing needed to ser(ice the interr!*t The remainder of the *rocessing is then com*leted by some other dedicated tas" r!nning in "ernel s*ace or in !ser s*ace 3details are o*erating system s*ecific4

First Technology Transfer - Feb 2013

11?

5nstallation of Exce*tion /andlers

5nstallation of Exce*tion /andlers

Re;!ires "no&ledg of the str!ct!re and location of the exce*tion and interr!*t table 3general exce*tion table4

The interrupt table is also called a vector table

An entry in the (ector table *oints to the beginning of an exce*tion ser(ice ro!tine 3E R4 or an interr!*t ser(ice ro!tine 35 R4 Ty*ically2 the start !* code for an embedded system installs the E Rs at system start!* Ty*ically2 hard&are de(ice dri(ers install the 5 Rs at dri(er initialisation time if no ex*licit handler f!nctions are s*ecified for certain exce*tions or interr!*ts the RT% may install defa!lt handler f!nctions 3to ens!re *ro*er rece*tion and ret!rn from exce*tions4 ome RT% es *ro(ide mechanisms (ia &hich an embedded systems de(elo*er can o(er&rite the defa!lt handler f!nction &ith one of their o&n2 or

5nsert f!rther *rocessing in addition to the defa!lt *rocessing

First Technology Transfer - Feb 2013

11B

5nterr!*ts - a(ing tate 5nformation

a(ing *rocessor state information d!ring exce*tion or interr!*t handling


The details are hard&are and o*erating system s*ecific and Ty*ically in(ol(e some "ind of stac"

)hen an interr!*t occ!rs the *rocessor 3ty*ically4 sa(es2 at a minim!m2 the stat!s register and the *rogram co!nter The a "ernel de(elo*er and interr!*t handler de(elo*er needs to decide &hat f!rther information needs to be sa(ed - so that *rogram exec!tion can res!me *ro*erly after the exce*tion 5n a ty*ical embedded o*erating system2 &hen a tas" is created a tas" control bloc" is created and a bloc" of memory reser(ed for stac" !se

The stac" *ointer 3 #4 for a gi(en tas" *oints to the to* of the stac" data in the stac" memory area for that tas" )hene(er a context s&itch occ!rs the acti(e stac" *ointer is reinitialised to the # for the acti(e tas"

)hen an exce*tion or interr!*t occ!rs the *rocessor !ses &hiche(er stac" the # for the c!rrently acti(e is *ointing to store its minim!m state information
11C

First Technology Transfer - Feb 2013

Mested Exce*tions

)here a higher *riority interr!*t ser(ice ro!tine can interr!*t a r!nning lo&er *riority ser(ice ro!tine iss!es that need to be considered incl!de

Considering if the a**lication stac" large eno!gh to accommodate the maxim!m ex*ected n!mber of nested interr!*ts > Thin"ing abo!t ho& a stac" o(erflo& exce*tion arising d!ring exce*tion handling to be dealt &ith >

5f stac" o(erflo& is not detected 3 e0g0 beca!se there is no bo!nds chec"ing on the stac" 4 - data residing beyond the bo!nds of the stac" may be o(er&ritten

)hat if this is Tas" Control -loc" 3 TC- 4 data > These "inds of error may be s*oradic and diffic!lt to re*rod!ce Consider ha(ing an E R or 5 R !se its o&n stac" !ch as stac" is called an exception frame

First Technology Transfer - Feb 2013

11G

Exce*tion /andler 5ss!es

Exce*tion handlers are commonly &ritten !sing a mixt!re of assembler and a high le(el *rogramming lang!age s!ch as C or CII An exce*tion handler2 ty*ically2 is made !* of t&o *arts

The first *art r!ns in the exce*tion or interr!*t context The second *art r!ns in a tas" context

A common strategy &hen im*lementing E Rs or 5 Rs is for the E R or 5 R to allocate a bloc" of memory for its o&n *ri(ate stac" 3either statically or dynamically4 before it installs itself into the system

The exce*tion handler then sa(es the c!rrent stac" *ointer into some tem*orary memory location and reinitialises the stac" *ointer to *oint to its *ri(ate stac" and then begins *rocessing #rior to ret!rning the exce*tion handler resets the stac" *ointer to the *re(io!sly sa(ed (al!e

First Technology Transfer - Feb 2013

11J

Mas"ing 5nterr!*ts and 5 Rs

The three main &ays of mas"ing interr!*ts are

Disable a de(ice so that it cannot assert additional interr!*ts


5nterr!*ts at all le(els 3from other de(ices4 can still occ!r Mas" interr!*ts at e;!al or lo&er *riority le(els /igher *riority interr!*ts can still occ!r

The de(ice can contin!e to generate interr!*ts - b!t they are ignored by the *rocessor

Disable the global system-&ide interr!*t re;!est line to the *rocessor

Mo interr!*ts 3 &hate(er their *riority le(el 4 reach the *rocessor

E;!i(alent to mas"ing interr!*ts at the highest *riority le(el

5 R &ants to red!ce the total n!mber of interr!*ts raised by the de(ice 5 R is non-reentrant 5 R needs to carry o!t some atomic o*erations The abo(e methods are !sed by 5 Rs for one or more of the follo&ing reasons )here an architect!re !ses an interr!*t mas" register 3 5MR 4 - this &ill need to be sa(ed by the 5 R - &hich &ill set the bits of the 5MR to &hat it needs2 and then the sa(ed (al!es &ill be restored &hen the 5 R ret!rns0
120

First Technology Transfer - Feb 2013

Timing Exce*tion #rocessing

/ard&are designer needs to !se the a**ro*riate #5C *riority le(el #rogrammer 3 of the 5 R 4 needs to !nderstand the timing re;!irements of each de(ice &hen the 5 R is r!nning

)ith interr!*ts disabled )ith e;!al or lo&er *riority interr!*ts disabled )ith all interr!*ts disabled

)hen interr!*ts are disabled tho!ght needs to be gi(en to interr!*t miss sit!ations

5m*ortant iss!e for de(ices !sing edge-triggering as a mechanism for asserting an interr!*t

RT% "ernel sched!ler cannot r!n &hen a r!nning 5 R disables all system interr!*ts

May therefore effect the time deadlines of other tas"s

First Technology Transfer - Feb 2013

121

Exce*tion Timing 5ss!es

)hen analysing exce*tion timing iss!es the follo&ing conce*ts 3 terms 4 are often !sed

Time inter(al bet&een interr!*ts 3 de*ends on interr!*t fre;!ency 4 5nterr!*t latency - the time inter(al bet&een the time &hen the interr!*t is raised and the time &hen the 5 R begins to exec!te de*ends on

Time ta"en by the *rocessor to ac"no&ledge the interr!*t and carry o!t initial ho!se"ee*ing &or" )hether a higher *riority interr!*t is acti(e at the time )hether the interr!*t is disabled and the later re-enabled by soft&are

5nterr!*t *rocessing time e;!ation 9 Response Time < Interr pt 1atency = Interr pt >rocessin' Time

First Technology Transfer - Feb 2013

122

T&o tage 5nterr!*t /andling

5nterr!*t #rocessing may be s*lit bet&een

5nterr!*t context &or" - this *art of the 5 R


er(ices the de(ice - ac"no&ledges the re;!est and #!ts the de(ice into a "no&n o*erational state in &hich it can res!me o*eration

Tas" context &or" - deals &ith the remainder of the *rocessing of the interr!*t e0g0 *arsing an in*!t frame header3s4

Tas" context &or" may be im*lemented as some "ind of daemon

#ossible ad(antages of s*litting interr!*t handling


.o&er *riority interr!*ts can be handled less !rgently than more critical tas"s There is less chance of missing interr!*ts Conc!rrency is im*ro(ed beca!se minimal ser(icing of de(ices means they can contin!e o*erations &hile *re(io!s re;!ests are ;!e!ed !* for *rocessing &hen the demands on the system are less 5nterr!*t res*onse time increases - beca!se of sched!ling delays and the *ossibility that the daemon tas" may need to yield to other higher *riority tas"s

Conse;!ences of s*litting interr!*t *rocessing

First Technology Transfer - Feb 2013

123

*!rio!s 5nterr!*ts

A s*!rio!s interr!*t is

A signal of short d!ration on one of the interr!*t lines

#robably ca!sed by some "ind of signal :glitch: The *ossibility of s*!rio!s interr!*ts occ!rring needs to be considered caref!lly &hen &or"ing &ith de(ices that !se le(el or edge triggering to assert an interr!*t Dealing &ith s*!rio!s interr!*ts often in(ol(es !se of techni;!es s!ch as e0g0

Debo!ncing Filtering

First Technology Transfer - Feb 2013

128

Timers and Timer er(ices

Timers and Timer er(ices are (ital in the sched!ling of f!t!re e(ents &itho!t them o*erating system sched!lers co!ld not be im*lemented0 $ses of timers incl!de 9

Ro!nd robin sched!ling ched!ling data retransmission and *rotocol reco(ery in comm!nications *rotocols Collection of system timing and *erformance information /ard timers - deri(ed from *hysical timer circ!itry that directly interr!*ts the *rocessor &hen the timer ex*ires

Time sensiti(e acti(ities in an embedded system may be dri(en by

$sed &here timing *recision and latency needs to be (ery *redictable Em*hasis is on efficient sched!ling of soft&are e(ents that do not re;!ire high timing *recision
12?

oft timers - soft&are e(ents sched!led (ia soft&are

First Technology Transfer - Feb 2013

Ty*es of Timer

Ty*es of time incl!de - Real Time Cloc"s2 ystem Cloc"s and 5nter(al Timers

Real Time Cloc"


Trac"s time2 date2 month2 year Commonly integrated &ith battery-*o&ered DRAM 5nde*endent of C#$ and *rogrammable inter(al timer Real time can be maintained bet&een system *o&er cycles

ystem Cloc"

#erforms essentially the same <ob as a Real Time Cloc" Can trac" ela*sed time since system *o&er !* 5nitial (al!e ty*ically retrie(ed from real time cloc" at *o&er !*2 or2 set by the !ser Dri(en by the *rogrammable inter(al timer
12B

First Technology Transfer - Feb 2013

#rogrammable 5nter(al Timer 3#5T4

#rogrammable 5nter(al Timer 3#5T4 Dri(en by a fixed fre;!ency in*!t cloc" so!rce Contains a set of *rogrammable timer control registers Timer interr!*t rate is the n!mber of timer interr!*ts generated *er second et by setting a (al!e s*ecifying the a**ro*riate scaling factor to be a**lied to the timer in*!t cloc" *!lses Timer co!ntdo&n (al!e Determines &hen next timer interr!*t occ!rs .oaded into the rele(ant control register Decremented e(ery :scaled: cloc" cycle Timer generates an interr!*t &hen this (al!e reaches 'ero De*ending on the ty*e of cloc" there may be other registers that determine e0g0 )hether *eriodic timer interr!*ts are generated )hether the co!ntdo&n (al!e sho!ld be a!tomatically reloaded for the next timer interr!*t
12C

First Technology Transfer - Feb 2013

Timer hard&are initialisation

Mormally *erformed as *art of system start!*

Reset and bring timer hard&are to a "no&n initial state .oad correct (al!e into timer control register that sets the timer interr!*t fre;!ency 5nitialise other timer control registers to a**ro*riate (al!es 5nstall timer interr!*t ser(ice ro!tine Enable timer interr!*t

First Technology Transfer - Feb 2013

12G

Timer 5nterr!*t er(ice Ro!tine

A ty*ical timer 5 R

$*dates the system cloc" Calls the registered "ernel f!nction to notify the *assage of a *re*rogrammed *eriod of time Ac"no&ledges interr!*t - reinitialises rele(ant timer control registers Ret!rns from the interr!*t

First Technology Transfer - Feb 2013

12J

oft Timer /andling


#attern for 5m*lementing a oft-Timer /andling Facility A soft-timer handling facility sho!ld

#ermit an a**lication to start a timer #ermit an a**lication to sto* or cancel a *re(io!sly installed timer Ta"e care of maintaining the collection of a**lication timers #rocessing carried o!t &ithin the timer 5 R itself #rocessing carried o!t &ithin a tas" context

oft timer *rocessing in(ol(es


Ty*ically the time resol!tion re;!ired by the soft timer facility is m!ch less than the time inter(al bet&een s!ccessi(e timer interr!*t e(ents e0g0

Timer interr!*t e(ents might be generated e(ery 10 msecs and the time resol!tion for the soft timer facility may be 100 msec

A common strategy is to !se some "ind of co!nter in the timer 5 R that is decremented on e(ery timer interr!*t e(ent and !nbloc"s a soft timer facility &or"er tas" &hen it co!nts do&n to 'ero

First Technology Transfer - Feb 2013

130

oft Timer /andling - ctd0

The soft&are timer facility maintains a table of co!nt do&n (al!es 3 corres*onding to a m!lti*le of the soft timer time inter(al e0g0 100 msec 4 and associated a**lication timeo!t f!nctions to be called &hen the co!nt do&n (al!e reaches 'ero0 The &or"er tas" tra(erses this table and for each entry

Decrements the co!nt do&n (al!e )hen the co!nt do&n (al!e reaches 'ero in(o"es the associated a**lication timeo!t f!nction

)here a large n!mber of a**lication timeo!t f!nctions is in(ol(ed a linear collection data str!ct!re s!ch as a table or lin"ed list is not the most efficient - as entries are not ordered by co!ntdo&n (al!e0 Delays to the act!al r!nning of the &or"er tas"

Time to com*lete the timer 5 R Time ta"en to sched!le the &or"er tas" Time before the &or"er tas" act!ally r!ns - it may2 for exam*le2 be delayed from r!nning by the exec!tion of some other high *riority tas"

First Technology Transfer - Feb 2013

131

Timing )heel #attern

Re;!irements for efficient insertion2 deletion2 cancellation and !*date of soft timers2 are2 to some extent m!t!ally conflicting 000 )here the n!mber of a**lication tas"s is large then linear tra(ersal of an array or a do!bly lin"ed list 3 do!bly lin"ed beca!se insertions are more efficient in do!bly lin"ed lists 4 can be time 3 and C#$ cycle 4 cons!ming0 %ne im*lementation o*timisation strategy is the :Timing )heel:0 The timing &heel

5s a circ!lar b!ffer Each slot re*resents a !nit of time 3 &ith res*ect to the *recision of the soft&are timer 4 e0g0 if this (al!e is 100 msec then each slot re*resents the *assing of 100 msec0 A cloc" dial *ointer *oints to the slot corres*onding to the c!rrent time lots f!rther along re*resent the f!t!re For e(ery :soft timer tic": the cloc" dial *ointer mo(es along to the next time slot Each slot *oints to a do!bly lin"ed list of timeo!t e(ent handlers 3also called callbac" f!nctions 3 callbac"s for short 44

5t is a list of e(ents &ith the same ex*iration time


132

First Technology Transfer - Feb 2013

Timing )heel 5m*lementation

First Technology Transfer - Feb 2013

133

Timing )heel 5ss!es

5ss!es )ith The Timing )heel A**roach

Finite si'e of timing &heel 3circ!lar4 b!ffer

e0g0 if time slots are at 100 msec inter(als and the circ!lar b!ffer contains 10 slots then a**lications can only be sched!led for !* to 1000 msec ahead #ossible sol!tion is to !se a tem*orary b!ffer for :o(erflo& condition: e(ents and to ma"e them sched!lable &hen the cloc" dial has :gone ro!nd: the a**ro*riate n!mber of times $se a hierarchical timing &heel e0g0

A &heel in !nits of 100 msec A &heel in !nits of seconds A &heel in !nits of min!tes

Determining 6 setting bo!nds on soft-time handler in(ocation Details are im*lementation and a**lication design s*ecific

This is a :diffic!lt: *roblem %ne a**roach is to !se modeling and sim!lation techni;!es 3e0g0 based on timed #etri Mets or Colo!red #etri Mets4
138

First Technology Transfer - Feb 2013

Real Time 56%

From the *rogramming *ers*ecti(e 5n*!t-%!t*!t 3 56% 4 %*erations in Real Time and Embedded ystems im*ly

Comm!nicating &ith the de(ice #rogramming the de(ice to initiate an 56% re;!est #erforming transfer of data bet&een the de(ice and the system #ro(iding notification &hen the o*eration com*letes Kno&ledge of hard&are details of the de(ice - register definitions and access methods -eing able to locate the correct de(ice &hen there are m!lti*le instances of it on the system Details of ho& the de(ice is integrated &ith the rest of the system Kno&ing ho& to handle errors that can occ!r d!ring 56% o*erations

This re;!ires

First Technology Transfer - Feb 2013

13?

Real Time 56%

From the RT% *ers*ecti(e 56% o*erations im*ly


.ocating the correct de(ice for the 56% re;!est .ocating the correct de(ice dri(er for that de(ice 5ss!ing the a**ro*riate re;!est to the de(ice dri(er The RT% may ha(e to *ro(ide an abstraction that hide the de(ice dri(er characteristics and s*ecific details from a**lication de(elo*ers

5deally2 an a**lication de(elo*er &ants a sim*le and !niform &ay to comm!nicate &ith all the different "inds of de(ices *resent in the system

First Technology Transfer - Feb 2013

13B

-asic #rinci*les of 56%

56% s!bsystems are im*lemented on the basis of a layered model The 56% s!bsystem hides de(ice s*ecific information from the "ernel and from !ser a**lications

#ro(ides a !niform access method to the *eri*heral 56% de(ices of the system 5nteracts &ith the de(ice dri(ers &hich in t!rn Deals &ith hard&are and interr!*t handler details

De(ices may be

#ort ma**ed - de(ice address s*ace is se*arate from memory address s*ace Memory ma**ed - de(ice address s*ace is *art of the system memory address s*ace 5f direct memory access 3DMA4 is not a(ailable then data transfer bet&een the de(ice and the system in(ol(es

Transfer of data from the de(ice register to the *rocessor register and then Trom the *rocessor register to memory

A DMA controller *ermits direct transfer of data from the de(ice to memory 3 and (ice (ersa 4 &itho!t !sing the *rocessor
13C

First Technology Transfer - Feb 2013

Character-Mode (s0 -loc"-Mode De(ices

5n character-mode de(ices data is transferred a byte at a time


Ty*ically in a serial fashion Mormally !sed for sim*le de(ices s!ch as "ey*ads or R 232 lin"s Dri(ers may b!ffer the data if transfer rate from system to de(ice is faster than the de(ice can handle

5n bloc"-mode de(ices data is transferred a bloc" at a time 3ty*ical bloc" si'es are ?12 bytes or 1028 bytes4

)here the amo!nt of data to be transferred is not s!fficient to fill a bloc"


The bloc" may be *added o!t to the a**ro*riate si'e Alternati(ely the dri(er may cache a n!mber of smaller &rites to fill !* the bloc"

First Technology Transfer - Feb 2013

13G

Ty*ical 56% !bsystem 5m*lementation #attern

56% s!bsystem defines the A#5 set


De(ice dri(er im*lements each f!nction in the set De(ice dri(er ex*orts this set of f!nctions to the 56% s!bsystem De(ice dri(er

Does the &or" needed to set !* the de(ice for !se ets !* the association bet&een the 56% s!bsystem A#5 and the corres*onding de(ice-s*ecific 56% calls

A ty*ical standard set of 56% f!nctions is

create - create a (irt!al instance of an 56% de(ice destroy - delete a (irt!al instance of an 56% de(ice open - *re*are an 56% de(ice for !se close - indicate to a de(ice that its ser(ices are no longer re;!ired - !s!ally this initiates a set of de(ice s*ecific clean!* o*erations read - read data from the 56% de(ice write - &rite data to the 56% de(ice ioctl - iss!e control commands to the 56% de(ice
13J

First Technology Transfer - Feb 2013

!bsystem A#5

A common strategy for ma**ing generic 56% s!bsystem f!nctions to dri(er f!nctions &hen im*lementing dri(er code in C is to

Define a data str!ct!re &hich is a collection of f!nction *ointers e0g0 typede" str ct * int (?Create)(#oid)+ int (?Open)(#oid)+ int (?Read)(#oid)+ int(?3rite)(#oid)+ int (?Close)(#oid)+ int(?Ioctl)(#oid)+ int(?/estroy)(#oid)+ 0 IO$/R@$I;T7R2(C7+

Then2 a (ariable of this ty*e can be defined and initialised so that the (ario!s f!nction *ointers *oint to the act!al de(ice s*ecific f!nctions0

First Technology Transfer - Feb 2013

180

De(ice Dri(er Table

Ty*ically the 56% s!bsystem &ill contain a dri(er table - an array of str!ct!res 3 records 4 of the form typede" str ct * int de#ice$id+ char de#ice$nameA%9B+ IO$/R@$I;T7R2(C7 ? dri#er$methods+ #oid ? instance$speci,c$data+ 0 dri#er$ta&le$record +

First Technology Transfer - Feb 2013

181

Memory Management

Ty*ically an embedded system RT% &ill *ro(ide some memory management ser(ices - !s!ally (ia system calls s!ch as malloc() and free() A *roblem &ith a**lications that ma"e fre;!ent calls to malloc() and free() is memory fragmentation Embedded a**lication de(elo*ers &ill often im*lement c!stom memory management facilities on to* of these basic ser(ices0 5n its most basic form2 dynamic memory allocation ta"es *lace from a contig!o!s bloc" of memory called the hea* A memory management facility maintains information abo!t the hea* in a reser(ed 3control bloc"4 area of memory &hich incl!des things s!ch as

tarting address of the memory bloc" Total si'e of the memory bloc" Allocation table &hich trac"s Areas of memory in !se Area of memory that are free i'e of each free area of memory
182

First Technology Transfer - Feb 2013

Memory Management - ctd0

Memory is normally allocated in m!lti*les of some fixed bloc" si'e e0g0 32 bytes )hen a re;!est for memory is made the smallest n!mber of contig!o!s bloc"s that can satisfy that re;!est is allocated0

A bit-string can be !sed to efficiently trac" &hich bloc"s of memory ha(e been allocated and &hich are free Each bit *osition corres*onds to a corres*onding bloc" *osition 5f the bit at that *osition is 0 then the bloc" is free 5f the bit at that *osition is 1 then the bloc" is ta"en 3 i0e0 has been allocated 4

A *ossible techni;!e for handling memory fragmentation is to !se some form of memory com*action to combine small free bloc"s into one larger bloc" of contig!o!s memory - its disad(antages incl!de

Meed for bloc" co*ying of data 5nability of an a**lication to access data &hilst it is being bloc" co*ied Re;!ires that tas"s &hich o&n the bloc"s access them !sing (irt!al addressing

Memory management needs to ta"e architect!re-s*ecific memory alignment re;!irements into acco!nt 3 e0g0 m!lti-byte data items s!ch as long integers may need to be aligned on an address that is a m!lti*le of 8 4
183

First Technology Transfer - Feb 2013

Memory Manager - Re;!irements

Desirable #ro*erties of an Efficient Memory Manager

Ability to ra*idly determine if there is a(ailable a large eno!gh bloc" to satisfy the memory re;!est - *art of the malloc o*eration Ability to ra*idly !*date internal control bloc" memory management information - *art of both the malloc and free o*erations Ability to ra*idly determine if a ne&ly freed bloc" can be combined &ith its neighbo!ring free bloc"s to form a larger contig!o!s free bloc" - *art of the free o*eration

First Technology Transfer - Feb 2013

188

-asic Malloc and Free

A commonly !sed sim*le a**roach to the im*lementation of malloc and free is to $se a fixed si'e static allocation array to im*lement the allocation ma* and A hea* to ra*idly locate the largest a(ailable free bloc"

Also im*lemented as a fixed si'e static array

Allocation ma*

The n!mber of entries in the array is e;!al to the n!mber of basic memory bloc"s 3 e0g0 if a basic memory bloc" &as 32 bytes and the amo!nt of a(ailable memory &as 1 M- then the array &o!ld ha(e 322CBG entries The encoding scheme !sed is as follo&s 9

To indicate a range of contig!o!s free bloc"s a *ositi(e n!mber 3e;!al to the n!mber of contig!o!s free bloc"s4 is *laced in the first and last entry re*resenting the range of free bloc"s To indicate a range of allocated bloc"s a negati(e n!mber 3the n!mber of bloc"s in the range times -1 4 is *laces in the first entry re*resenting the range2 and a 'ero is *laced in the last entry re*resenting the range The starting address of a bloc" of bytes can be com*!ted !sing the form!la startin'$address < o""set = nit$siCe ? inde!$in$allocation$map

First Technology Transfer - Feb 2013

18?

A /ea*

A hea* is2 logically2 a binary tree in &hich the ordering r!le is that the (al!e of the "ey in the *arent node is :greater than or e;!al to: the (al!e in the child nodes

A conse;!ence of this ordering *ro*erty is that a :hea*: binary tree can be im*lemented as an array Each node in the :hea*: binary tree array is a data str!ct!re 3record4 that contains

The si'e of the free bloc" re*resented by that node The starting index of that bloc" in the allocation array

malloc al&ays car(es o!t memory to allocate o!t of the largest a(ailable free bloc"

First Technology Transfer - Feb 2013

18B

Malloc Algorithm - %!tline

Examine the hea* to see if a free bloc" large eno!gh for the n!mber of bytes as"ed for in the allocation re;!est exists Ret!rn an error indication to the caller e0g0 a n!ll *ointer (al!e4 if there is no s!ch bloc" Fetch the starting allocation-array index of the free range from the to* of the hea* $*date the allocation array by mar"ing the ne&ly allocated bloc" 5f the entire bloc" is !sed to satisfy the allocation then !*date the hea* by deleting the largest node 5f *art of the bloc" is to be !sed then !*date the (al!es for the node str!ct!re at the to* of the hea* and rearrange the hea* 3hea*ify4 so that the c!rrently 3after allocation4 largest free bloc" is at the to* of the hea*
18C

First Technology Transfer - Feb 2013

Fixed i'e Memory Management

)here the range of si'es of memory bloc" to be allocated does not (ary &idely and it is "no&n that memory allocation can be satisfied by allocating one of n!mber of fixed si'ed memory bloc"s 3 e0g0 32 bytes2 B8 bytes2 12G bytes 4 then

Free memory bloc"s of a gi(en si'e can be maintained as a lin"ed list of free nodes Each list has an associated control str!ct!re 3handle4 that trac"s e0g0 the n!mber of nodes on the free list 5t a(oids memory fragmentation 5t can be more deterministic as com*ared to the hea* - &here the time ta"en by the :hea*ifying: o*eration &ill de*end on the act!al str!ct!re of the hea* binary tree Free memory bloc"s are ta"en from and added to the front of the free list - a constant time o*eration
18G

Ad(antages of this a**roach


First Technology Transfer - Feb 2013

-loc"ing (s0 Mon-bloc"ing Memory Allocation

5n many embedded real time a**lications in &hich there is limited memory and m!lti*le tas"s are com*eting for that memory it may be that a tem*orary :memory exha!stion: may arise0 To co*e &ith s!ch sit!ations a good memory allocation design sho!ld allo& for

Memory allocation &ith indefinite bloc"ing Memory allocation &ith bloc"ing for some timeo!t *eriod Memory allocation &ith no bloc"ing

%ne &ay of realising s!ch a design is to im*lement a bloc"ing memory allocation f!nction (ia !se of a m!tex loc" and a co!nting sema*hore

As o!tlined in the follo&ing diagram 9


18J

First Technology Transfer - Feb 2013

-loc"ing Memory Allocation

First Technology Transfer - Feb 2013

1?0

-loc"ing Memory Allocation - Ex*lained

Co!nting sema*hore initialised to total n!mber of a(ailable memory bloc"s &hen memory *ool is created Memory bloc"s are freed and allocated from the head of the lin"ed list The m!tex loc" is !sed to g!arantee excl!si(e tas" access to both the freebloc"s list and to the control str!ct!re For an allocation re;!est

Tas" m!st first ac;!ire the co!nting sema*hore 5f no bloc"s are a(ailable the tas" bloc"s on the co!nting sema*hore Tas" m!st next ac;!ire the m!tex loc" 5f another tas" is in the middle of ac;!iring a bloc" then this tas" bloc"s )hen the m!tex loc" is ac;!ired the tas" retrie(es the bloc" from the free-bloc"s list

A tas" releases the co!nting sema*hore &hen it has finished &ith the memory bloc"

First Technology Transfer - Feb 2013

1?1

Memory Allocation - Deallocation

#se!do code for memory allocation and memory deallocation 9 /? Memory (llocation ?/ (c- ire ( co ntin'$semaphore ) 1oc) ( m te! ) Retrie#e memory &loc) "rom pool 8nloc) ( m te! ) /? Memory /eallocation ?/ 1oc) ( m te! ) Release memory &loc) &ac) into the pool 8nloc) ( m te! ) Release ( co ntin'$semaphore )

First Technology Transfer - Feb 2013

1?2

ynchronisation - #atterns and trategies

The t&o main categories of synchronisation are

Reso!rce synchronisation

Concerned &ith safe access to some shared reso!rce3s4 Ma"es !se of synchronistion *rimiti(es s!ch as m!texes and sema*hores in the im*lementation of m!t!al excl!sion algorithms Concerned &ith sit!ations in m!lti-threaded 6 m!lti-tas"ing a**lications &here the collection of co-o*erating tas"s needs to reach a certain state before they can *roceed A tas" in the collection &ill bloc" till all the tas"s ha(e reached the re;!ired state Tas" *osts its arri(al at a barrier Tas" &aits for other *artici*ating tas"s to reach that barrier Tas" recei(es notification to *roceed beyond the barrier

Acti(ity synchronisation

-arrier synchronisation

First Technology Transfer - Feb 2013

1?3

ynchronisation - #atterns and trategies - ctd0

Rende'(o!s synchronisation

5n(ol(es !ses of synchronisation and comm!nication *oint 3called an entry4


%ne tas" defines an entry and ma"es it *!blic %ther tas" calls the entry 3 as an ordinary f!nction call 4 The iss!er of the entry call is bloc"ed if the call cannot be acce*ted The tas" defining the entry

Acce*ts the call Exec!tes it Ret!rns the res!lts to the caller

The iss!er of the call establishes a rende'(o!s &ith the tas" defined in the entry Mote9 5n the rende'(o!s bi-directional mo(ement of data is *ossible

Arg!ments *assed into the entry call Res!lts ret!rned from the entry call

A rende'(o!s that does not in(ol(e data *assing 3a sim*le rende'(o!s4 can be im*lemented bet&een t&o tas"s by !sing t&o binary sema*hores
1?8

First Technology Transfer - Feb 2013

im*le Rende'(o!s

First Technology Transfer - Feb 2013

1??

-arrier ynchronisation

#se!do code ill!strating a &ay to im*lement barrier synchronisation typede" str ct * m te!$type condition$#ar$type int int 0 &arrier$type+ &arrier$loc)+ &arrier$condition+ &arrier$co nt+ n m&er$o"$threads+

&arrier$call( &arrier$type ? &arr ) * loc)$m te!(D(&arr-E&arrier$loc)))+ &arr-E&arrier$co nt==+ i"(&arr-E&arrier$co nt F &arr-En m&er$o"$threads) condition$wait(D(&arr-E&arrier$condition),D(&arr-E&arrier$loc)))+ else * &arr-E&arrier$co nt < G+ condition$&roadcast(D(&arr-E&arrier$condition))+ 0 nloc)$m te!(D(&arr-E&arrier$loc)))+ 0
First Technology Transfer - Feb 2013 1?B

Comm!nication #atterns

%ne &ay of classifying comm!nication is into ignal centric All necessary information is con(eyed in the e(ent signal itself Data centric 5nformation is carried in the data transferred A combination of signal centric and data centric Another &ay of classifying comm!nication is into .oosely co!*led comm!nication Data *rod!cer does not re;!ire a res*onse from the data cons!mer e0g0 An 5 R *osting messages on a message ;!e!e Tightly co!*led comm!nication 5n(ol(es bidirectional transfer of data Data *rod!cer &aits synchrono!sly for a res*onse to its data transfer before contin!ing exec!tion2 or Res*onse is ret!rned asynchrono!sly &hile the *rod!cer contin!es *rocessing e0g0 tas" A &rites messages to a message ;!e!e read by tas" tas" - &rites messages to a 3different4 message ;!e!e read by tas" A
1?C

First Technology Transfer - Feb 2013

Critical ection Design 5ss!es

A critical section in a tas" is a fragment of code that accesses a shared reso!rce0 A com*eting critical section is a fragment of code in another tas" that accesses the same shared reso!rce Critical sections need to be g!arded by a s!itable m!t!al excl!sion mechanism to ens!re that each tas" has excl!si(e !se to the shared reso!rce &hen it needs it 3e0g0 &hen &riting to a shared area of memory4 )here critical time deadlines ha(e to be met the si'e and com*lexity of critical section code &ill be im*ortant 5deally a m!t!al excl!sion mechanism sho!ld

L!arantee that only one tas" can enter its critical section at any gi(en time Ens!re that m!lti*le com*eting tas"s are granted fair access to the shared reso!rce Ens!re that a tas" exec!ting in its critical section does not *re(ent another tas" from exec!ting in a non-com*eting critical section
1?G

First Technology Transfer - Feb 2013

Common Acti(ity ynchronisation Design #atterns

For any gi(en RT% or Embedded % yo! sho!ld be able to im*lement 3&here the *rimiti(es are a(ailable 2 or2 if necessary im*lement some *rimiti(es in terms of other *rimiti(es4 the follo&ing design *atterns0

For each im*lementation the beha(io!ral im*lications of ha(ing the tas"s at different *riorities needs to be ta"en into acco!nt0

Mo0 10 ynchronising t&o tas"s !sing a single binary sema*hore

The initial (al!e of the sema*hore is 0 Tas" - !ses the ac;!ire o*eration on the shared sema*hore Tas" A !ses the release o*eration on the shared sema*hore

Mo0 20 ynchronising an 5 R &ith a tas" !sing a single binary sema*hore

The initial (al!e of the sema*hore is 0 The tas" !ses the ac;!ire o*eration on the shared sema*hore The 5 R !ses the release o*eration on the shared sema*hore

Mos0 3 and 8 - (ariants of 1 and 2 b!t !sing e(ent registers instead of the binary sema*hore

First Technology Transfer - Feb 2013

1?J

Common Acti(ity ynchronisation Design #atterns

Mo0 ?0 ynchronising an 5 R &ith a tas" !sing a co!nting sema*hore


imilar to 20 b!t !sing a co!nting sema*hore Combines the acc!m!lation of e(ent occ!rrences &ith e(ent signalling The tas" can r!n as long as the co!nting sema*hore is non 'ero 5n(ol(es t&o tas"s 3 tas" A and tas" - 4 and t&o message ;!e!es 3 message ;!e!e A and message ;!e!e - 4 Each message ;!e!e can hold at most one message 3 s!ch str!ct!res are also called mailboxes in some o*erating systems 4 -oth message ;!e!es are initially em*ty )hen tas" A reaches the rende'(o!s it *!ts a message into message ;!e!e and &aits for a message to arri(e on message ;!e!e A )hen tas" - reaches the rende'(o!s it *!ts data into message ;!e!e A and &aits for data to arri(e on message ;!e!e Tas" A generates a signal to tas" Tas" - di(erts from its normal exec!tion *ath and exec!tes its asynchrono!s signal handler ro!tine
1B0

Mo0 B0 im*le Rende'(o!s &ith Data #assing

Mo0 C0 Asynchrono!s e(ent notification !sing signals


First Technology Transfer - Feb 2013

Common Reso!rce ynchronisation Design #atterns

Mo0 10 Accessing shared memory (ia m!texes

Tas" A and tas" - share a common m!tex and a common memory area Each tas" m!st first ac;!ire the m!tex before it can access the shared memory Each tas" m!st release the m!tex &hen it has finished accessing the shared memory This *attern in(ol(es an interr!*t ser(ice ro!tine 35 R42 a tas" and an interr!*t loc" An interr!*t loc" 3s!**orted by some *rocessor architect!res4 is !sed to disable an interr!*t and bloc" all other interr!*ts at or belo& that le(el The tas" m!st ac;!ire the interr!*t loc" before accessing the shared memory and release it after&ards This is in order to *re(ent the 5 R disr!*ting its access to the shared memory The 5 R does not need to be a&are of the interr!*t loc"
1B1

Mo0 20 Accessing shared memory &ith interr!*t loc"s

First Technology Transfer - Feb 2013

Common Reso!rce ynchronisation Design #atterns

Mo0 30 Accessing shared memory &ith *reem*tion loc"s

This *attern in(ol(es t&o tas"s a *reem*tion loc" and shared memory #reem*tion loc"ing in(ol(es disabling the "ernel sched!ler so that it &ill not *reem*t the tas" that has ta"en o!t the *reem*tion loc" Each tas" is res*onsible for disabling *reem*tion before it accesses The shared memory and for re-enabling *reem*tion &hen it has finished accessing the shared memory $nli"e the sit!ation &ith binary sema*hores and m!texes no &aiting is in(ol(ed

First Technology Transfer - Feb 2013

1B2

Common Reso!rce ynchronisation Design #atterns

Mo0 80 haring M!lti*le Reso!rce 5nstances (ia Co!nting ema*hores and M!texes

5n this *attern there are M tas"s sharing M reso!rces2 one co!nting sema*hore and one m!tex e0g0

M s*oolers sharing M *rinters

The co!nting sema*hore is initialised to the maxim!m n!mber of a(ailable reso!rces A tas" m!st ac;!ire the co!nting sema*hore before attem*ting to access a reso!rce A m!tex is !sed to *ro(ide a tas" &ith excl!si(e access to the shared reso!rce control str!ct!re 3 &hich e0g0 trac"s information abo!t &hich reso!rces are c!rrently in !se and &hich are a(ailable 4 A tas" m!st ac;!ire this m!tex before

Allocating a reso!rce instance Freeing a reso!rce instance


1B3

First Technology Transfer - Feb 2013

Data Transfer )ith Flo& Control

The aim of this *attern if for a cons!mer tas" to control the flo& of data from the *rod!cer0

5t in(ol(es a *rod!cer tas"2 a cons!mer tas"2 a co!nting sema*hore2 a data b!ffer For the *rod!cer to be able to &rite to the b!ffer it m!st ac;!ire the co!nting sema*hore

The *rod!cer &ill bloc" &hen the (al!e of the co!nting sema*hore is 0

The cons!mer is able to release the co!nting sema*hore 3 increase its co!nt (al!e 4 5nitially the co!nting sema*hore is set to some *ermissible to"en (al!e 3 less than the maxim!m allo&able to"en (al!e 4 The cons!mer is able to control the flo& rate by increasing the (al!e of the co!nting sema*hore a**ro*riately in relation to its ability to cons!me data0
1B8

First Technology Transfer - Feb 2013

Asynch Data - M!lti*le o!rces

/andling the Asynchrono!s Rece*tion of Data from M!lti*le Data Comm!nication Channels

The *attern here in(ol(es M!lti*le 5 Rs2 a sema*hore2 an interr!*t loc" and a daemon tas" Each 5 R inserts its data into a corres*onding message ;!e!e and *erforms a release o*eration on the sema*hore

The daemon tas"


-loc"s and &aits on the sema*hore 3 ac;!ire o*eration 4 Ta"es o!t an interr!*t loc" 3 this loc" needs to *rotect against the (ario!s m!lti*le interr!*t so!rces 4 #rocesses the a(ailable data

First Technology Transfer - Feb 2013

1B?

Asynch Data - M!lti*le o!rces

#se!do code sni**et 9 while( ac- ire(4inary$semaphore)) disa&le(interr pts) "or each messa'e$- e e 'et ms'$- e e$len'th "or (ms'$- e e$len'th) retrie#e messa'e ena&le (interr pts) process messa'e disa&le (interr pts ) end "or end "or ena&le (interr pts) end while

First Technology Transfer - Feb 2013

1BB

5m*lementing an E(ent-Register

5m*lementing an E(ent-Register $sing a hared Fariable2 an 5nterr!*t .oc" and a ema*hore The interr!*t loc" is !sed to g!ard the shared (ariable 3 5 Rs can generate e(ents thro!gh the shared (ariable 4 The sema*hore bloc"s the tas" &aiting on the desired e(ent 7#ent$recei#e(wanted$e#ents) * tas)$c&.wanted$e#ents < wanted$e#ents while(TR87) ac- ire(tas)$c&.e#ent$semaphore) disa&le(interr pts) e#ents < wanted$e#ents HOR tas)$c&.recei#ed$e#ents tas)$c&.wanted$e#ents < tas)$c&.wanted$e#ents (;/ ( ;OT e#ents ) ena&le (interr pts) i"( e#ents is not empty ) ret rn (e#ents) end i" end while 0

First Technology Transfer - Feb 2013

1BC

5m*lementing an E(ent-Register - ctd0


7#ent$send(e#ents) * disa&le(interr pts) tas)$c&.recei#ed$e#ents < tas)$c&.recei#ed$e#ents OR e#ents ena&le interr pts release (tas)$c&.e#ent$semaphore) 0

First Technology Transfer - Feb 2013

1BG

/andling M!lti*le Data and E(ent 5n*!ts

5n this *attern the daemon tas" has m!lti*le data in*!t so!rces 3 tas"s generating in*!t data4 and m!lti*le e(ent in*!t so!rces 3 5 Rs generating in*!t data 4 A sim*le exam*le might be a daemon that *rocesses data from an 56% de(ice and has a *eriodic timer

$sed for reco(ery if the de(ice is st!c" in an inconsistent state

@in some systems this f!nctionality is *ro(ided by a &atchdog timerA

The design *attern described here !ses

An e(ent register - &ith a gi(en in*!t being assigned to a gi(en bit in the e(ent register A co!nting sema*hore for e(ent acc!m!lation - for each e(ent in*!t so!rce A message ;!e!e for each data in*!t so!rce

5n this design *attern

The data *rod!cer *!ts a message in its message ;!e!e and sets the corres*onding bit in the e(ent register The 5 R increments its co!nting sema*hore and sets its corres*onding bit in the e(ent register
1BJ

First Technology Transfer - Feb 2013

/andling M!lti*le Data and E(ent 5n*!ts - ctd0

#se!do code for the daemon for one timer 5 R and one data *rod!cer9 while( ha#e$e#ents < wait "or e#ents "rom e#ent$re'ister ) i" ( ha#e$e#ents D /(T($7@7;T ) while( "etch messa'e "rom messa'e$- e e ) process messa'e end while end i" i" ( ha#e$e#ents D TIM7R$7@7;T ) co nter < G disa&le ( interr pts ) while ( ac- ire ( co ntin'$semaphore ) ) co nter < co nter = 6 end while ena&le ( interr pts ) i" ( co nter E M(H$CO8;T ) do$reco#ery else handle$tic)$e#ent end i" end i" end while

First Technology Transfer - Feb 2013

1C0

ending $rgent 6 /igh #riority Data -et&een Tas"s

5n this design *attern !rgent data is *laced into an !rgent message ;!e!e The remaining data is *laced into a normal message ;!e!e )hen a data *rod!cer tas" or 5 R has reg!lar data it *laces that data into its normal data message ;!e!e )hen a data *rod!cer tas" or 5 R has !rgent data to handle it *laces that data into an !rgent message ;!e!e and signals the cons!mer tas"0 The cons!mer tas"1s !rgent data signal handler retrie(es !rgent data from the !rgent data message ;!e!e and deals &ith it This *attern can be f!rther enhanced by adding flo& control mechanisms to control the flo& of !rgent data0

First Technology Transfer - Feb 2013

1C1

Deadloc"s

A Deadloc" is a state in &hich m!lti*le conc!rrent threads of exec!tion in a system are *ermanently loc"ed beca!se they ha(e reso!rce re;!irements that cannot be satisfied0 The conditions necessary for deadloc" to arise are

M!t!al excl!sion - a reso!rce can only be accessed by one tas" at a time Mo *reem*tion - a non *reem*tible reso!rce cannot be forcibly remo(ed from the tas" holding that reso!rce

5t only becomes a(ailable if the tas" gi(es it !* (ol!ntarily

/old and &ait - a tas" holds on to reso!rces it has already ac;!ired &hile &aiting to ac;!ire f!rther reso!rces Circ!lar &ait - a circ!lar chain of t&o or more tas"s exists &here each tas" holds one or more reso!rces re;!ired by the next tas" in the chain

First Technology Transfer - Feb 2013

1C2

Deadloc"s - ctd0

)hether deadloc" &ill occ!r or not is infl!enced by the reso!rce re;!est model - common ones being

ingle reso!rce re;!est model

Tas" can ha(e at most one o!tstanding reso!rce re;!est at a time Tas" can ha(e m!lti*le o!tstanding reso!rce re;!ests Tas" bloc"ed !ntil all the o!tstanding reso!rce re;!ests are granted Tas" can ha(e m!lti*le o!tstanding reso!rce re;!ests Tas" res!mes exec!tion as soon as one or more of the reso!rces re;!ested become a(ailable

AMD reso!rce re;!est model


%R reso!rce re;!est model


AMD-%R reso!rce re;!est model - &hich is a combination of the *re(io!s t&o


1C3

First Technology Transfer - Feb 2013

Deadloc" Detection

A stable deadloc" is one that can only be resol(ed by some external infl!ence

Arises &hen no tas" in the deadloc"ed set ex*ects a timeo!t or an abort that &ill eliminate the deadloc"

Many RT% come &ith a deadloc" detection mechanism - a global algorithm that is r!n *eriodically

5t detects deadloc"s in the system by examining the c!rrent state of reso!rce allocation and the *ending reso!rce re;!ests 5t is intr!si(e on the exec!tion of the tas"s in(ol(ed in the deadloc" The tas"s in(ol(ed in the deadloc" are not :deadloc" a&are:

A tem*oral deadloc" is one &here one or more tas"s of the deadloc"ed set either times o!t or aborts as a res!lt of timing constraints0

)hen a tas" times o!t of aborts it

Frees !* any reso!rces it &as holding at the time

This might res!lt in freeing !* reso!rces that &ere ca!sing the deadloc"
1C8

The tas" is :deadloc" a&are:

First Technology Transfer - Feb 2013

Deadloc" A(oidance

This is an algorithm de*loyed by the reso!rce allocation system

The algorithm *redicts &hether the c!rrent allocation re;!est &ill e(ent!ally lead to a deadloc" in the f!t!re if it is granted Each time a reso!rce re;!est is made the system tests to see if granting this re;!est &ill allo& the remaining reso!rces to be granted to different tas"s in s!bse;!ent allocations so that all tas"s can r!n to com*letion For deadloc" a(oidance to &or" each tas" needs to be able to estimate its maxim!m reso!rce re;!irements *er reso!rce ty*e in ad(ance

Diffic!lt to achie(e in highly dynamic systems Manageable in systems &ith *redictable o*erating en(ironments

First Technology Transfer - Feb 2013

1C?

Deadloc" #re(ention

Deadloc" *re(ention consists of a set of constraints and re;!irements that are b!ilt into the system s!ch that a reso!rce re;!est that might lead to a deadloc" is not *ermitted0

These constraints and re;!irements are designed to eliminate one or more of the conditions that might lead to deadloc" e0g0

Elimination of hold-and-&ait

A tas" m!st ac;!ire all the reso!rces it needs before starting exec!tion Dra&bac"s

Diffic!lt to "no& all reso!rces needed &hen system is highly dynamic All reso!rces m!st be released at once - hence m!st hold on to reso!rces till the tas" finishes -eca!se reso!rces are held for a long time and cannot be assigned to other tas"s this ma"es for inefficient !se of reso!rces
1CB

First Technology Transfer - Feb 2013

Deadloc" #re(ention - ctd0

Elimination of no-*reem*tion

Tas" m!st release already ac;!ired reso!rces if a ne& re;!est is denied Tas" m!st then start re;!esting re;!ired reso!rce all o(er again

Dra&bac"s

)hen re-starting reso!rce ac;!isition tas" m!st start from the beginning or from some &ell-defined chec"*oint #artially com*lete &or" is n!llified Tas" might ne(er com*lete

Eliminating circ!lar &ait deadloc" conditions

Re;!ires an ordering of reso!rces - so that if tas" holds reso!rce n!mber i then the next reso!rce it attem*ts to ac;!ire m!st be for reso!rce n!mber < &here < R i Reso!rces are organised in a hierarchical str!ct!re and a tas" is *ermitted to ac;!ire additional reso!rces &hile holding other reso!rces2

#ro(iding these additional reso!rces are higher in the hierarchy than any of the reso!rces c!rrently held

First Technology Transfer - Feb 2013

1CC

#riority 5n(ersion

#riority in(ersion is a sit!ation that occ!rs &here a lo&er *riority tas" is exec!ting and bloc"ing a higher *riority tas" from exec!ting beca!se the lo&er *riority tas" is holding a reso!rce re;!ired by the higher *riority tas"0 #riority in(ersion can become e(en more *roblematic &hen the lo& *riority tas" holding the :needed reso!rce: is itself *re-em*ted by another higher *riority tas" 3 e0g0 an intermediate le(el *riority tas" 40

)hen &ill the lo&er *riority tas" finish &ith the :needed: reso!rce so that the higher *riority tas" can ac;!ire it and r!n >

%ne a**roach to the *roblem of *riority in(ersion is to raise 3tem*orarily4 the *riority of the tas" holding the :needed reso!rce: to the same *riority le(el as the higher *riority tas" that is bloc"ed0

This is the basis of the #riority 5nheritance #rotocol &hose r!les go(erning the sit!ation &here a tas" T is re;!esting a reso!rce R are as follo&s

R10 5f R is in !se T is bloc"ed R20 5f R is free then R is allocated to T R30 )hen a tas" of higher *riority than T re;!ests the reso!rce R then the exec!tion *riority of T is raised to that of the re;!esting tas" R80 Tas" T ret!rns to its *re(io!s *riority &hen it releases R
1CG

First Technology Transfer - Feb 2013

The Ceiling #riority #rotocol

The #riority 5nheritance #rotocol does not eliminate deadloc"0 The Ceiling #riority #rotocol re*resents an attem*t to im*ro(e on the #riority 5nheritance #rotocol0 /ere The *riority of e(ery tas" is "no&n The reso!rces re;!ired by e(ery tas" are "no&n For any gi(en reso!rce the *riority ceiling of that reso!rce is the highest *riority of all *ossible tas"s that might need to ac;!ire that reso!rce The r!les go(erning the sit!ation &here a tas" T is re;!esting a reso!rce R are as follo&s R10 5f R is in !se T is bloc"ed R20 5f R is free then R is allocated to T0 T1s exec!tion *riority is raised to the *riority ceiling of R if that is higher0 At any gi(en time T1s exec!tion *riority is e;!al to the highest *riority ceiling of all the reso!rces it holds R30 T1s *riority is assigned the next-highest *riority ceiling of the remaining reso!rces &hen T releases a reso!rce &ith the highest *riority ceiling R80 Tas" T ret!rns to its *re(io!s *riority &hen it has releases all reso!rces

First Technology Transfer - Feb 2013

1CJ

The #riority Ceiling #rotocol

/ere

The *riority of e(ery tas" is "no&n The reso!rces re;!ired by e(ery tas" are "no&n before that tas" starts exec!ting The c!rrent *riority ceiling for a r!nning system is the highest *riority ceiling of all reso!rces in !se at that time

The r!les go(erning the sit!ation &here a tas" T is re;!esting a reso!rce R are as follo&s R10 5f R is in !se T is bloc"ed R20 5f R is free and the *riority of T is higher than the c!rrent *riority ceiling then R is allocated to T R30 5f the c!rrent *riority ceiling belongs to one of the reso!rces that T c!rrently holds2 then R is allocated to T2 other&ise T is bloc"ed R80 The tas" that bloc"s T inherits T1s *riority if it is higher and

Exec!tes at this *riority !ntil it releases e(ery reso!rce &hose *riority ceiling is higher than or e;!al to T1s *riority 0 The tas" then ret!rns to its *re(io!s *riority
1G0

First Technology Transfer - Feb 2013

The #riority Ceiling #rotocol - ctd0

5n the #riority Ceiling #rotocol the *ossible ca!ses for a tas" being bloc"ed are therefore

Direct reso!rce contention - the re;!ested reso!rce is c!rrently in !se #riority inheritance bloc"ing - the bloc"ing tas" has inherited a higher *riority and its c!rrent exec!tion *riority is higher than that of the re;!esting tas" #riority ceiling bloc"ing - a tas" cannot bloc" itself if it holds a reso!rce that has defined the c!rrent *riority ceiling A circ!lar &ait condition is not *ossible beca!se

The #riority Ceiling #rotocol im*oses an ordering on the ac;!isition of reso!rces0

Mone of the tas"s holding reso!rces can inherit a higher *riority than T2 and then *reem*t T and re;!est a reso!rce that T holds0

The "ey characteristics of the *riority ceiling *rotocol are therefore

A re;!esting tas" can be bloc"ed by only one tas" - the bloc"ing inter(al is th!s limited to at most the d!ration of a single critical section Transiti(e bloc"ing is not *ossible Deadloc" can ne(er occ!r

First Technology Transfer - Feb 2013

1G1

Fo!ndations of ARM CortexM Embedded C #rogramming

First Technology Transfer - Feb 2013

1G2

%(er(ie&

#rere;!isites

Familiarity &ith the C #rogramming .ang!age ome ex*erience of &or"ing &ith embedded systems

The co!rse &ill co(er

Architect!re and 5nstr!ction et of the ARM Cortex M3

The ARM Cortex M8 feat!res can be considered as a s!*erset of those of the ARM Cortex M3 L#5% Timers $ART A6D

)riting C code to initialise and !se common on chi* *eri*herals and de(ices

5m*lementing interr!*t handles tandard techni;!es for testing and deb!gging code

First Technology Transfer - Feb 2013

1G3

Cha*ter 1 %(er(ie& of the ARM Cortex M3 /istory and Architect!re

First Technology Transfer - Feb 2013

1G8

ARM S Cortex M3

ARM does not ma"e *rocessors it designs *rocessor architect!res and licences the 5ntellect!al #ro*erty 35#4 to chi* man!fact!rers s!ch as T2 Atmel2 T52 MH#

The chi* man!fact!rers then design and im*lement real *rocessors by adding e0g0 (ario!s *eri*herals s!ch as 52C2 #52 $ART2 CAM T

The ARM family of *rocessors s*ans the range from chea* and *o&er efficient de(ices to high *erformance de(ices2 incl!ding m!lti-core de(ices The target mar"et of the Cortex-M3 core is the field2 traditionally2 ser(ed by G- or 1Bbit controllers2 &here

Chea* yet *o&erf!l controllers &ith lo& *o&er cons!m*tion are re;!ired

%n ARMC systems man!fact!rers had to add the basic *eri*herals s!ch as2 the interr!*t controller2 systic" timer and s!**ort for slee* modes0 This Cortex-M3 core design comes &ith a standardi'ed microcontroller core &hich

#ro(ides a core design &ith the interr!*t system2 28-bit ysTic" timer2deb!g system and memory ma* incl!ded0

First Technology Transfer - Feb 2013

1G?

Cortex M3 - Architect!re

The Cortex family has three main *rofiles

The A *rofile for high end a**lications

#rocessors targeted at com*lex % and !ser a**lications

The R *rofile2 targeted at real time a**lications The M *rofile2 targeted at cost-sensiti(e embedded system microcontroller a**lications 5t has se*arate Code and Data b!ses

The Cortex-M3 is a /ar(ard architect!re

The architect!re inside the Cortex-M3 is a ARM(C- M R5 C *rocessor The M core is relati(ely small2 ha(ing only 33U000 logic cells This red!ces the si'e of the chi* and means that chea*er man!fact!ring *rocesses !sing 003?Vm technology can be !sed

First Technology Transfer - Feb 2013

1GB

Cortex M3 - 5nterr!*ts

The Cortex-M3 core *ro(ides a Mested Fector 5nterr!*t Controller 3MF5C40 The MF5C *ro(ides a standardised interr!*t str!ct!re &ith dedicated interr!*t (ectors for !* to 280 *eri*heral so!rces

Each interr!*t so!rce can be indi(id!ally *rioriti'ed

The MF5C *ro(ides fast interr!*t handling0

The time ta"en from recei(ing an interr!*t to starting the first line of code in the interr!*t ser(ice ro!tine is t&el(e cycles0

All interr!*ts can be *rioriti'ed on three le(els9 *re-em*ting2 s!b-*riority and hard&are-*riority0

The first t&o le(els can be config!red (ia the soft&are The n!mber of bits for *riority le(el setting is 8

The design of the Cortex is s!ch that interr!*t ser(ice ro!tines 35 R4 can be &ritten f!lly in C

5nterr!*t ro!tines do not re;!ire assembler code

First Technology Transfer - Feb 2013

1GC

Cortex 5nstr!ction et

ARMC and ARMJ C#$s ha(e t&o instr!ction sets


32-bit ARM and 1B-bit Th!mb )hen r!nning code containing mixed instr!ctions it is necessary to ex*licitly s&itch from one instr!ction set to another as necessary

The Cortex family is designed to s!**ort only the 1B-bit Th!mb-2 instr!ction set0

im*lifies assembler coding as there is no longer a need for s&itching bet&een t&o instr!ction sets0

The Th!mb-2 instr!ction &as designed to be feat!re rich2 and C6CII com*iler friendly

First Technology Transfer - Feb 2013

1GG

Cortex C#$

The Cortex core is a 32-bit R5 C C#$ core

/as a richer instr!ction set &hen com*ared &ith earlier ARMC6J *rocessors architect!res

Lood integer maths s!**ort 5m*ro(ed bit mani*!lation UharderU real-time *erformance

#i*eline

The Cortex C#$ can exec!te most instr!ctions in a single cycle2 similarly to ARMC and ARMJ C#$s by

$sing a three stage *i*eline0

)hilst one instr!ction is being exec!ted2 the next isbeing decoded and a third is being fetched from memory0

M!lti*lication

A 32-bit m!lti*lication can be exec!ted in one cycle as the Cortex-M3 has a hard&are m!lti*lication !nit0

The Cortex-M3 architect!re is s!ch that there is no longer a need to im*lement start!* code in assembler S it can2 no&2 be done in C0
1GJ

First Technology Transfer - Feb 2013

Cortex M3 S Deb!g 5nterface

The Cortex-M3 has a Deb!g Access #ort 3DA#4 &hich can be !sed in

7TAL mode2 or 5n erial)ire Deb!g Mode

Re;!ires only t&o lines

Cloc" and data0 ARMC *rocessors had only t&o /ard&are--rea"*oints0 The Cortex-M3 has

G brea"*oints2 and2 additionally Fa!lt Conditions and Exce*tions can be set0

Fa!lts and Exce*tions can be s!*er(ised &itho!t the ha(ing to set brea"*oints0

The deb!g interface &or"s in lee*-mode0

First Technology Transfer - Feb 2013

1J0

Exam*le Cortex M3 #rocessor

The .#C1CBG from MH# is a fairly ty*ical Cortex M3 *rocessor

5ts C#$ cloc" can r!n at !* to 100 M/' ?12"- on-chi* Flash R%M &ith enhanced Flash Memory Accelerator2 5n- ystem #rogramming 35 #4 and 5n-A**lication #rogramming 35A#42 B8"- RAM Eight channel Leneral *!r*ose DMA controller2 Ethernet 106100 MAC &ith dedicated DMA2 $ - 200 f!ll-s*eed De(ice controller and /ost6%TL controller &ith DMA2 CAM 200- &ith t&o channels Fo!r $ARTs2 one &ith f!ll Modem interface2 Three 52C serial interfaces Three #56 # serial interfaces %ne 52 interface2

First Technology Transfer - Feb 2013

1J1

Exam*le Cortex M3 #rocessor S ctd0


Leneral *!r*ose 56% *ins 12-bit ADC &ith G channels 10-bit DAC2 Fo!r 32-bit Timers &ith ca*t!re6com*are2 tandard #)M Timer bloc"2 Motor control #)M for three-*hase Motor control =!adrat!re Encoder2 )atchdog Timer Real Time Cloc" &ith o*tional -attery bac"!*2 ystem Tic" Timer Re*etiti(e 5nterr!*t Timer -ro&n-o!t detect circ!it2 #o&er-%n Reset2 #o&er Management $nit2 )a"e!* 5nterr!*t Controller2 Crystal oscillator2 8M/' internal RC oscillator2 #..2 7TAL and erial )ire Deb!g6Trace #ort &ith ETM

First Technology Transfer - Feb 2013

1J2

Cortex M3 - chematic
Cortex-M3 #rocessor Core ystem 5nterr!*t Controller 3MF5C4 5nstr!ction Fetch $nit Decoder Register -an" A.$ Trace 5nterface

5nterr!*ts

Deb!g ystem

Trace

Memory 5nterface

5nstr!ction -!s

Memory #rotection $nit

Data b!s

-!s 5nterconnect

Deb!g 5nterface

Deb!g

Code Memory

Memory system And *eri*herals

#ri(ate #eri*herals

%*tional

First Technology Transfer - Feb 2013

1J3

Cortex-M3 Registers

The Cortex-M32 li"e most R5 C *rocessors has a set of general *!r*ose registers

R0 - R12

As &ell as three registers R13 - R1? that are !sed for

tac" #ointer R13 - act!ally there are t&o of these and they are ban"ed 3only one is (isible at a time4

R13 3M #4 - Main tac" #ointer R13 3# #4 - #rocess tac" #ointer

.in" Register 3.R4 - R18 #rogram Co!nter 3#C4 - R1?

*ecial registers

#rogram registers 5nterr!*t mas" registers Control register

First Technology Transfer - Feb 2013

1J8

*ecial Registers

#rogram stat!s registers - x# H - ha(e bits 3flags4 *ro(iding stat!s information4

Arithmetic and logic *rocessing flags


'ero flag carry flag

Exec!tion stat!s C!rrent exec!ting interr!*t n!mber

5nterr!*t mas" registers

#R5MA K - $sed to disable all interr!*ts exce*t the nomas"able interr!*t 3MM54 and hard fa!lt FA$.TMA K - $sed to disable all interr!*ts exce*t the MM5 -A E#R5 - $sed to disable all interr!*ts ha(ing a *riority le(el e;!al to or less than some s*ecified *riority le(el C%MTR%. - $sed to define *ri(ilege stat!s and stac" *ointer selection

First Technology Transfer - Feb 2013

1J?

Cortex M3 - Registers

First Technology Transfer - Feb 2013

1JB

%*eration Modes

!**ort for code safety is *ro(ided by controlling the *rocessor state A Cortex-M3 *rocessor has

T&o modes

Thread mode - r!nning a normal *rocessing thread /andler mode - r!nning an exce*tion handler

5nterr!*t handler ystem exce*tion handler

T&o *ri(ilege le(els

#ri(ileged le(el

#rocessor has access to all memory ranges 3!nless barred by Memory #rotection $nit 3M#$4 settings - if the *rocessor has an M#$ /as access to all instr!ctions s!**orted by the *rocessor Cannot change to a *ri(ileged state by &riting to the control register To change *ri(ilege le(el it has to trigger an exce*tion and the exce*tion handler changes *ri(ilege le(el
1JC

$ser *rogram

First Technology Transfer - Feb 2013

%*eration Modes - ctd0


Exce*tion handlers can only r!n in *ri(ileged mode )hen a *rocessor lea(es the reset state it is r!nning a reg!lar *rogram 3thread mode4 and is in the *ri(ileged state An exce*tion handler can change the *ri(ilege le(el of a !ser thread

Mormally &hen an exce*tion handler has com*leted its &or" the *rocessor &ill ret!rn to its *re(io!s state )hen an exce*tion handler changes the state e0g0 from *ri(ileged to !ser2 by &riting to the Control register then the *rocessor &hen it ret!rns2 ret!rns to the ne&ly config!red state

A *ri(ileged !ser *rocess can change its state to !ser by &riting to the control register The ability to s&itch bet&een *ri(ileged and !ser le(els is !sef!l &hen im*lementing o*erating systems

5t *ro(ides a means of *rotecting the o*erating system from +rog!e, a**lications

First Technology Transfer - Feb 2013

1JG

%*eration Mode F M

First Technology Transfer - Feb 2013

1JJ

Mested Fectored 5nterr!*t Controller 3MF5C4

The Mested Fectored 5nterr!*t Controller 3MF5C4 allo&s nesting of interr!*ts &ith higher *riorities0 i0e0

5f a higher *riority interr!*t occ!rs &hilst a lo&er *riority interr!*t handler is exec!ting then2

The lo&er *riority interr!*t is *reem*ted and the higher *riority interr!*t exec!tes next0

Certain *riorities s!ch as the reset exce*tion &hich is the highest 3lo&est n!mber4 *riority2 are fixed %ther exce*tion handler *riorities are *rogrammable and can be changed dynamically2 i0e at r!n time2

To be able to change *riorities dynamically re;!ires that the interr!*t (ector is relocated from flash to ram and that it is then *atched &ith the ne& handler0

First Technology Transfer - Feb 2013

200

Mested Fectored 5nterr!*t Controller 3MF5C4

The MF5C ta"es care of stac"ing 3*!shing registers onto the stac"4 and !n-stac"ing 3*o**ing registers from the stac"4 at the hard&are le(el2 hence

An exce*tion handler can be im*lemented as a reg!lar C f!nction

Fectored means that &hen an interr!*t is asserted its n!mber is "no&n to the *rocessor and is !sed to index into the interr!*t (ector to obtain the handler address directly

Contrast this &ith a shared handler &hich re;!ires code for en!merating de(ices to disco(er &hich de(ice interr!*ted the *rocessor0

)hen de(ising *rioritisation strategies caref!l analysis and design is re;!ired2 a sim*ler sol!tion is !s!ally *referable to a com*lex one

)or"ing &ith <!st three *riority le(els e0g0 lo&2 medi!m and high is not ;!ite as straightfor&ard as one might thin"

First Technology Transfer - Feb 2013

201

MF5C - Tail Chaining

)hen t&o interr!*ts arri(e at the same time2 or a lo&er *riority interr!*t occ!rs &hile exec!ting a same or higher *riority interr!*t i0e0 non *re-em*ting2

The higher *riority interr!*t exec!tes first &hile the other remains *ending and As soon as the higher *riority interr!*t finishes exec!ting the *ending interr!*t is exec!ted immediately2 i0e0 tail-chained to the first one2 &itho!t !n-stac"ing and then stac"ing the registers again &hich is not necessary beca!se

The contents of the stac" ha(e not changed This s*eeds !* the exec!tion of s!bse;!ent interr!*t handlers0

Mote 9

D!e to the /ar(ard architect!re2 the stac"ing of the registers can ta"e *lace sim!ltaneo!sly &ith the fetches of the interr!*t (ector and isr code0

First Technology Transfer - Feb 2013

202

MF5C - .ate Arri(al

)hen a high *riority interr!*t is asserted &hile the *rocessor is entering a lo&er *riority interr!*t2 and the assert occ!rs bet&een stac"ing of registers and before the exec!tion of the first handler instr!ction2

The higher *riority interr!*t (ector is fetched tac"ing is allo&ed to finish2 and as soon as it has done so2

The *rocessor exec!tes the higher *riority interr!*t immediately2 then2 &hen it finishes exec!ting it2 The lo&er *riority interr!*t is tail-chained to the higher *riority interr!*t and allo&ed to exec!te0

imilarly2 if the interr!*t occ!rs &hile !n-stac"ing is ta"ing *lace2 the !n-stac"ing is abandoned and and the lo&er *riority interr!*t is tail-chained to the higher *riority interr!*t and allo&ed to exec!te0 These scenarios are ill!strated on the next slide

First Technology Transfer - Feb 2013

203

MF5C - .ate Arri(al and #re-em*tion - 5ll!strated


.ate Arri(al

#re-em*tion

First Technology Transfer - Feb 2013

208

-it -anding

A -it--and region ma"es it *ossible to *erform atomic bit mani*!lation thro!gh another memory region called the alias region

Each bit in the -it--and region can be addressed thro!gh a 32-bit aligned address in the alias region2 i0e0

Each &ord in the -it--and is ma**ed to 32 addresses in the alias region0

-it--anding can s*eed !* a read-modify-&rite o*eration e0g0

5n order to set a bit bit in some de(ice register2 for instance2 to enable interr!*ts2 the normal *roced!re &o!ld be to *erform a read-modify-&rite o*eration i0e0

Read a &ord2 then Mas" it and then

)here there are conc!rrency iss!es it &o!ld also be necessary to ens!re that the o*eration &o!ld be atomic A code sni**et sho&ing the "ind of code that &o!ld be &ritten is sho&n on the next slide

First Technology Transfer - Feb 2013

20?

-it -and Ma**ing

First Technology Transfer - Feb 2013

20B

-it -anding - ctd0


#define DEVICE_BASE_ADDR #define ENABLE_INT_ AS! ((uint32_t*)0x2007C000) (0x0") #$id en%&'e_int() ( )) t%* f$+ ex,'u-i#e %,,e-)) .%it ./i'e it0- '$,1ed ./i'e (__LDRE23(DEVICE_BASE_ADDR))4 uint32_t i 5 *DEVICE_BASE_ADDR4 i 65 ENABLE_INT_ AS!4 __STRE23(i7 DEVICE_BASE_ADDR)4 }

))ex,'u-i#e .+ite

Mote9 .DREH and TREH are the ne&er ARM

These instr!ctions do not loc" the b!s

First Technology Transfer - Feb 2013

20C

-it -anding - ctd0

$sing bit-banding the code sni**et sho&n *re(io!sly co!ld be re-&ritten as follo&s

#define DEVICE_BASE_ALIAS #$id en%&'e_int() ( *DEVICE_BASE_ALIAS 5 "4 }

((uint32_t*)0x22000000)

First Technology Transfer - Feb 2013

20G

Cortex M3 - Memory Ma*

The ARM Corte'-M3 memory ma* is *redefined

-!ilt-in *eri*herals can be accessed (ia standard memory access instr!ctions

32 bit addressing s*ans a 8 L- memory s*ace

5n *ractice Cortex-M3 systems &ill ha(e considerably less than 8 L- of memory The 8L- memory s*ace is di(ided into s*ecified address ranges

C%DE RAM #eri*herals External RAM External de(ice ystem le(el

The Cortex-M3 internal b!s infrastr!ct!re is o*timised for memory !sage

First Technology Transfer - Feb 2013

20J

Cortex M3 - Memory Ma*

First Technology Transfer - Feb 2013

210

Cortex M3 - Memory Ma* - 5nterfaces

First Technology Transfer - Feb 2013

211

Memory #rocessor Regions - #ermissions


)R - )rite Thro!gh )-)A - )rite -ac" )rite Allocate HM - Exec!te Me(er Mote9 #ri(ate #eri*heral -!s and ystem s*ace at 0xE0000000 - 0xFFFFFFFF are *ermanently HM0 The M#$ cannot change this0

First Technology Transfer - Feb 2013

212

-!s 5nterface

The Cortex-M3 has se(eral b!s interfaces -!s interfaces s!**ort instr!ction fetches and data access conc!rrently Main b!s interfaces Code memory b!ses 5-Code b!s - for instr!ction fetches and (ector fetches from code memory s*ace D-code b!s - for data and deb!g access to code memory s*ace Data access has higher *riority than deb!g access ystem b!s 5nstr!ction and (ector fetches as &ell as data and deb!g access to ystem memory s*ace Arbitration order is Data accesses 5nstr!ction and (ector fetches Deb!g #ri(ate *eri*heral b!s Data and deb!g access to External #eri*heral memory s*ace

First Technology Transfer - Feb 2013

213

Cha*ter 2 #rogramming the Cortex-M3 in C

First Technology Transfer - Feb 2013

218

Ty*ical A**lication -!ild

A *ro<ect2 ty*ically2 in(ol(es com*iling se(eral mod!les 3 mostly C mod!les2 b!t2 maybe2 also some assembler mod!les4

This *rod!ces a collection of ob<ect 30o4 files

The (ario!s ob<ect files are lin"ed2 together &ith library 3archi(e4 files to *rod!ce an exec!table image file in an a**ro*riate format e0g0 0axf or 0elf

AHF - ARM Exec!table Format - a s*ecialised form of E.F E.F - Exec!table and .in"ing Format

)here the memory ma* is com*lex the lin"ing *rocess can be controlled (ia a scatter-loading scri*t )hen *rogramming the Cortex-M3 in C it is common to find that Cortex-M3 microcontroller man!fact!rers s!**ly de(ice dri(er libraries2 im*lemented in C2 for controlling the (ario!s *eri*herals ARM has de(elo*ed a Cortex Microcontroller oft&are 5nterface tandard 3CM 5 4

First Technology Transfer - Feb 2013

21?

Cortex-M3 5DEs

The more &idely !sed commercial ARM Cortex-M3 de(elo*ment tools are those from

Keil - no& *art of ARM 5AR Code-Red - from MH#2 and targetted at MH# Cortex-M3 designs

This 5DE is Ecli*se based

Most of these 5DEs come &ith a (ario!s exam*le *rograms demonstrating !se of (ario!s *eri*herals De(elo*ers of Cortex-M3 based de(elo*ment and e(al!ation boards also *ro(ide exam*les targetted at their *artic!lar boards

tellaris - no& *art of T5 Embedded Artists - a &edish com*any that ma"es a (ariety of ARM based teaching and *rototy*ing boards - they &or" ;!ite closely &ith MH# %limex - a -!lgarian com*any that ma"es a &ide (ariety of inex*ensi(e embedded systems boards - incl!ding ARM Cortex-M3 boards

First Technology Transfer - Feb 2013

21B

A im*le Cortex-M3 C #rogram

This exam*le is ta"en from the MH# - Code Red exam*le set for the MH# .#C1CBG *rocessor 3&hich is closely related to the MH# .#C1CBJ *rocessor4 5t consists of t&o files

crOstart!*Ol*c1CBx0c 5%test0c

5t is a (ariation on the classical embedded system +hello &orld, exam*le that in(ol(es flashing one or more .EDs Fariations on this exam*le are

Flashing .EDs !sing a +timed &hile loo*, Flashing .EDs by *olling for a Timer %(erflo& e(ent flag Flashing .EDs by !sing a Timer 5nterr!*t

First Technology Transfer - Feb 2013

21C

crOstart!*Ol*c1CBx0c

This "ind of file is ty*ical of embedded Cortex-M3 a**lications Ty*ically it

ets !* the Fector table

5n sim*le *rograms most of the exce*tion handlers &ill be im*lemented as d!mmy f!nctions

Calls S8-te9Init() if CM 5 is being !sed *ecifies the entry *oint


calls __9%in if the Red.ib library is !sed calls 9%in other&ise

Finally ends &ith a +fail safe, infinite &hile loo*

./i'e (") ( 4 }

First Technology Transfer - Feb 2013

21G

5%test0c

Mani*!lating L#5% in(ol(es

etting the 5% #ort *ins to be either in*!ts or o!t*!s )riting 1 or 0 to the #ort *ins to &hich the .EDs are attached to t!rn them on or off T!rning an .ED on )aiting for a &hile T!rning an .ED off )aiting for a &hile

-lin"ing in(ol(es - re*eatedly

First Technology Transfer - Feb 2013

21J

5%test0c - Code
#in,'ude :';,"7xx</: #in,'ude :t8;e</: int 9%in (#$id) ( uint32_t i7 =4 )* S8-te9C'$,1>;d%te() u;d%te- t/e S8-te9?+e@uen,8 #%+i%&'e *) S8-te9C'$,1>;d%te()4 LAC_BAIC2DE?ICDIR 5 0x000000??4 LAC_BAIC2DE?ICCLR 5 0x000000??4 ./i'e(") ( f$+(i 5 04 i F G4 iHH) ( LAC_BAIC2DE?ICSET 5 " FF i4 f$+(= 5 "0000004 = E 04 =DD)4 } LAC_BAIC2DE?ICCLR 5 0x000000??4 f$+(= 5 "0000004 = E 04 =DD)4 } )* A2<xx defined %- Cut;ut- *) )* tu+n $ff %'' t/e LED- *)

First Technology Transfer - Feb 2013

220

Accessing Memory-Ma**ed Registers in C

trategies for accessing memory ma**ed registers in C code incl!de Defining a macro to con(ert address (al!es into C *ointers There are (ario!s &ays of doing this W T5CK Timer Registers

W T5CK Timer Registers

First Technology Transfer - Feb 2013

221

Accessing Memory-Ma**ed Registers in C - ctd0

Defining the registers as a data str!ct!re and then defining a *ointer to that str!ct!re
W T5CK Timer Registers

First Technology Transfer - Feb 2013

222

Accessing Memory-Ma**ed Registers in C - ctd0

$sing a data str!ct!re2 and defining the base address of the *eri*heral !sing a scatter lin"er scri*t d!ring the lin"ing stage W T5CK
Timer Registers

First Technology Transfer - Feb 2013

223

CM 5 - -ac"gro!nd

The moti(ation !nderlying CM 5 &as to im*ro(e

oft&are !sability oft&are inter-o*erability

%f ARM Microcontroller soft&are

The "ey idea &as to

#ro(ide a standardised soft&are interface for Cortex-M3 *rocessor feat!res #ro(ide a standardised set of common system and 56% f!nctions To im*ro(e soft&are *ortability and re!sability To ma"e it easier for soft&are sol!tion s!**liers to de(elo* *rod!cts that co!ld &or" seamlessly &ith de(ice dri(er libraries from different silicon (endors *eed !* the soft&are de(elo*ment *rocess Ma"e it *ossible to !se embedded soft&are on m!lti*le com*iler toolchains Minimise de(ice dri(er com*atibility iss!es &hen so!rcing soft&are from m!lti*le *ro(iders
228

The goals &ere

First Technology Transfer - Feb 2013

CM 5 - Areas of tandardisation

/ard&are Abstraction .ayer 3/A.4 for Cortex-M3 *rocessor registers

tandardised definitions for MF5C2 ystem Control -loc" registers2 W T5CK register2 M#$ registers 000

tandardised system exce*tion names tandardised header file organisation method Common system initialisation method

Fia a (endor *ro(ided SystemInit() f!nction An intrinsic f!nction is one that *rod!ces instr!ctions 3assembler code4 that cannot be generated ib 5EC65 % C

tandardised intrinsic f!nctions

Common comm!nication access f!nctions for $ART2 Ethernet2 #5 000 tandardised method for embedded soft&are to determine the system cloc" fre;!ency

The de(ice dri(er code defines and initialises a (ariable called ystemFre;!ency

An embedded % cn set ! the W T5CK !nit based on the system cloc" fre;!ency
22?

First Technology Transfer - Feb 2013

CM 5 %rganisation

The str!ct!re of CM 5 follo&s a layered a**roach Core #eri*heral Access .ayer

Mame and address definitions /el*er f!nctions for accessing core registers and core *eri*herals

Middle&are Access .ayer

Common *eri*heral access methods tandardised comm!nication interfaces for $ART2 Ethernet2 #5 000

MC$ s*ecific De(ice #eri*heral Access .ayer

Mame and address definitions Dri(er code for accessing *eri*herals

MC$ s*ecific access f!nctions for *eri*herals

%*tional additional hel*er f!nctions for *eri*herals

First Technology Transfer - Feb 2013

22B

CM 5

tr!ct!re

First Technology Transfer - Feb 2013

22C

CM 5 $se

CM 5 is inco*orated into the de(ice dri(er library

CM 5 can be !sed in *ro<ects &itho!t any s*ecial set!* re;!irement For any gi(en MC$ de(ice the de(ice (endor *ro(ides a header file2 &hich

5ncl!des any additional header files needed by the de(ice dri(er library

5ncl!ding the Core #eri*heral Access .ayer The (ario!s files are

,$+e_,93</ - &hich contains


#eri*heral register definitions and access f!nctions for the Cortex-M3 *rocessor *eri*herals CM 5 intrinsic f!nction *rototy*es

,$+e_,93<, - contains im*lementations of the intrinsic f!nctions -8-te9_Fde#i,eE</ - contains microcontroller s*ecific interr!*t n!mber and *eri*heral register definitions -8-te9_Fde#i,eE<, - contains the ystem5nit f!nction for the *artic!lar *rocessor
22G

First Technology Transfer - Feb 2013

CM 5 $se - ctd0

First Technology Transfer - Feb 2013

22J

#rogramming &ith FreeRT%

First Technology Transfer - Feb 2013

230

%(er(ie&

This mod!le follo&s (ery m!ch the *rinted and online doc!mentation for FreeRT% 2 incl!ding the (ario!s boo"s and the FreeRT% man!al &ritten by Richard -arry0 5t is ass!med that yo! ha(e co*ies of these to hand Rather than going thro!gh all the details to be fo!nd in the abo(e reso!rces the a**roach ta"en here &ill be to

Ex*lore the FreeRT% A#5 %(er(ie& FreeRT% config!ration and set!* iss!es 5m*lement and ada*t the (ario!s code sni**ets to be fo!nd in the FreeRT% man!al2 doc!mentation and boo"s Examine2 b!ild and r!n some of the demonstrator *rograms on a (ariety of ARM Cortex M8 boards !sing t&o 5DEs

5AR1s 5AR Embedded )or"bench 5DE - #ro*rietary com*iler &ith a Microsoft Fis!al t!dio based front end0 Atmel1s Atmel Fis!al t!dio B - com*iler based on the LM$ LCC com*iler

First Technology Transfer - Feb 2013

231

trategy

The strategy follo&ed &ill be an ob<ect oriented strategy 000

FreeRT% reso!rces can be considered as

5nstances of some reso!rce class &hich2 in effect

Defines attrib!tes Defines methods for mani*!lating and !sing reso!rce instances The "ey FreeRT% reso!rces are

Tas"s - Tas" A#5 =!e!es - =!e!e A#5 ema*hores - ema*hore A#5

5n addition it &ill be necessary to co(er

Memory management 5nterr!*t management )or"ing &ith ARM M#$ 3Memory #rotection $nit4

Wo! can do&nload the FreeRT% Cortex M3 exam*les from

http://www freertos or!/"ocumentation/co#e/source$co#e$for$%ortex$&'$e#ition$ examples$usin!$IA($an#$stellaris )ip


232

First Technology Transfer - Feb 2013

-ac"gro!nd

Richard -arry1s boo"s and the online FreeRT% doc!mentation *ro(ide (ery detailed descri*tions of the (ario!s A#5s 000 Rather than re*eating all the details here yo! sho!ld go and access them from the a**ro*riate so!rces Wo! are also enco!raged to ex*lore the FreeRT% so!rce code as some of the details can only be fo!nd o!t from ins*ecting the so!rces A cross-referencing &eb site 3b!ilt !sing %*enLro"4 can be fo!nd at http://co#e meta!er #e/source/xref/freertos/ Tools for searching and cross-referencing code 9 The il(er earcher - http://co#e meta!er #e/source/xref/freertos/ %*enLro" - http://www opensolaris or!/os/pro*ect/open!rok/ o*enhro" - extends the %*enLro" *ro<ect to index sni**ets2 &hich are files that are referenced by other files0 earch res!lts ta"e into acco!nt the n!mber of times a ni**et has been referenced
svn checkout http://openhrok.googlecode.com/svn/trunk/ openhrok-read-only

C co*e - http://cscope sourcefor!e net/ Wo! are also enco!raged to try o!t different com*ilers and com*are the res!lts e0g0 IA( +%% base# $ e ! Atmel Stu#io , -eil

First Technology Transfer - Feb 2013

233

FreeRT% - Code %(er(ie&

The t&o-(ol!me series +The Architect!re of %*en o!rce A**lications, contains a really good o(er(ie& of the architect!re of FreeRT% from the code - organisation2 data str!ct!re2 A#5 and algorithms *oint of (ie&

http://www aosabook or!/en/freertos html Do&nload the original for yo!r o&n !se 5f yo! ha(e time then install %*enLro" 6 o*enhro" 000

The next fe& slides are 3shamelessly4 based on the contents of that article

%heck that you can reach http://co#e meta!er #e/source/xref/freertos/

As &e go thro!gh the next fe& slides the intention is that yo! sho!ld ex*lore the so!rce code

Wo! sho!ld also di* +into and o!t of, the so!rce code d!ring the co!rse also

Ma"ing notes2 as &ell as !*dating these slides 3&here necessary4

First Technology Transfer - Feb 2013

238

FreeRT% The Tas" A#5

First Technology Transfer - Feb 2013

23?

Tas" A#5

This is *robably the largest and most com*lex A#5 in FreeRT% 5t contains

A#5 f!nctions for creating and managing tas"s A#5 f!nctions for interacting &ith and managing the sched!ler

Most of the !nderlying so!rce code is *latform inde*endent C #latform de*endent details in(ol(e things s!ch as

Config!ring the timer systems - that dri(e the sched!ler Config!ring the memory s!bsystem

M#$ 3Memory #rotection $nit4 - if *resent on the target *rocessor2 and2 if being !sed

Details of ho& tas"s interact &ith interr!*ts Details of ho& the ARM Cortex *ort of FreeRT% !ses CM 5 )riting *ro*rietary de(ice dri(ers - &here necessary
23B

First Technology Transfer - Feb 2013

FreeRT% - Architect!re

mall a**lication - minim!m FreeRT% core


Three so!rce 30c4 files and a small set of header files Aro!nd J000 lines of code Ty*ical binary code image is !nder 10K-0 Tas"s9 Acco!nts for aro!nd ?0X of the core so!rce code

Three main areas9 tas"s2 comm!nication2 and hard&are interfacing0

A tas" is a !ser-defined C f!nction &ith a gi(en *riority0 tasks c and task h do all the hea(y lifting for creating2 sched!ling2 and maintaining tas"s0

Comm!nication9 Acco!nts for abo!t 80X of the core code

Deals &ith comm!nication0 .ueue c and .ueue h handle FreeRT% comm!nication0 Tas"s and interr!*ts !se ;!e!es to send data to each other and to signal the !se of critical reso!rces !sing sema*hores and m!texes0 Abo!t BX of the FreeRT% core code acts a shim bet&een the hard&areinde*endent FreeRT% core and the hard&are-de*endent code0
23C

The core code is mostly hard&are-inde*endent

First Technology Transfer - Feb 2013

/ard&are De*endent Code

FreeRT% is highly config!rable by design

Can be b!ilt as a single C#$2 bare-bones RT% 2 s!**orting only a fe& tas"s2 or Can be b!ilt as a richly f!nctional m!lticore system &ith TC#65#2 a file system2 and $ -0

Config!ration o*tions are selected in FreeRT% Config0h by setting (ario!s Ydefines0

Cloc" s*eed2 hea* si'e2 m!texes2 and A#5 s!bsets are all config!rable in this file e0g0 con,'M(H$>RIORITI7S ( ( nsi'ned port4(S7$TJ>7 ) K ) con,'C>8$C1OCL$MN ( 69GGGGGG81 ) con,'TICL$R(T7$MN ( ( portTic)Type ) 6GGG ) con,'MI;IM(1$ST(CL$SIN7 ( ( nsi'ned short ) 6GG ) con,'TOT(1$M7(>$SIN7 ( ( siCe$t ) ( O ? 6G9O ) )

Ide,ne Ide,ne Ide,ne Ide,ne Ide,ne

First Technology Transfer - Feb 2013

23G

/ard&are De*endent Code - ctd0

/ard&are-de*endent code li(es in se*arate files for each com*iler toolchain and C#$ architect!re e0g0 For the 5AR com*iler on an ARM Cortex-M3 chi*

The hard&are-de*endent code li(es in the /ree(T0S/Source/portable/IA(/A(&1%&'6 directory0 portmacro h - declares all of the hard&are-s*ecific f!nctions port c and portasm s - contain all of the act!al hard&arede*endent code0 The hard&are-inde*endent header file portable h Yincl!de1s the correct portmacro h file at com*ile time0 FreeRT% calls the hard&are-s*ecific f!nctions !sing Ydefine1d f!nctions declared in portmacro h

First Technology Transfer - Feb 2013

23J

/ard&are De*endent F!nction - Exam*le

Mini excercise 9 Chec" to see &hether the follo&ing is really tr!e 00 The hard&are-inde*endent file tasks c fre;!ently needs to enter a critical section of code to *re(ent *reem*tion0 The details of entering a critical section are architect!re s*ecific tas"s0c hides the architect!re s*ecific details by calling the global macro port7;T7R$CRITIC(1()

/o& is this macro im*lemented > Mote9 5f e0g0 b!ilding FreeRT% !sing the 5AR com*iler targetting an ARM Cortex-M3 chi* - the macro is defined in 2reeRTOS/So rce/porta&le/I(R/(RM$CM%/portmacro.h &hich defines port7;T7R$CRITIC(1() as follo&s 9 Ide,ne port7;T7R$CRITIC(1() #>ort7nterCritical() #>ort7nterCritical() is act!ally defined in 2reeRTOS/So rce/porta&le/I(R/(RM$CM%/port.c The port c file is hard&are-de*endent2 and contains code that !nderstands the 5AR com*iler and the Cortex-M3 chi*0 #>ort7nterCritical() enters the critical section !sing this hard&ares*ecific im*lementation and ret!rns to the hard&are-inde*endent tasks c
280

First Technology Transfer - Feb 2013

/ard&are De*endent F!nction - Exam*le - ctd0

Mini excercise ctd0 Refresh yo!r "no&ledge of the di"" command $se the diff command to ex*lore the difference bet&een ARM Cortex M3 and ARM Cortex M8 *orts of FreeRT% by examining the differences bet&een the follo&ing files portasm.!

port.c portmacro.h

Mote9 Microsoft Fis!al t!dio 3Team Fo!ndation er(er4 edition has ;!ite extensi(e L$5 diff ca*abilities

Mote9 FreeRT% im*lements hard&are-de*endent f!nctionality &ith C *re*rocessor Ide,ne macros

$sed caref!lly it is *ossible to im*lement error free code The ma<or ad(antage is that ex*anding code inline red!ces f!nction call o(erheads

First Technology Transfer - Feb 2013

281

Tas" ched!ling - Tas" #riority

Each FreeRT% tas" has a2 !ser assigned2 *riority (al!e associated &ith it

Fal!es can range bet&een 0 3the lo&est *riority4 and the com*iletime (al!e of con,'M(H$>RIORITI7S-6 3the highest *riority40

FreeRT% !ses a :ready list: to "ee* trac" of all tas"s that are c!rrently ready to r!n0 5m*lemented as an array of tas" lists li"e this9 static !1ist p!ReadyTas)s1istsAcon,'M(H$>RIORITI7SB+

p!ReadyTas)s1istsAGA is a list of all ready *riority 0 tas"s2 p!ReadyTas)s1istsA6A is a list of all ready *riority 1 tas"s 000 !* to p!ReadyTas)s1istsAcon,'M(H$>RIORITI7S-6B

First Technology Transfer - Feb 2013

282

Tas" ched!ling - .essons from the Trenches

Read the follo&ing FreeRT% FA= Disc!ssion thread 9

The context &as *orting an 5AR b!ilt Cortex M3 exam*le to so as to com*ile it !sing gcc http:/ /www."reertos.or'/2reeRTOS$S pport$2or m$(rchi#e/(pril$9G69/"reert os$Ro nd$Ro&in$Sched lin'$P estions$K99QG9G.html Mote the (ario!s *oints made abo!t !sing tas)/elay() and tas)Jield()

)e &ill come bac" to these later

Mote also the final *art of the disc!ssion

I "o nd the so rce o" the pro&lem and it5s nothin' to do with the OS. ... I5m a"raid I had accidentally not placed my 'lo&al #aria&les in the 4SS section. (The 'lo&als were 'ettin' placed in COMMO; and I hadn5t added that section into my &ss section.) The reason there was a tho sands:6 ratio was . st that the #aria&les were not 'ettin' initialiCed to G. Once I ,!ed this, the ratio is #ery close to 6:6. SorryR I )eep relearnin' that I sho ld really in#esti'ate thoro 'hly &e"ore as)in' a - estion.
First Technology Transfer - Feb 2013 283

FreeRT% - ystem Tic"

The heartbeat of a FreeRT% system is the system tic"0 FreeRT% config!res the system to generate a *eriodic tic" interr!*t0 The tic" interr!*t fre;!ency is a config!rable *arameter Ty*ically in the millisecond range0

E(ery time the tic" interr!*t fires2 the #Tas)SwitchConte!t() f!nction is called

#Tas)SwitchConte!t(4 selects the highest-*riority ready tas" and *!ts it in the *xC!rrentTC- (ariable as follo&s 9

/? 2ind the hi'hest-priority - e e that contains ready tas)s. ?/ while ( list1IST$IS$7M>TJ( D( p!ReadyTas)s1istsA !TopReady>riority B ) ) ) * con,'(SS7RT( !TopReady>riority )+ -- !TopReady>riority+ 0 /? list:7T$O3;7R$O2$;7HT$7;TRJ wal)s thro 'h the list, so the tas)s o" the same priority 'et an e- al share o" the processor time. ?/ list:7T$O3;7R$O2$;7HT$7;TRJ( p!C rrentTC4, D( p!ReadyTas)s1istsA !TopReady>riority B ) )+
First Technology Transfer - Feb 2013 288

FreeRT% - ystem Tic" - ctd0

-efore the &hile loo* starts2 !TopReady>riority is g!aranteed to be greater than or e;!al to the *riority of the highest-*riority ready tas"0 The while() loo* starts at *riority le(el !TopReady>riority and &al"s do&n thro!gh the p!ReadyTas)s1istsAA array to find the highest-*riority le(el &ith ready tas"s0

list:7T$O3;7R$O2$;7HT$7;TRJ(4 then grabs the next ready tas" from that *riority le(el1s ready list0 )hen #Tas)SwitchConte!t(4 ret!rns the hard&are-de*endent code starts r!nning that tas"0 The remaining GJ00I lines of FreeRT% are the +s!**orting cast,

At that *oint p!C rrentTC4 *oints to the highest-*riority tas"2 and

The abo(e code is at the absol!te heart of FreeRT% 0

First Technology Transfer - Feb 2013

28?

FreeRT% - Ready .ist

First Technology Transfer - Feb 2013

28B

Tas" Control -loc"

The TC- is defined in tasks c

typede" str ct ts)Tas)Control4loc) * #olatile portST(CL$TJ>7 ?p!TopO"Stac)+ /? >oints location o" last item placed on the tas)s stac).
TMIS M8ST 47 TM7 2IRST M7M47R O2 TM7 STR8CT. ?/

!1istItem !:eneric1istItem+ /? 1ist item sed to place the TC4 in ready and &loc)ed - e es. ?/ !1istItem !7#ent1istItem+ /? 1ist item sed to place the TC4 in e#ent lists.?/ nsi'ned port4(S7$TJ>7 !>riority+ /? The priority tas) - G is the lowest priority. ?/ portST(CL$TJ>7 ?p!Stac)+ /? >oints to the start o" the stac). ?/ si'ned char pcTas);ameA con,'M(H$T(SL$;(M7$17; B+ /? /escripti#e name o" tas) 2acilitates de& ''in' only. ?/ Ii" ( portST(CL$:RO3TM E G ) portST(CL$TJ>7 ?p!7ndO"Stac)+ /? 8sed "or stac) o#erSow chec)in' on architect res Iendi" Ii" ( con,'8S7$M8T7H7S << 6 ) nsi'ned port4(S7$TJ>7 !4ase>riority+ /? The priority last assi'ned to the tas) sed &y the priority inheritance mechanism. ?/ Iendi" 0 ts)TC4+
where the stac) 'rows p "rom low memory. ?/

First Technology Transfer - Feb 2013

28C

Tas" Control -.oc" - ctd0

p!Stac) - holds the starting address of the stac" p!TopO"Stac) - holds the address of the c!rrent stac" to* p!7ndO"Stac) *oints to the end of the stac"

$sed to chec" for stac" o(erflo& in those systems &here the stac" gro&s :!*: to higher addresses0

5f the stac" gro&s :do&n: to lo&er addresses then stac" o(erflo& is chec"ed by com*aring the c!rrent to* of stac" against the start of stac" memory in p!Stac)

!>riority stores the *riority c!rrently assigned to the tas" its initial *riority is the *riority assigned to the tas" &hen first created !4ase>riority - !sed to remember the original *riority &hilst the tas" is tem*orarily ele(ated to the :inherited: *riority in *riority inheritance

First Technology Transfer - Feb 2013

28G

Tas" Control -.oc" - ctd0

The !1istItem member (ariables !:eneric1istItem and !7#ent1istItem are !sed in the im*lementation of the (ario!s FreeRT% sched!ling lists

)hen a tas" is inserted into a list

FreeRT% inserts a *ointer to either the TC-1s !:eneric1istItem or !7#ent1istItem

A tas" can be in one of fo!r states9 r!nning2 ready to r!n2 s!s*ended2 or bloc"ed0 FreeRT% does not store the state (al!e in a se*arate member (ariable

FreeRT% trac"s tas" state im*licitly by *!tting tas"s in the a**ro*riate list9 ready list2 s!s*ended list2 bloc"ed list The *resence of a tas" in a *artic!lar list indicates the tas"1s state0

As a tas" changes from one state to another2 FreeRT% sim*ly mo(es it from one list to another0

First Technology Transfer - Feb 2013

28J

#rocess tate Diagram

First Technology Transfer - Feb 2013

2?0

Tas" Creation and et!*

A tas" is created by calling the !Tas)Create() f!nction

A ne& TC- ob<ect is allocated to store the name2 *riority2 and other tas" attraib!tes Memory for the amo!nt of stac" re;!ested is allocated and the address of the start of the stac" memory is sa(ed in the TC-1s p!Stac) member0

The stac" is initiali'ed so that it &ill a**ear as if the ne& tas" is already r!nning and &as interr!*ted by a context s&itch0

This allo&s the sched!ler to treat the ne&ly created tas" in exactly the same &ay as it treats tas"s that ha(e been r!nning for a &hile

The sched!ler does not need any s*ecial case code for handling ne& tas"s0

The im*lementation details are architect!re de*endent e0g0 the code for an ARM Cortex-M3 *rocessor im*lementation is sho&n on the next fe& slides

First Technology Transfer - Feb 2013

2?1

Tas" Creation and et!* - ctd0


nsi'ned int ?p!>ortInitialiseStac)( nsi'ned int ?p!TopO"Stac), pdT(SL$CO/7 p!Code, #oid ?p#>arameters ) * /? Sim late the stac) "rame as it wo ld &e created &y a conte!t switch interr pt. ?/ p!TopO"Stac)--+ /? O""set added to acco nt "or the way the MC8 ses the stac) on entry/e!it o" interr pts. ?/ ?p!TopO"Stac) < portI;ITI(1$H>SR+ /? !>SR ?/ p!TopO"Stac)--+ ?p!TopO"Stac) < ( portST(CL$TJ>7 ) p!Code+ /? >C ?/ p!TopO"Stac)--+ ?p!TopO"Stac) < G+ /? 1R ?/ p!TopO"Stac) -< K+ /? R69, R%, R9 and R6. ?/ ?p!TopO"Stac) < ( portST(CL$TJ>7 ) p#>arameters+ /? RG ?/ p!TopO"Stac) -< Q+ /? R66, R6G, RT, RQ, RU, RV, RK and RO. ?/ ret rn p!TopO"Stac)+

First Technology Transfer - Feb 2013

2?2

Tas" Creation and et!* - ctd0

The ARM Cortex-M3 *rocessor *!shes registers on to the stac" &hen a tas" is interr!*ted0

p!>ortInitialiseStac)(4 modifies the stac" so that loo" as if the registers &ere *!shed e(en tho!gh the tas" has not act!ally started r!nning

Kno&n (al!es are stored to the stac" for the ARM registers x# R2 #C2 .R2 and R00 The remaining registers R1 -- R12 get stac" s*ace allocated for them by decrementing the to* of stac" *ointer2 b!t no s*ecific data is stored in the stac" for those registers0 The ARM architect!re doc!mentation states that those registers are !ndefined at reset2 so a 3non-b!ggy4 *rogram &ill not rely on ant "no&n (al!es

First Technology Transfer - Feb 2013

2?3

Tas" Creation and et!* - ctd0

After the stac" is set !* FreeRT% disables interr!*ts *rior to

Modifying the the ready lists and other sched!ler str!ct!res FreeRT% initiali'es the sched!ler1s tas" lists The lists for trac"ing tas"s that ha(e been s!s*ended2 "illed2 and delayed are also initialised at this *oint

5f this is the first tas" to e(er be created


After any first-time initiali'ation has been com*leted the ne& tas" is added to the ready list at its s*ecified *riority le(el Tas" creation is com*leted by re-enabling nterr!*ts

First Technology Transfer - Feb 2013

2?8

FreeRT% .ists

FreeRT% lists are ;!ite com*lex str!ct!res 9

First Technology Transfer - Feb 2013

2??

.ist tr!ct!res

The FreeRT% list is a standard circ!lar do!bly lin"ed list &ith some extra attrib!tes
/? The #al e &ein' listed. In most cases this is sed to sort the list in descendin' order. ?/ #olatile str ct !1IST$IT7M ? p!;e!t+ /? >ointer to ne!t !1istItem in the list. ?/ #olatile str ct !1IST$IT7M ? p!>re#io s+ /? >ointer to pre#io s !1istItem in the list. ?/ #oid ? p#Owner+ /? >ointer to the o&.ect (normally a TC4) that contains the list item. There is there"ore a two-way lin) &etween the o&.ect containin' the list item and the list item itsel". ?/ #oid ? p#Container+ /? >ointer to the list in which this list item is placed (i" any). ?/

str ct !1IST$IT7M * portTic)Type !Item@al e+

0+ typede" str ct !1IST * #olatile nsi'ned port4(S7$TJ>7 !; m&erO"Items+ #olatile !1istItem ? p!Inde!+ /? 8sed to wal) thro 'h the list. >oints to the last item ret rned &y a call to p#1ist:etOwnerO";e!t7ntry (). ?/ #olatile !Mini1istItem !1ist7nd+ /? 1ist item that contains the ma!im m possi&le item #al e, meanin' it is always at the end o" the list and is there"ore sed as a mar)er. ?/ 0 !1ist+

First Technology Transfer - Feb 2013

2?B

.ist tr!ct!res - ctd0

The list element !Item@al e is the !s!ally the *riority of the tas" being trac"ed or a timer (al!e for e(ent sched!ling0

.ists are "e*t in high-to-lo& *riority order i0e0

The highest-*riority !Item@al e 3the largest n!mber4 is at the front of the list and The lo&est *riority !Item@al e 3the smallest n!mber4 is at the end of the list0

The p!;e!t and p!>re#io s *ointers are standard lin"ed list *ointers0 p#Owner is a *ointer to the o&ner of the list element0

$s!ally a *ointer to a tas"1s TC- ob<ect0 p#Owner ma"es tas" s&itching fast in #Tas)SwitchConte!t()

%nce the highest-*riority tas"1s list element is fo!nd in p!ReadyTas)s1istsAB2 that list element1s p#Owner *ointer leads !s directly to the TC- needed to sched!le the tas"0

First Technology Transfer - Feb 2013

2?C

.ist tr!ct!res - ctd0

p#Container *oints to the list that the item is in The list handle str!ct!re2 !1ist2 can be !sed to ;!ic"ly determine if a list item is in a *artic!lar list

!; m&erO"Items holds the si'e of the list All ne& lists are initiali'ed to contain a single element - the !1ist7nd element

!1ist7nd.!Item@al e is a sentinel (al!e &hich is e;!al to the largest (al!e for the !Item@al e (ariable9

G!"""" &hen portTic)Type is a 1B-bit (al!e and G!"""""""" &hen portTic)Type is a 32-bit (al!e The insertion algorithm ens!res that x.istEnd is al&ays the last item in the list0

ince lists are sorted high-to-lo&2 the !1ist7nd element is !sed as a mar"er for the start of the list0 ince the list is circ!lar2 this !1ist7nd element is also a mar"er for the end of the list0

First Technology Transfer - Feb 2013

2?G

Mini Exercise

Examine the f!nction list:7T$O3;7R$O2$;7HT$7;TRJ()


/o& does it do its &or" > )here is it called from > /o& does it do &ra* aro!nd detection > )hich lists does it mani*!late and ho& > )hen is it called >

Examine the f!nction #Tas)SwitchConte!t()


First Technology Transfer - Feb 2013

2?J

-asic M!lti-Tas"ing

The basic *attern is (ery sim*le

5ts the details that are hard Define the f!nctions that &ill form the basis of the (ario!s tas"s Create tas" instances

-asic *attern 9

#ossible tas" instance combinations Each tas" r!ns a !ni;!e f!nction and has a !ni;!e *riority M!lti*le tas"s r!nning the same f!nction and m!lti*le tas"s r!nning at the same *riority le(el are *ossible tart !* the tas" sched!ler

First Technology Transfer - Feb 2013

2B0

-asic M!lti-Tas"ing

/o& does one go abo!t assigning &or" to different tas"s > /o& does one go abo!t assigning *riorities to tas"s > /o& does one decide ho& m!ch stac" s*ace a gi(en tas" sho!ld ha(e > 5s it a good idea to share memory bet&een tas"s >

5s a +-lac"board #attern, a**roach s!itable for embedded systems > )hat abo!t an +%bser(er #attern, > #rod!cer - Cons!mer Readers and )riters )or"cre& *attern Tas" *ools
2B1

ome common m!lti-tas"ing scenarios


First Technology Transfer - Feb 2013

-asic M!lti-Tas"ing Tem*late

For act!al details for different *rocessors and a (ariety of exam*les st!dy the (ario!s *orts and exam*le *ro<ects that come &ith the FreeRT% do&nload2 or that are a(ailable from the chi* (endors 6 5DE (endors 3Keil2 5AR2 Ro&ley2 0004

/? Iincl des and Ide,nes section ?/ ... /? The tas) " nction " nction prototypes ?/ #oid #Tas)6( #oid ?p#>arameters )+ #oid #Tas)9( #oid ?p#>arameters )+ int main( #oid ) * /? Call appropriate con,' ration and initialisation " nctions ?/ ... /? Create the speci,ed tas)s. ?/ ... !Tas)Create( #Tas)6, /? >ointer to the " nction that implements the tas). ?/ WTas) 6W, /? Te!t name "or the tas). This is to "acilitate de& ''in' only. ?/ 9KO, /? Stac) depth in words. ?/ ;811, /? ;811 i"" not sin' the tas) parameter. ?/ 6, /? Tas) priority le#el ?/ ;811 )+ /? ;811 i" not sin' the tas) handle. ?/ /? Create the other tas)s similarly ?/ !Tas)Create( #Tas)9, WTas) 9W, 9KO, ;811, 6, ;811 )+ #Tas)StartSched ler()+ /? Tas)s now e!ec tin' ?/ "or( ++ ) + /? Sa"ety net ... ?/ 0
First Technology Transfer - Feb 2013 2B2

Leneral )ords of Ad(ice

5t is a good idea to start a ne& FreeRT% *ro<ect by basing it on one of the *ro(ided *re-config!red demos0

This sho!ld ens!re that


The ne& *ro<ect incl!des all the necessary so!rce and header files2 and That it installs the necessary interr!*t ser(ice ro!tine

A FreeRT% a**lication &ill start !* and exec!te <!st li"e a non-RT% a**lication !ntil #Tas)StartSched ler() is called0

#Tas)StartSched ler() is normally called from the a**lication1s main() f!nction0 The RT% only controls the exec!tion se;!encing after #Tas)StartSched ler() has been called0 Let the code for the (ario!s tas"s exec!ting correctly 3correct start !* code2 correct lin"er config!ration2 etc04 on the chosen target before attem*ting to !se any RT% f!nctionality0

First Technology Transfer - Feb 2013

2B3

FreeRT%

o!rce Files

At a minim!m2 the follo&ing so!rce files ha(e to be incl!ded in e(ery FreeRT% *ro<ect9 2reeRTOS/So rce/tas)s.c 2reeRTOS/So rce/- e e.c 2reeRTOS/So rce/list.c 2reeRTOS/So rce/porta&le/AcompilerB/Aarchitect reB/port.c. 2reeRTOS/So rce/porta&le/MemMan'/heap$!.c where 5!5 is 6, 9, % or O.

5f the directory that contains the port.c file also contains an assembly lang!age file2 then the assembly lang!age file has to be !sed also0 )here soft&are timer f!nctionality is re;!ired then incl!de 2reeRTOS/So rce/timers.c 5f !sing co-ro!tine f!nctionality2 incl!de FreeRTOS/So rce/cro tine.c The directories for the follo&ing header files m!st be in the com*iler1s incl!de *ath

2reeRTOS/So rce/incl de 2reeRTOS/So rce/porta&le/AcompilerB/Aarchitect reB

De*ending on the *ort2 it may also be necessary for the same directories to be in the assembler1s incl!de *ath0
2B8

First Technology Transfer - Feb 2013

Config!ration File

E(ery *ro<ect m!st ha(e a 2reeRTOSCon,'.h

2reeRTOSCon,'.h tailors the RT% "ernel to the a**lication being b!ilt0


5t is *ecific to the a**lication2 not the RT% 2 and ho!ld be *laced in an a**lication directory

5f hea*O12 hea*O22 or hea*O8 is incl!ded in the *ro<ect2 then2 in 2reeRTOSCon,'.h !se the definition con,'TOT(1$M7(>$SIN7 to dimension the FreeRT% hea*

Mote9 An a**lication &ill not lin" if con,'TOT(1$M7(>$SIN7 is set too high0

The definition con,'MI;IM(1$ST(CL$SIN7 sets the si'e of the stac" !sed by the idle tas"0

5f con,'MI;IM(1$ST(CL$SIN7 is set too lo&2 then the idle tas" &ill generate stac" o(erflo&s

5nterr!*t Fectors 9

The method !sed to install the interr!*t handlers *ro(ided by the RT% *ort is de*endent on the *ort and com*iler being !sed

$se the +official, demo a**lication for the *ort being !sed as a starting *oint
2B?

First Technology Transfer - Feb 2013

AM8 H#.A5MED - tarter .ab

The AM8 H#.A5MED board is a lo& cost CortexM8 e(al!ation board *rod!ced by Atmel for e(al!ating their ARM CortexM8 *rocessor technology Atmel1s o&n 5DE Atmel t!dio B !ses a gcc based com*iler and a Microsoft Fis!al t!dio based front end0 Atmel *ro(ides a &hole lot of exam*les (ia its A F 3Atmel oft&are Frame&or"4 reso!rces

These come b!ndled &ith Atmel t!dio B2 or can be do&nloaded se*arately The se*arately do&nloaded exam*les contain 5AR *ro<ects as &ell as LCC *ro<ects

5t is often a good idea2 &hen starting to ne& embedded systems to ha(e a n!mber of tool"its and com*ilers a(ailable

ometimes2 *roblems arising &ith one toolchain do not arise &ith a different toolchain and (ice (ersa At some *oint2 ty*ically2 one or other of the toolchains is selected as the basis for the final *rod!ct

First Technology Transfer - Feb 2013

2BB

AM8 H#.A5MED - tarter .ab - #art 1

#art 1- &ill !se Atmel t!dio B as the 5DE

This is a free 5DE and the *hiloso*hy is


5f it is good eno!gh for Atmel it is *robably good eno!gh for me 5t sho!ld be easier to get the Atmel exam*les r!nning !sing this 5DE as o**osed to some other 5DE e0g0 5AR2 Keil2 Attolic To be able to do&nload code to the target board and also to be able to deb!g code it is necessary to do&nload and install the a**ro*riate tools and dri(ers from egger

The AM8 ex*lained board contains a 7TAL s!bsystem that !ses egger technology

%n examining the AM8 H#.A5MED board yo! &ill obser(e that it has t&o $ - interfaces

A $ - interface to the 7TAL s!bsystem A $ - interface for $ - de(ice a**lications de(elo*ed on the target

The exercise in(ol(es

Com*iling and r!nning a sim*le exam*le that flashes some .EDs

The fre;!ency of .ED flashing changes &hen different sections of the to!ch slider are to!ched

Com*iling a FreeRT% exam*le that *rograms the board to f!nction as a dis" dri(er 5m*lementing a FreeRT% based .ED flashing a**lication
2BC

First Technology Transfer - Feb 2013

AM8 H#.A5MED - tarter .ab - #art 1

5n Atmel t!dio B create and r!n t&o AM8 H#.A5MED A F *ro<ects

The first *ro<ect to create is the getting started *ro<ect 000 this basically !tilises t&o .EDs and the to!ch slider 00 De*ending on &here yo! to!ch the slider the rate of .ED blin"ing &ill change The second *ro<ect is the basic FreeRT% *ro<ect &hich in(ol(es *rogramming the de(ice so that &hen connected as a de(ice to the #C it &ill a**ear as a dis" dri(e 00

Test o!t the de(ice 5n &hich "ind of memory is the filesystem created > )hat ha**ens &hen the *rogram is reset >

First Technology Transfer - Feb 2013

2BG

AM8 H#.A5MED - tarter .ab - #art 1

Mo& yo! "no& that yo! can get .EDs to flash2 and a FreeRT% *ro<ect to com*ile0 Wo!r challenge is to create a FreeRT% a**lication as follo&s

5m*lement a f!nction that flashes an .ED !sing a b!sy &ait a**roach Create t&o tas"s %ne tas" flashes one .ED The other tas" flashes the other .ED The *arameter *assed into the tas" create call s*ecifies &hich .ED to flash and at &hat rate0

First Technology Transfer - Feb 2013

2BJ

AM8 H#.A5MED - tarter .ab - #art 2

The Atmel A F exam*les do&nloaded se*arately from Atmel t!dio B contain se(eral 5AR exam*les for the AM8 H#.A5MED board

A flashing .ED exam*le A FreeRT% exam*le

The goal is to get both these exam*les to com*ile and r!n2 and then To com*lete the same challenge as *osed in #art 12 exce*t2 this time !sing the 5AR 5DE

First Technology Transfer - Feb 2013

2C0

Tas" Management Ex*lored in Lreater Detail

First Technology Transfer - Feb 2013

2C1

Tas" tates and Transitions

The basic state diagram is sho&n belo& 9

First Technology Transfer - Feb 2013

2C2

Tas" #riorities

Conce*t!al o!tline of tas" *riority lists 000

First Technology Transfer - Feb 2013

2C3

xTas"Create

Tas"s are created (ia xTas"Create - &hich has the follo&ing f!nction *rototy*e port4(S7$TJ>7 !Tas)Create ( pdT(SL$CO/7 p#Tas)Code, const portCM(R ? const pc;ame, nsi'ned portSMORT sStac)/epth, #oid ?p#>arameters, nsi'ned port4(S7$TJ>7 !>riority, !Tas)Mandle ?p#CreatedTas) )+

p#Tas)Code - #ointer to the tas" entry f!nction0

Tas"s m!st be im*lemented to ne(er ret!rn 3i0e0 contin!o!s loo*40

pc;ame - Descri*ti(e name for the tas"0

$sed mainly to facilitate deb!gging

Max length defined by con,'M(H$T(SL$;(M7$17;

First Technology Transfer - Feb 2013

2C8

xTas"Create - ctd0

sStac)/epth - si'e of the tas" stac" *ecified as the n!mber of (ariables the stac" can hold - not the n!mber of bytes e0g0 5f the stac" is 32 bits &ide and !s tac"De*th is defined as 1002 800 bytes &ill be allocated for stac" storage0 tac" de*th m!lti*lied by stac" &idth m!st not exceed the maxim!m (al!e that can be contained in a (ariable of ty*e siCe$t p#>arameters - #ointer !sed as the *arameter for the tas" being created0 !>riority - The *riority at &hich the tas" sho!ld r!n0 ystems that incl!de M#$ s!**ort can o*tionally create tas"s in a *ri(ileged 3system4 mode by setting bit port>RI@I17:7$4IT of the *riority *arameter e00

To create a *ri(ileged tas" at *riority 2 the !>riority *arameter sho!ld be set to 3 9 X port>RI@I17:7$4IT 40

p#CreatedTas) - $sed to *ass bac" a handle by &hich the created tas" can be referenced0 xTas"Create ret!rns

pd>(SS if the tas" &as s!ccessf!lly created and added to a ready list An error code defined in the file pro.de"s. h other&ise
2C?

First Technology Transfer - Feb 2013

xTas"Create - Tem*late ni**et

The basic xTas"Create !sage *attern is sho&n belo& 9


/? Tas) wor) " nction ?/ #oid #Tas)Code( #oid ? p#>arameters ) * "or( ++ ) * /? Tas) wor) ... ?/ 0 0 /? 2 nction to create a tas) .. ?/ #oid #Other2 nction( #oid ) * static nsi'ned char c>arameterTo>ass+ !Tas)Mandle !Mandle+ /? ;ote that the parameter c>arameterTo>ass m st e!ist "or the li"etime o" the tas) hence declared as static ?/ !Tas)Create( #Tas)Code, W;(M7W, ST(CL$SIN7, D c>arameterTo>ass, ts)I/17$>RIORITJ, D!Mandle )+ /? 8se the handle to delete the tas). ?/ #Tas)/elete( !Mandle )+ 0

First Technology Transfer - Feb 2013

2CB

5dle Tas"

The 5dle Tas" is created a!tomatically &hen the RT% sched!ler is started at the lo&est *ossible *riority The idle tas" is res*onsible for freeing memory allocated by the RT% to tas"s that ha(e since been deleted

A**lications that in(o"e #Tas)/elete() sho!ld ens!re that the idle tas" is not star(ed of *rocessing time &hen it is called !*on to free !* reso!rces

The idle tas" can legitimately be star(ed of microcontroller time !nder all other conditions

5t is *ossible for a**lication tas"s to share the idle tas" *riority 3ts)I/17$>RIORITJ4

Enabled by setting the con,'I/17$SMO81/$JI71/ config!ration *arameter to 1

5n this case the idle tas" &ill yield immediately sho!ld any other tas" at the idle *riority be ready to r!n

An alternati(e to ha(ing se(eral tas"s r!nning at idle *riority is the follo&ing9

et config5D.EO /%$.DOW5E.D to 00 $se an idle hoo" in *lace of se*arate tas"s at the idle *riority0 Create all a**lication tas"s at a *riority greater than the idle *riority0

First Technology Transfer - Feb 2013

2CC

5dle Tas" /oo"

An idle tas" hoo" is a f!nction that is called d!ring each cycle of the idle tas"0 5t is a mechanism that can be !sed to add extra f!nctionality to the idle tas"

-eca!se there m!st al&ays be at least one tas" that is ready to r!n the hoo" f!nction m!st not call any A#5 f!nctions that co!ld ca!se the idle tas" to bloc" e0g0

#Tas)/elay()2 or a ;!e!e or sema*hore f!nction &ith a bloc" time Mote9 co-ro!tines can bloc" &ithin the hoo" f!nction0

To create an idle hoo"9

et con,'8S7$I/17$MOOL to 1 in 2reeRTOSCon,'.h Define a f!nction that has the follo&ing name and *rototy*e9

#oid #(pplicationIdleMoo)( #oid )+

A common !se case of the idle hoo" f!nction is to *!t the microcontroller C#$ into a *o&er sa(ing mode0

First Technology Transfer - Feb 2013

2CG

Tas" /oo"

Tas" hoo" f!nctions are in(o"ed (ia a call to port4(S7$TJ>7 !Tas)Call(pplicationTas)Moo) ( !Tas)Mandle !Tas), #oid ?p#>arameter )+

con,'8S7$(>>1IC(TIO;$T(SL$T(: m!st be defined as 1 for this f!nction to be a(ailable A 1tag1 (al!e can be assigned to each tas"0

Mormally the (al!e is for the !se of the a**lication only and the RT% "ernel does not access it0 /o&e(er2 it is *ossible to !se the tag to assign a hoo" 3or callbac"4 f!nction to a tas" - the hoo" f!nction being exec!ted by callin xTas"CallA**licationTas"/oo"340 Each tas" can define its o&n callbac"2 or none at all0

First Technology Transfer - Feb 2013

2CJ

Tas" /oo"

Altho!gh it is *ossible to !se the first f!nction *arameter to call the hoo" f!nction of any tas"2 the most common !se of a tas" hoo" f!nction is &ith the FreeRT% trace hoo" macros Tas" hoo" f!nctions m!st ha(e ty*e pdT(SL$MOOL$CO/72 i0e0

Ta"e a #oid ? *arameter2 and ret!rn a (al!e of ty*e port4(S7$TJ>7 The #oid ? *arameter can be !sed to *ass any information into the hoo" f!nction0 The *arameters ha(e the follo&ing meanings 9

!Tas) - the handle of the tas" &hose hoo" f!nction is being called0 #assing M$.. as !Tas) &ill call the hoo" f!nction associated &ith the c!rrently exec!ting tas"0 p#>arameter - the (al!e to *ass to the hoo" f!nction 5t can be a *ointer to a str!ct!re2 or a n!meric (al!e0

First Technology Transfer - Feb 2013

2G0

Tas" /oo" - Tem*late Code ni**et

The follo&ing code fragment ill!strates the tas" hoo" !sage *attern 9
/? /e,ne the call&ac) " nction e.'. ?/ static port4(S7$TJ>7 pr#7!ampleTas)Moo)( #oid ? p#>arameter ) * /? >er"orm some action - e.'. lo''in' a #al e, pdatin' the tas) state, o tp ttin' some #al e, etc. ?/ ret rn G+ 0 /? /e,ne the tas) that sets pr#7!ampleTas)Moo) as its hoo)/ta' #al e &y re'isterin' the Tas) Moo) at the start o" this tas) " nction e.'. ?/ #oid #SomeTas)( #oid ?p#>arameters ) * /? Re'ister o r call&ac) " nction. ?/ #Tas)Set(pplicationTas)Ta'( ;811, 7!ampleTas)Moo) )+ "or( ++ ) * /?Tas) wor) ... ?/ 0

First Technology Transfer - Feb 2013

2G1

Tas" Management A#5s

The Tas" Management A#5 f!nctions can be gro!*ed into three *arts Creation f!nctions

$tility f!nctions

ts"5D.EO#R5%R5TW xTas"LetTic"Co!nt !xTas"LetM!mber%fTas"s (Tas".ist (Tas"LetR!nTime tats (Tas" tartTrace !lTas"EndTrace !xTas"Let tac"/igh)aterMar" (Tas" etA**licationTas"Tag xTas"LetA**licationTas"Tag xTas"CallA**licationTas"/oo"

xTas"Create (Tas"Delete

Control f!nctions

(Tas"Delay (Tas"Delay$ntil !xTas"#riorityLet (Tas"#riority et (Tas" !s*end (Tas"Res!me xTas"Res!meFrom5

First Technology Transfer - Feb 2013

2G2

vTask"elete()

!Tas)Create() and #Tas)/elete() ha(e already been co(ered #oid #Tas)/elete( !Tas)Mandle !Tas) )+

I;C18/7$#Tas)/elete m!st be defined as 1 for the f!nction to be a(ailable Remo(es a tas" from the RT% "ernels management The tas" being deleted is remo(ed from all ready2 bloc"ed2 s!s*ended and e(ent lists0 Mote9 Memory allocated by the tas" code is not a!tomatically freed2 and sho!ld be freed before the tas" is deleted0 Mote9 The demo exam*le death.c demonstrates the

Dynamic creation of tas"s 3at r!n time4 Deletion of tas"s The *assing of *arameters to tas"s

First Technology Transfer - Feb 2013

2G3

vTask"elay()

#oid #Tas)/elay( portTic)Type !Tic)sTo/elay )+

I;C18/7$#Tas)/elay m!st be defined as 1 for the f!nction to be a(ailable0

Delays a tas" for the s*ecified n!mber of tic"s0 The act!al time that the tas" remains bloc"ed de*ends on the tic" rate0 The constant portTICL$R(T7$MS can be !sed to calc!late the real time delay from the tic" rate To a resol!tion of one tic" *eriod0 *ecifies a time at &hich the tas" &ishes to !nbloc" relati(e to the time at &hich #Tas)/elay() is called Does not *ro(ide a good method of controlling the fre;!ency of a cyclical tas" as The exec!tion *ath ta"en thro!gh the code2 and other tas" and interr!*t acti(ity2 &ill effect the fre;!ency at &hich (Tas"Delay34 gets called

-etter to !se #Tas)/elay8ntil() 2 &hich s*ecifies an absol!te time 3rather than a relati(e time4 at &hich the calling tas" sho!ld !nbloc"0 The exam*le flash0c demonstrates Delaying2 as &ell as #assing *arameters and creating tas"s
2G8

First Technology Transfer - Feb 2013

vTask"elay2ntil()

#oid #Tas)/elay8ntil( portTic)Type ?p!>re#io s3a)eTime, portTic)Type !TimeIncrement )+

I;C18/7$#Tas)/elay8ntil m!st be defined as 1 for the f!nction to be a(ailable0 Delays a tas" !ntil a s*ecified time0

Can be !sed by cyclical tas"s to ens!re a constant exec!tion fre;!ency0 *ecifies the absol!te 3exact4 time at &hich it &ishes to !nbloc"0 )ill ret!rn immediately 3&itho!t bloc"ing4 if !sed to s*ecify a &a"e time that is already in the *ast0

A tas" !sing #Tas)/elay8ntil() to exec!te *eriodically m!st re-calc!late its re;!ired &a"e time if the *eriodic exec!tion is halted for any reason 3e0g0 if the tas" is tem*orarily *laced into the !s*ended state4 ca!sing the tas" to miss one or more *eriodic exec!tions0 Detect by chec"ing the (ariable *assed by reference as the p!>re#io s3a)eTime *arameter against the c!rrent tic" co!nt M!st not be called &hile the RT% sched!ler has been s!s*ended by a call to #Tas)S spend(ll()

First Technology Transfer - Feb 2013

2G?

vTask"elay2ntil() $ ctd0

#arameters9

p!>re#io s3a)eTime - *ointer to (ariable holding the time at &hich the tas" &as last !nbloc"ed0 The (ariable m!st be initialised &ith the c!rrent time *rior to its first !se

Thereafter the (ariable is a!tomatically !*dated &ithin #Tas)/elay8ntil() - the cycle time *eriod0

!TimeIncrement

The tas" &ill be !nbloc"ed at time (?p!>re#io s3a)eTime = !TimeIncrement)0 Calling #Tas)/elay8ntil &ith the same !TimeIncrement *arameter (al!e &ill res!lt in a tas" r!nning &ith a fixed inter(al *eriod e0g0

/ / >er"orm an action e#ery 6G tic)s. #oid #Tas)2 nction( #oid ? p#>arameters ) * portTic)Type !1ast3a)eTime+ const portTic)Type !2re- ency < 6G+ / / Initialise !1ast3a)eTime with the c rrent time. !1ast3a)eTime < !Tas):etTic)Co nt()+ "or( ++ ) * / / 3ait "or ne!t cycle. #Tas)/elay8ntil( D!1ast3a)eTime, !2re- ency )+ / / /o somethin' ... 0 0
First Technology Transfer - Feb 2013 2GB

!s*ending and Res!ming Tas"s


Tas"s can be s!s*ended and res!med as necessary #oid #Tas)S spend( !Tas)Mandle !Tas)ToS spend )+

!s*ends the tas" A s!s*ended a tas" &ill not get any more *rocessing time Calls to #Tas)S spend are not acc!m!lati(e - i0e0

Calling #Tas)S spend () t&ice on the same tas" still only re;!ires one call to #Tas)Res me () to ready the s!s*ended tas"0

I;C18/7$#Tas)S spend m!st be defined as 1 for this f!nction to be a(ailable

#oid #Tas)Res me( !Tas)Mandle !Tas)ToRes me )+ Res!mes the tas" 5MC.$DEO(Tas" !s*end m!st be defined as 1 for this f!nction to be a(ailable The dynamic0c exam*le demonstrates

#assing *arameters into a tas" Dynamically changing *riorities !s*ending tas"s !s*ending the RT% sched!ler

First Technology Transfer - Feb 2013

2GC

Res!ming a Tas" from an 5 R


5 R code sho!ld be of short d!ration and m!st not bloc" There are $se Cases for &hich res!ming a tas" from an 5 R ma"es sense e0g 5f an emergency b!tton - &hich triggers an edge le(el based interr!*t on the corres*onding 56% *in is *ressed then the tas" that carries o!t the emergency sh!tdo&n *roced!re sho!ld be called immediately There is no reason to sched!le s!ch a tas" other&ise port4(S7$TJ>7 !Tas)Res me2romISR( !Tas)Mandle !Tas)ToRes me )+

Res!mes a s!s*ended tas" Can be called from &ithin an 5 R Ret!rns pdTR87 if res!ming the tas" sho!ld res!lt in a context s&itch2 other&ise *dFA. E

$sed by the 5 R to determine if a context s&itch may be re;!ired follo&ing the 5 R0

I;C18/7$#Tas)S spend and I;C18/7$!Tas)Res me2romISR m!st both be defined as 1 for this f!nction to be a(ailable0

Mote9 A tas" that has been s!s*ended by one of more calls to #Tas)S spend() &ill be made a(ailable for r!nning again by a single call to !Tas)Res me2romISR()0 Mote9 !Tas)Res me2romISR() sho!ld not be !sed to synchronise a tas" &ith an interr!*t if there is a *ossibility that the interr!*t co!ld arri(e *rior to the tas" being s!s*ended $nder s!ch circ!mstances a sema*hore sho!ld be !sed as a synchronisation mechanism

First Technology Transfer - Feb 2013

2GG

Res!ming a Tas" from an 5 R - ctd0

The follo&ing code tem*late sni**et ill!strates a ty*ical code *attern for res!ming a tas" from an 5 R
!Tas)Mandle !Mandle+ #oid #(2 nction( #oid ) * / / Create a tas), storin' the handle. !Tas)Create( #Tas)Code, W;(M7W, ST(CL$SIN7, ;811, ts)I/17$>RIORITJ, D!Mandle )+ / / ... Rest o" code. 0 #oid #Tas)Code( #oid ?p#>arameters ) * / / The tas) &ein' s spended and res med. "or( ++ ) * / / ... >er"orm some " nction here. #Tas)S spend( ;811 )+ / / The tas) s spends itsel". / / The tas) is now s spended, so will not contin e ntil the ISR res mes it. 0 0 #oid #(n7!ampleISR( #oid ) * port4(S7$TJ>7 !JieldRe- ired+ !JieldRe- ired < !Tas)Res me2romISR( !Mandle )+ / / Res me the s spended tas). i"( !JieldRe- ired << pdTR87 ) * / / Switch conte!t so the ISR ret rns to a di""erent tas) details depend on the port / / ;OT7: Mow this is done depends on the port yo are sin'. Chec) portJI71/$2ROM$ISR()+ 0 0

First Technology Transfer - Feb 2013

2GJ

Collecting R!n Time 5nformation

#olatile portTic)Type !Tas):etTic)Co nt( #oid )+


Cannot be called from an 5 R Ret!rns - the n!mber of tic"s since #Tas)StartSched ler &as called0 Can be called from an 5 R0 Ret!rns - the n!mber of tic"s since #Tas)StartSched ler &as called0 Ret!rns - the n!mber of tas"s that the RT% "ernel is c!rrently managing0 Ready tas"s I bloc"ed tas"s I s!s*ended tas"s I tas"s deleted b!t not yet freed by the idle tas" .ists all the c!rrent tas"s2 along &ith their c!rrent state and stac" !sage high &ater mar"0

#olatile portTic)Type !Tas):etTic)Co nt2romISR( #oid )+


nsi'ned port4(S7$TJ>7 !Tas):et; m&erO"Tas)s( #oid )+


#oid #Tas)1ist( portCM(R ?pc3rite4 ""er )+

Tas"s are re*orted as bloc"ed 31-142 ready 31R142 deleted 31D14 or s!s*ended 31 140

con,'8S7$TR(C7$2(CI1ITJ m!st be defined as 1 for this f!nction to be a(ailable Disables interr!*ts for its d!ration0

Mot intended for normal a**lication r!ntime !se b!t as a deb!g aid0

#arameter - pc3rite4 ""er - a b!ffer into &hich the details &ill be &ritten2 in ascii form

ho!ld be large eno!gh to contain the o!t*!t - a**rox2 80 bytes *er tas" %K
2J0

First Technology Transfer - Feb 2013

Collecting R!n Time 5nformation - ctd0

#oid #Tas):etR nTimeStats( portCM(R ?pc3rite4 ""er )+

con,':7;7R(T7$R8;$TIM7$ST(TS m!st be defined as 1 for this f!nction to be a(ailable0 The a**lication m!st *ro(ide definitions for

portCO;2I:8R7$TIM7R$2OR$R8;$TIM7$ST(TS()

Config!res a *eri*heral timer6co!nter

port:7T$R8;$TIM7$CO8;T7R$@(187

Ret!rns the timers c!rrent co!nt (al!e res*ecti(ely0 The co!nter sho!ld be r!nning at at least 10 times the fre;!ency of the tic" co!nt0 )ill disable interr!*ts for its d!ration0 5ntended as a deb!g aid0

etting con,':7;7R(T7$R8;$TIM7$ST(TS to 1 &ill res!lt in a total acc!m!lated exec!tion time being stored for each tas"0 The pc3rite4 ""er - m!st be large eno!gh to hold the 3ascii text4 o!t*!t

A**rox 80 bytes *er tas" %K


2J1

First Technology Transfer - Feb 2013

Tracing Tas"s

Tas" tracing !sed to ma"e !se of the f!nctions #Tas)StartTrace and t!rned off &ith lTas)7ndTrace

C!rrently tas" tracing sho!ld ma"e !se of the Trace /oo" Macros &hich can be !sed to e0g0

et a digital o!t*!t to indicate &hich tas" is exec!ting - allo&ing e0g0 a logic analy'er to be !sed to (ie& and record the tas" exec!tion se;!ence and timing0 et an analog!e o!t*!t to a (oltage that re*resents &hich tas" is exec!ting allo&ing an oscillosco*e to be !sed to (ie& and record the tas" exec!tion se;!ence and timing0 .og tas" exec!tion se;!ences2 tas" timing2 RT% "ernel e(ents and A#5 calls for offline analysis0 5ntegrate RT% "ernel e(ents into third *arty deb!ggers0

Macros called from &ithin interr!*ts2 es*ecially the tic" interr!*t2 m!st be fast and !se little stac" s*ace Macro definitions m!st occ!r before the incl!sion of FreeRT% 0h0

First Technology Transfer - Feb 2013

2J2

Tas" Tags

Tas" tags are sim*ly labels associated &ith tas"s

The getter and setter methods are2 res*ecti(ely


!Tas):et(pplicationTas)Ta' #Tas)Set(pplicationTas)Ta' A 1tag1 is for the !se of the a**lication only


A 1tag1 (al!e can be assigned to each tas"0

5t is not !sed by the RT% 5t is ty*ically !sed in (ario!s RT% trace macros pdT(SL$MOOL$CO/7 p!Ta'@al e )+

#oid #Tas)Set(pplicationTas)Ta'( !Tas)Mandle !Tas), con,'8S7$(>>1IC(TIO;$T(SL$T(: m!st be defined as 1 for this f!nction to be a(ailable Ta"es t&o arg!ments

!Tas) - the handle of the tas" to &hich a tag (al!e is being assigned0

#assing !Tas) as M$.. ca!ses the tag to be assigned to the calling tas"0 %f ty*e pdT(SL$MOOL$CO/7 to *ermit a f!nction *ointer to be assigned as the tag2 altho!gh any (al!e can act!ally be assigned0
2J3

p!Ta'@al e - the (al!e being assigned to the tas" tag0

First Technology Transfer - Feb 2013

Tas" Tags

pdT(SL$MOOL$CO/7 !Tas):et(pplicationTas)Ta'( !Tas)Mandle !Tas) )+

con,'8S7$(>>1IC(TIO;$T(SL$T(: m!st be defined as 1 for this f!nction to be a(ailable0 Ret!rns the ZtagU (al!e associated &ith a tas"0 The meaning and !se of the tag (al!e is defined by the a**lication &riter0 Ta"es one arg!ment - !Tas) - the handle of the tas" being ;!eried0

A tas" can ;!ery its o&n tag (al!e by !sing M$.. as the *arameter (al!e0

#oid #(Tas)( #oid ?p#>arameters ) * #Tas)Set(pplicationTas)Ta'( ;811, ( #oid ? ) 6 )+ "or( ++ ) * /? Rest o" tas) code 'oes here. ?/ 0 0 #oid #(2 nction( #oid ) * !Tas)Mandle !Mandle+ int iRet rnedTas)Mandle+ i"( !Tas)Create ( #(Tas), W/emo tas)W, ST(CL$SIN7, ;811, T(SL$>RIORITJ, D!Mandle ) << pd>(SS ) * #Tas)/elay( 6GG )+ iRet rnedTas)Mandle < ( int )!Tas):et(pplicationTas)Ta'( !Mandle )+ 0 0
First Technology Transfer - Feb 2013 2J8

etting $* .ogging &ith Tags

im*le exam*le belo& ets an a**lication tas" tag Defines a tracing macro to o!t*!t a (oltage associated &ith the tas"
#oid #Tas)6( #oid ?p#>arameters ) * /? 2irst tas) sets its ta' #al e to 6. ?/ #Tas)Set(pplicationTas)Ta'( ;811, ( #oid ? ) 6 )+ /?This tas) to &e represented &y#olta'e scale o" 6?/ "or( ++ ) * /? Tas) code 'oes here. ?/ 0

/? Second tas) sets its ta' #al e to 9. ?/ #oid #Tas)6( #oid ?p#>arameters ) * #Tas)Set(pplicationTas)Ta'( ;811, ( #oid ? ) 9 )+ /?This tas) to &e represented &y#olta'e scale o" 9?/ "or( ++ ) * /? Tas) code 'oes here. ?/ 0 0 /? /e,ne the traceT(SL$S3ITCM7/$I;() macro to o tp t the #olta'e associated with the tas) &ein' selected to r n on port G. ?/ Ide,ne traceT(SL$S3ITCM7/$I;() #Set(nalo' eO tp t( G, ( int ) p!C rrentTC4-Ep!Tas)Ta' )
First Technology Transfer - Feb 2013 2J?

Letting the tac" )atermar"

nsi'ned port4(S7$TJ>7 !Tas):etStac)Mi'h3aterMar) ( !Tas)Mandle !Tas) )+

Ret!rns the minim!m amo!nt of remaining stac" s*ace that &as a(ailable to the tas" since the tas" started exec!ting i0e0

The amo!nt of stac" that remained !n!sed &hen the tas" stac" &as at its greatest 3dee*est4 (al!e0

The stac" 1high &ater mar"10

I;C18/7$ !Tas):etStac)Mi'h3aterMar) m!st be defined as 1 for this f!nction to be a(ailable0 Ta"es one arg!ment2 !Tas) - the handle of the tas" being ;!eried0

A tas" can ;!ery its o&n high &ater mar" by *assing M$.. as the !Tas) *arameter0

Ret!rn (al!e is the high &ater mar" in &ords 3for exam*le2 on a 32 bit machine a ret!rn (al!e of 1 &o!ld indicate that 8 bytes of stac" &ere !n!sed40

A ret!rn (al!e is 'ero then the tas" has li"ely o(erflo&ed its stac"0 A (al!e is close to 'ero means the tas" has come close to o(erflo&ing its stac"0

First Technology Transfer - Feb 2013

2JB

Tas" /oo"s

Tas" hoo"s are2 ty*ically2 !sed in code tracing of a**lications

Ty*ically (ia trace hoo" macros port4(S7$TJ>7 !Tas)Call(pplicationTas)Moo)( !Tas)Mandle !Tas), #oid ?p#>arameter )+

con,'8S7$(>>1IC(TIO;$T(SL$T(: m!st be defined as 1 for this f!nction to be a(ailable A 1tag1 (al!e can be !sed to assign a hoo" 3or callbac"4 f!nction to a tas"

The hoo" f!nction is exec!ted by calling !Tas)Call(pplicationTas)Moo)()0

Each tas" can define its o&n callbac" Tas" callbac"s are o*tional Tas" hoo" f!nctions m!st ha(e ty*e pdT(SL$MOOL$CO/72 i0e0

Ta"e a #oid ? *arameter2 and ret!rn a (al!e of ty*e port4(S7$TJ>70

The (oid [ *arameter can be !sed to *ass any information into the hoo" f!nction Ta"es t&o arg!ments

!Tas) - the handle of the tas" &hose hoo" f!nction is being called0 #assing M$.. as xTas" &ill call the hoo" f!nction assocaited &ith the c!rrently exec!ting tas"0 p#>arameter - the (al!e to *ass to the hoo" f!nction

First Technology Transfer - Feb 2013

2JC

Tas" /oo" - ctd0

A mini-tem*late code sni**et is sho&n belo& 9

/? /e,ne the call&ac) " nction (ssi'n it as the tas) ta'. ;ote: The call&ac) " nction - this m st ha#e type pdT(SL$MOOL$CO/7 ?/ static port4(S7$TJ>7 pr#7!ampleTas)Moo)( #oid ? p#>arameter ) * /? /o somethin' appropriate e.'. o tp t some in"ormation ?/ ... ret rn G+ 0 /? ;ow de,ne the tas) that sets pr#7!ampleTas)Moo) as its hoo)/ta' #al e - in e""ect Yre'ister the tas) call&ac) " nctionZ ?/ #oid #(notherTas)( #oid ?p#>arameters ) * #Tas)Set(pplicationTas)Ta'( ;811, pr#7!ampleTas)Moo) )+ /? Re'ister call&ac) " nction ?/ "or( ++ ) * /? 3or) done &y the tas) ?/ 0 0 /? 7!ample se o" the hoo) (call&ac)) - 'et the RTOS )ernel to call the hoo) " nction o" each tas) that is &ein' switched o t d rin' a resched le. ?/ Ide,ne traceT(SL$S3ITCM7/$O8T() !Tas)Call(pplicationTas)Moo)( p!C rrentTC4, G )

First Technology Transfer - Feb 2013

2JG

Exercise

Ex*lore the FreeRT% doc!mentation describing trace hoo" macros and their !ses Modify the exam*les yo! ha(e been &or"ing on earlier to incl!de some trace f!nctionality De(ise a mechanism to t!rn tracing on and off dynamically - co(ering the *ossible o*tions listed belo&

T!rn all tracing on and off T!rn tracing on and off selecti(ely

First Technology Transfer - Feb 2013

2JJ

FreeRT% 5nter-tas" Comm!nication =!e!es2 M!texes and ema*hores

First Technology Transfer - Feb 2013

300

=!e!es

=!e!es are the *rimary form of intertas" comm!nication in FreeRT%

$sed to send messages bet&een tas"s2 and bet&een interr!*ts and tas"s0 Ty*ically !sed as thread safe F5F% 3First 5n First %!t4 b!ffers &ith ne& data being sent to the bac" of the ;!e!e Fixed si'e messages - message si'e defined at ;!e!e creation time Messages *laced in the ;!e!e by co*ying2 not by reference

5f re;!ired the messages can be references

=!e!e o*erations are bloc"ing &ith a timeo!t The "ernel ta"es care of allocating the memory !sed as the ;!e!e storage area

First Technology Transfer - Feb 2013

301

=!e!es - ctd0

Fariable si'ed messages can be sent by defining ;!e!es to hold str!ct!res that contain

A member that *oints to the ;!e!ed message2 and Another member that holds the si'e of the ;!e!ed message0

A single ;!e!e can be !sed to recei(e different message ty*es2 and messages from m!lti*le locations

Define the ;!e!e to hold a str!ct!re that has


A member that holds the message ty*e2 and Another member that holds the message data 3or a *ointer to the message data40 /o& the data is inter*reted de*ends on the message ty*e0 This a**roach is the basis for im*lementing e(ent dri(en a**lications

=!e!es are &ell s!ited for !se in a memory *rotected en(ironment0

A tas" that is restricted to a *rotected memory area can *ass data to a tas" that is restricted to a different *rotected memory area beca!se in(o"ing the RT% by calling the ;!e!e send f!nction &ill raise the microcontroller *ri(ilege le(el0 The ;!e!e storage area is only accessed by the RT% 3&ith f!ll *ri(ileges40
302

First Technology Transfer - Feb 2013

-loc"ing on =!e!es

=!e!e A#5 f!nctions *ermit a bloc"ing time to be s*ecified0 )hen a tas" attem*ts to read from an em*ty ;!e!e

The tas" &ill be *laced into the -loc"ed state 3so it is not cons!ming any C#$ time and other tas"s can r!n4 !ntil

Either data becomes a(ailable on the ;!e!e2 or the bloc" time ex*ires0

)hen a tas" attem*ts to &rite to a f!ll ;!e!e

The tas" &ill be *laced into the -loc"ed state 3so it is not cons!ming any C#$ time and other tas"s can r!n4 !ntil

Either s*ace becomes a(ailable in the ;!e!e2 or the bloc" time ex*ires0

5f more than one tas" bloc"s on the same ;!e!e then the tas" &ith the highest *riority &ill be the tas" that is !nbloc"ed first0 Mote9 5nterr!*ts m!st M%T !se A#5 f!nctions that do not end in :From5 R:0

First Technology Transfer - Feb 2013

303

=!e!e Management A#5s

There are 8 main gro!*s of A#5 methods Creation methods

F!lly feat!red methods

!P e eSend !P e eSendTo4ac) !P e eSendTo2ront !P e eRecei#e !P e e>ee) !P e eMess'es3aitin'

!P e eCreate #P e e/elete

.ight )eight methods

!P e eSend2romISR !P e eSendTo4ac)2romISR !P e eSendTo2ront2romISR !P e eRecei#e2romISR !P e eMessa'es3aitin'2romISR !P e eIsP e e7mpty2romISR !P e eIsP e e2 ll2romISR

Alternati(e - !se &here an alternati(e im*lementation is a(ailable

!P e e(ltSendTo4ac) !P e e(ltSendTo2ront !P e e(ltRecei#e !P e e(lt>ee)

First Technology Transfer - Feb 2013

308

Creating and Deleting =!e!es


The ;!e!e A#5 *ro(ides the 2ex*ected2 create and delete methods !P e eMandle !P e eCreate ( nsi'ned port4(S7$TJ>7 !P e e1en'th, nsi'ned port4(S7$TJ>7 !ItemSiCe )+ Creates a ne& ;!e!e instance0 Allocates the storage re;!ired by the ne& ;!e!e Ret!rns a handle for the ;!e!e 0 if the ;!e!e cannot be created Ta"es t&o arg!ments

!P e e1en'th - maxim!m n!mber of items that the ;!e!e can contain0 !ItemSiCe - n!mber of bytes each item in the ;!e!e &ill re;!ire0 5tems are ;!e!ed by co*y2 not by reference Each item on the ;!e!e m!st be the same si'e

#oid #P e e/elete( !P e eMandle !P e e )+ Deletes a ;!e!e - freeing all the memory allocated for storing of items *laced on the ;!e!e

Ta"es one arg!ment - !P e e - a handle to the ;!e!e to be deleted


30?

First Technology Transfer - Feb 2013

ending and Reading Messages

The FreeRT% ;!e!e A#5 *ro(ides a fairly standard set of methods for interacting &ith ;!e!es

ending2 sending to front2 sending to bac"2 destr!cti(e reading 3reading4 and non-destr!cti(e reading 3*ea"ing42 as &ell as Mon-bloc"ing recei(ing and sending methods to be !sed from 5 Rs -eca!se ;!e!es are shared reso!rces thread safe !se is associated &ith the caref!l !se of sema*hores and m!texes

The next fe& slides &ill re(ie& the sensing and recei(ing A#5 methods

First Technology Transfer - Feb 2013

30B

-asic ending - x=!e!e end

port4(S7$TJ>7 !P e eSend( !P e eMandle !P e e, const #oid ? p#ItemToP e e, portTic)Type !Tic)sTo3ait )+ This is a macro that calls x=!e!eLeneric end34 5ncl!ded for bac"&ard com*atibility &ith (ersions of FreeRT% that did not incl!de the !P e eSendTo2ront() and !P e eSendTo4ac)() macros

E;!i(alent to !P e eSendTo4ac)() #osts an item on a ;!e!e0 The item is ;!e!ed by co*y2 not by reference0 M!st not be called from an interr!*t ser(ice ro!tine Ta"es the follo&ing *arameters

!P e e - handle to the ;!e!e on &hich the item is to be *osted0 p#ItemToP e e - *ointer to the item that is to be *laced on the ;!e!e !Tic)sTo3ait - maxim!m amo!nt of time the tas" sho!ld bloc"

)ill ret!rn immediately if the ;!e!e is f!ll and xTic"sTo)ait is set to 00 Time is defined in tic" *eriods 5f I;C18/7$#Tas)S spend is set to 111 then s*ecifying the bloc" time as portM(H$/71(J &ill ca!se the tas" to bloc" indefinitely 3&itho!t a timeo!t40
30C

Ret!rns pdTR87 if the item &as s!ccessf!lly *osted2 other&ise errP8787$2811

First Technology Transfer - Feb 2013

-asic ending - x=!e!e end - ctd0

The follo&ing tem*late 6 code sni**et demonstrates the basic a**roach to &or"ing &ith ;!e!es

str ct (Messa'e * portCM(R cMessa'eI/+ portCM(R c/ataA 9G B+ 0 !Messa'e+ nsi'ned port1O;: l@ar < 6G81+ #oid #(Tas)( #oid ?p#>arameters ) * !P e eMandle !P e e6, !P e e9+ str ct (Messa'e ?p!Messa'e+ / / Create a - e e capa&le o" containin' 6G nsi'ned lon' #al es. !P e e6 < !P e eCreate( 6G, siCeo"( nsi'ned port1O;: ) )+ / / Create a - e e capa&le o" containin' 6G pointers to (Messa'e str ct res. !P e e9 < !P e eCreate( 6G, siCeo"( str ct (Messa'e ? ) )+ / / ... i"( !P e e6 R< G ) * / / Send an nsi'ned lon'. 3ait "or 6G tic)s "or space to &ecome a#aila&le i" necessary. i"( !P e eSend( !P e e6, ( #oid ? ) D l@ar, ( portTic)Type ) 6G ) R< pd>(SS ) * / / 2ailed to post the messa'e, e#en a"ter 6G tic)s. 0 0 i"( !P e e9 R< G ) * / / Send a pointer to a str ct (Messa'e o&.ect. /on5t &loc) i" the - e e is already " ll. p!Messa'e < D !Messa'e+ !P e eSend( !P e e9, ( #oid ? ) Dp!Messa'e, ( portTic)Type ) G )+ 0 / / ... Rest o" tas) code. 0
First Technology Transfer - Feb 2013 30G

ending to Front 6 -ac" of a =!e!e

FreeRT% *ro(ides an !P e e:enericSend() method &hich can be called to add ;!e!e elements to either the front or bac" of the ;!e!e !P e eSendTo2ront() and !P e eSendTo4ac)() are macros that call !P e e:enericSend()

They both ha(e similar macro definitions - the res!lting f!nction call ret!rns a (al!e of ty*e port4(S7$TJ>7

The (al!e is pdTR87 if the item &as s!ccessf!lly *osted2 other&ise errP8787$2811 The *arameters are

!P e e - handle to the ;!e!e on &hich the item is to be *osted0 p#ItemToP e e - *ointer to the item to be *laced on the ;!e!e !Tic)sTo3ait - the maxim!m amo!nt of time the tas" sho!ld bloc" &aiting for s*ace to become a(ailable on the ;!e!e2 sho!ld it already be f!ll0 The call &ill ret!rn immediately if this is set to 0 The time is defined in tic" *eriods 5f I;C18/7$#Tas)S spend is set to 111 then s*ecifying the bloc" time as *ortMAHODE.AW &ill ca!se the tas" to bloc" indefinitely 3i0e0 &itho!t a timeo!t4
30J

First Technology Transfer - Feb 2013

ending to -ac" of =!e!e

The follo&ing code sni**et6tem*late ill!strate the general *attern of !se 9

str ct (Messa'e * portCM(R cMessa'eI/+ portCM(R c/ataA 9G B+ 0 !Messa'e+ nsi'ned port1O;: l@ar < 6G81+ #oid #(Tas)( #oid ?p#>arameters ) * !P e eMandle !P e e6, !P e e9+ str ct (Messa'e ?p!Messa'e+ !P e e6 < !P e eCreate( 6G, siCeo"( nsi'ned port1O;: ) )+ !P e e9 < !P e eCreate( 6G, siCeo"( str ct (Messa'e ? ) )+ / / ... i"( !P e e6 R< G ) * i"( !P e eSendTo2ront( !P e e6, ( #oid ? ) D l@ar, ( portTic)Type ) 6G ) R< pd>(SS ) * / / 2ailed to post the messa'e, e#en a"ter 6G tic)s. 0 0 i"( !P e e9 R< G ) * p!Messa'e < D !Messa'e+ !P e eSendTo2ront( !P e e9, ( #oid ? ) Dp!Messa'e, ( portTic)Type ) G )+ 0 / / ... Rest o" tas) code. 0
First Technology Transfer - Feb 2013 310

Reading a Message

FreeRT% im*lements a !P e e:enericRecei#e() f!nction that can be called !*on to *erform a


A Destr!cti(e read of a message - !se the macro !P e eRecei#e() A non-destr!cti(e read 3the message remains in the ;!e!e4 - !se the macro !P e e>ee)()

port4(S7$TJ>7 !P e eRecei#e( !P e eMandle !P e e, #oid ?p#4 ""er, portTic)Type !Tic)sTo3ait )+


Recei(es an item from a ;!e!e0 The item is recei(ed by co*y into a s!itable si'ed b!ffer M!st not be !sed in an interr!*t ser(ice ro!tine Ta"es three *arameters

!P e e

- handle to the ;!e!e from &hich the item is to be recei(ed0

p#4 ""er - *ointer to the b!ffer into &hich the recei(ed item &ill be co*ied0 !Tic)sTo3ait - maxim!m amo!nt of time the tas" sho!ld bloc" &aiting for an item if the ;!e!e is em*ty &hen the call is made

etting !Tic)sTo3ait to 0 &ill ca!se the f!nction to ret!rn immediately if the ;!e!e is em*ty0 The time is defined in tic" *eriods

5f I;C18/7$#Tas)S spend is set to 111 then s*ecifying the bloc" time as portM(H$/71(J &ill ca!se the tas" to bloc" indefinitely Ret!rn (al!e is pdTR87 if an item &as s!ccessf!lly recei(ed from the ;!e!e2 other&ise pd2(1S7
311

First Technology Transfer - Feb 2013

Reading a Message - Exam*le

The basic *attern of reading and &riting messages is sho&n belo&

str ct (Messa'e * portCM(R cMessa'eI/+ portCM(R c/ataA 9G B+ 0 !Messa'e+ !P e eMandle !P e e+ #oid #(Tas)( #oid ?p#>arameters ) * / / Tas) to create a - e e and post a #al e. str ct (Messa'e ?p!Messa'e+ !P e e < !P e eCreate( 6G, siCeo"( str ct (Messa'e ? ) )+ i"( !P e e << G ) * / / 2ailed to create the - e e. 0 / / ... / / Send a pointer to a str ct (Messa'e o&.ect. /on5t &loc) i" the - e e is already " ll. p!Messa'e < D !Messa'e+ !P e eSend( !P e e, ( #oid ? ) Dp!Messa'e, ( portTic)Type ) G )+ / / ... Rest o" tas) code. 0 #oid #(/i""erentTas)( #oid ?p#>arameters ) * / / Tas) to recei#e "rom the - e e. str ct (Messa'e ?p!R!edMessa'e+ i"( !P e e R< G ) * / / Recei#e a messa'e created - e e. 4loc) "or 6G tic)s i" a - e e empty i"( !P e eRecei#e( !P e e, D( p!R!edMessa'e ), ( portTic)Type ) 6G ) ) * / / pcR!edMessa'e now points to the str ct (Messa'e #aria&le posted &y #(Tas). 0 0 / / ... Rest o" tas) code. 0 First Technology Transfer - Feb 2013 312

#ee"ing at a Message

port4(S7$TJ>7 !P e e>ee)( !P e eMandle !P e e, #oid ?p#4 ""er, portTic)Type !Tic)sTo3ait )+

imilar to x=!e!eRecei(e34 exce*t that an item is recei(ed from the ;!e!e2 b!t is not remo(ed from it

=!estions9 $nder &hat circ!mstances might yo! !P e e>ee) > Exercise9

5m*lement a sim*le *rod!cer tas" that &rites to a ;!e!e in a b!rsty &ay

.ots of &rites then nothing for a &hile then more &rites A lo& *riority tas" that *a!ses for a &hile after e(ery item has been read

5m*lement a sim*le cons!mer tas" that reads from a ;!e!e

/a(e one .ED light !* &hen the &riter is &riting and another .ED light !* &hen the reader is reading

First Technology Transfer - Feb 2013

313

Monitoring =!e!es

Ex*lore the doc!mentation for the follo&ing f!nctions


!P e eMessa'es3aitin'() !P e eMessa'es3aitin'2romISR() !P e eIsP e e2 ll2romISR() !P e eIsP e e7mpty2romISR() !P e eSend2romISR() !P e eSendTo4ac)2romISR() !P e eSendTo2ront2romISR() !P e eRecei#e2romISR()

Modify the sim*le *rod!cer-cons!mer exam*le so that /igh *riority message get added to the front of the ;!e!e The *rod!cer slo&s do&n its rate of sending messages &hen the b!ffer is nearly f!ll De(ise some "ind of sim*le +5 am ali(e *rotocol, &hich can be !sed by the *rod!cer or cons!mer they are still r!nning e(en tho!gh the b!ffer has been em*ty for a long time 3cons!mer side iss!e42 or f!ll for a long time 3*rod!cer side iss!e4 5m*lement a timer interr!*t handler ro!tine that &rite some data to a ;!e!e on e(ery timer interr!*t 5m*lement a timer interr!*t handler ro!tine that reads some data from a ;!e!e on e(ery timer interr!*t

First Technology Transfer - Feb 2013

318

Exam*les to R!n and t!dy


R!n the follo&ing FreeRT% exam*les >ollP.c - &hich demonstrates


5nter-tas" comm!nications Man!ally yielding *rocessor time #olling a ;!e!e for s*ace to &rite #olling a ;!e!e for s*ace to read #re-em*tion Creating tas"s 5nter-tas" comm!nications -loc"ing on ;!e!e reads -loc"ing on ;!e!e &rites #assing *arameters into a tas" #re-em*tion Creating tas"s
31?

4loc)P.c - &hich demonstrates

First Technology Transfer - Feb 2013

=!e!e ets

=!e!e sets im*lement a mechanism &hich allo&s an RT% tas" to bloc" 3*end4 on a read o*eration from m!lti*le RT% ;!e!es or sema*hores sim!ltaneo!sly

Mote9 An alternati(e method is to !se -loc"ing on M!lti*le %b<ects

A ;!e!e set m!st be ex*licitly created (ia a call to !P e eCreateSet() before it can be !sed0

%nce created2 standard FreeRT% ;!e!es and sema*hores can be added to the set (ia calls to !P e e(ddToSet() !P e eSelect2romSet() can be !sed to disco(er &hich2 if any2 of the ;!e!es or sema*hores contained in the set is in a state &here a ;!e!e read or sema*hore ta"e o*eration &o!ld be s!ccessf!l0

Motes9

-loc"ing on a ;!e!e set that contains a m!tex &ill not ca!se the m!tex holder to inherit the *riority of the bloc"ed tas"0 A recei(e 3in the case of a ;!e!e4 or ta"e 3in the case of a sema*hore4 o*eration m!st not be *erformed on a member of a ;!e!e set

$nless a call to !P e eSelect2romSet() has first ret!rned a handle to that set member0
31B

First Technology Transfer - Feb 2013

FreeRT% ema*hores and M!texes

First Technology Transfer - Feb 2013

31C

M!texes and ema*hores

-inary sema*hores and m!texes are (ery similar

There are a fe& s!btle differences that need to be !nderstood

M!texes incl!de a *riority inheritance mechanism Are the better choice for im*lementing sim*le m!t!al excl!sion -inary sema*hores do not incl!de a *riority inheritance mechanism

Are the better choice for im*lementing synchronisation )hether it be -et&een tas"s or -et&een tas"s and an interr!*t A binary sema*hore need not be gi(en bac" once obtained

/ence2 tas" synchronisation can be im*lemented by one tas"6interr!*t contin!o!sly 1gi(ing1 the sema*hore &hile another contin!o!sly 1ta"es1 the sema*hore
31G

First Technology Transfer - Feb 2013

M!texes and ema*hores - ctd0

The *riority of a tas" that 1ta"es1 a m!tex can *otentially be raised if another tas" of higher *riority attem*ts to obtain the same m!tex0

The tas" that o&ns the m!tex 1inherits1 the *riority of the tas" attem*ting to 1ta"e1 the same m!tex0 This means the m!tex m!st al&ays be 1gi(en1 bac"

%ther&ise the higher *riority tas" &ill ne(er be able to obtain the m!tex2 and The lo&er *riority tas" &ill ne(er 1disinherit1 the *riority -oth m!tex and binary sema*hores are assigned to (ariables of ty*e !SemaphoreMandle and can be !sed in any A#5 f!nction that ta"es a *arameter of this ty*e

First Technology Transfer - Feb 2013

31J

Co!nting ema*hore

The t&o main !ses of co!nting sema*hores are 9 Co!nting e(ents0 5n this !se case an e(ent handler &ill 1gi(e1 a sema*hore each time an e(ent occ!rs 3incrementing the sema*hore co!nt (al!e42 and A handler tas" &ill 1ta"e1 a sema*hore each time it *rocesses an e(ent 3decrementing the sema*hore co!nt (al!e40 #ro(iding the initial co!nt (al!e is 'ero - the co!nt (al!e &ill be the difference bet&een the n!mber of e(ents that ha(e occ!rred and the n!mber that ha(e been *rocessed0 Reso!rce management0 5n this !se case the co!nt (al!e indicates the n!mber of reso!rce instances a(ailable0 To obtain control of a reso!rce a tas" m!st first obtain a sema*hore decrementing the sema*hore co!nt (al!e0 )hen the co!nt (al!e reaches 'ero there are no a(ailable reso!rces left )hen a tas" finishes &ith the reso!rce it 1gi(es1 the sema*hore bac" incrementing the sema*hore co!nt (al!e0 The initial co!nt (al!e sho!ld be set to the maxim!m co!nt (al!e Corres*onding to the sit!ation &here all the reso!rces are a(ailable0
320

First Technology Transfer - Feb 2013

Rec!rsi(e M!tex

A rec!rsi(e m!tex2 &hen !sed rec!rsi(ely2 can be 1ta"en1 re*eatedly by its o&ner0 The m!tex does not become a(ailable again !ntil the o&ner has called !Semaphore:i#eRec rsi#e() for each s!ccessf!l 1ta"e1 re;!est e0g0

5f a tas" s!ccessf!lly 1ta"es1 the same m!tex 3 times then the m!tex &ill not be a(ailable to any other tas" !ntil the o&ning tas" has 1gi(en1 the m!tex bac" exactly 3 times0

Macro that im*lements a rec!rsi(e m!tex by !sing the existing ;!e!e mechanism0 A rec!rsi(e m!tex !ses a *riority inheritance mechanism /ence2 a tas" 1ta"ing1 a rec!rsi(e m!tex M$ T A.)AW 1gi(e1 that m!tex bac" once it is no longer re;!ired0 M!tex ty*e sema*hores cannot be !sed from &ithin interr!*t ser(ice ro!tines0

First Technology Transfer - Feb 2013

321

ema*hores and M!texes

5n FreeRT% the A#5 methods for mani*!lating ;!e!es and sema*hores6m!texes are macros that call do&n to the !nderlying f!nctions in the ;!e!e frame&or" im*lementation The ;!e!e and sema*hore6m!tex A#5s are2 in a certain sense2 intero*erable

-inary sema*hore6m!tex - is in effect2 a ;!e!e that can hold 1 item Co!nting sema*hore - is2 in effect2 a ;!e!e that can hold n items 3each of data si'e 04

5t is *ossible to extend the A#5 methods by defining ne& macros on the ;!e!e1s im*lementation A#5s

5f yo! do this be s!re to test these macros o!t thoro!ghly

First Technology Transfer - Feb 2013

322

ema*hore6M!tex Management A#5s

The FreeRT% ema*hore6M!tex management A#5 methods can be bro"en do&n into 8 categories Creation

.ight )eight

!Semaphore:i#e2romISR

Alternati(e - $sed &here an alternati(e im*lentation is *resent

#SemaphoreCreate4inary !SemaphoreCreateCo ntin' !SemaphoreCreateM te! !SemaphoreCreateRec rsi#eM te!

!Semaphore(ltTa)e !Semaphore(lt:i#e

F!lly Feat!red

!SemaphoreTa)e !SemaphoreTa)eRec rsi#e !Semaphore:i#e !Semaphore:i#eRec rsi#e

First Technology Transfer - Feb 2013

323

Ta"ing and Li(ing of ema*hores

The follo&ing code tem*late 6 sni**et ill!strates a ty*ical !sage *attern 9


!SemaphoreMandle !Semaphore < ;811+ #oid #(Tas)( #oid ? p#>arameters ) * / / Create m te! the semaphore to ' ard a shared reso rce. !Semaphore < !SemaphoreCreateM te!()+ 0 #oid #(notherTas)( #oid ? p#>arameters ) * / / ... /o other thin's. i"( !Semaphore R< ;811 ) * i"( !SemaphoreTa)e( !Semaphore, ( portTic)Type ) 6G ) << pdTR87 ) * / / O&tained the semaphore and can now access the shared reso rce. / / ... / / Release the semaphore - when ,nished sin' the shared reso rces !Semaphore:i#e( !Semaphore )+ 0 else * / / Co ld not o&tain the semaphore - cannot access the shared reso rce sa"ely. 0 0 0

First Technology Transfer - Feb 2013

328

Exercise

5m*lementation of a Readers and )riters !se case The goal is to

/a(e a critical section &here m!lti*le &riters are *resent b!t only one &riter at a time can &rite M!lti*le readers are *resent and m!lti*le readers can read conc!rrently Fairness of access for both readers and &riters is re;!iredl

First Technology Transfer - Feb 2013

32?

5nterr!*ts and Reso!rce Management

First Technology Transfer - Feb 2013

32B

E(ent Dri(en A**lications

Real &orld systems ty*ically ha(e to handle e(ents originating from m!lti*le so!rces

Different e(ents may ha(e different re*onse time re;!irements and ha(e different *rocessing o(erheads Many of the iss!es may &ell be considered d!ring the Re;!irements Analysis *hase of a *ro<ect - *ossibly also in(ol(ing $se Case Analysis

5ss!es

)hich e(ents m!st be detected and ho& >


5nterr!*ts > #olling > 5n the interr!*t handler or2 *lit into to* half and bottom &or"

5nterr!*t handling

To* half - critical &or" - done in the interr!*t handler -ottom half - deferred interr!*t handling &or" Comm!nicating e(ents from the interr!*t handler to the main a**lication code

First Technology Transfer - Feb 2013

32C

Deferred 5nterr!*t /andling

The a**roaches described by Richard -arry 3see $sing the FreeRT% Real Time Kernel - Cortex M3 Edition4 co(er

$sing binary sema*hores for 5 R - Tas" synchronisation $sing co!nting sema*hores for 5 R - Tas" synchronisation

The tas" code may also be str!ct!red aro!nd +acti(e ob<ects, an abstraction based on the combination of a ;!e!e &ith a state machine a**lication that *rocess e(ents as they are *lace on the ;!e!e

www.state-machine.com/"reertos/P/L$2reeRTOS.pd"

First Technology Transfer - Feb 2013

32G

-inary ema*hore ynchronisation

trategy for time critical e(ent handling

et the e(ent handler tas" *riority s!ch the the handler tas" &ill al&ays *re-em*t any other tas"s in the system 5m*lement the 5 R 3the Cortex M3 architect!re and FreeRT% both allo& 5 Rs to be im*lemented entirely in C4 in s!ch a &ay that the 5 R ret!rns directly to the handler tas" &hen the 5 R com*letes exec!ting 5m*lement the handler tas" so that it bloc"s 3ta)e4 on a sema*hore that &ill be !nbloc"ed by the 5 R 35 R *erforms a 'i#e o*eration on the sema*hore before com*leting exec!tion4

The 5 R !ses a s*ecial form of !Semaphore:i#e2 namely2 !Semaphore:i#e2romISR

The exam*le gi(en in the FreeRT% boo" !ses a soft&are generated interr!*t generated e(ery ?00 msec by a tri(ially sim*le *eriodic tas"

The handler tas" synchronises &ith the timer interr!*t The interr!*t handler2 &ritten in C2 *erforms a gi(e on the synchronising sema*hore2 clears the corres*onding interr!*t flag and *erforms a ret!rn from the interr!*t handler

First Technology Transfer - Feb 2013

32J

The #eriodic and /andler Tas"s

The code for the *eriodic tas" is 9 static #oid #>eriodicTas)(#oid ?p#>aremeters) * "or (++) * #Tas)/elay( KGG / portTICL$R(T7$MS )+ #>rintStrin'(Y>eriodic tas) - 'eneratin' interr pt[nZ)+ mainTRI::7R$I;T7RR8>T()+ / / Sets a &it in the interr pt controller5s / / Set >endin' re'ister #>rintStrin'(Y>eriodic tas) - interr pt 'enerated[nZ)+ 0

The code for the handler tas" is 9 static #oid #MandlerTas)(#oid ?p#>aremeters) * !SemaphoreTa)e(!4inarySemaphore, G)+ "or (++) * !SemaphoreTa)e(!4inarySemaphore, portM(H$/71(J)+ #>rintStrin'(YMandler tas) - e#ent processin'[nZ)+ 0

First Technology Transfer - Feb 2013

330

5nterr!*t /andler and main34

The code for the soft&are interr!*t handler is 9


#oid #So"twareInterr ptMandler (#oid) * port4(S7$TJ>7 !Mi'her>riorityTas)3o)en < pd2(1S7+ !Semaphore:i#e2romISR ( !4inarySemaphore, D!Mi'her>riorityTas)3o)en )+ mainC17(R$I;T7RR8>T+ port7;/$S3ITCMI;:$ISR( !Mi'her>riorityTas)3o)en )+ / / port7;/$S3ITCMI;:$ISR() is part o" the Corte!M% port layer / / ;e#er call tas)Jield() "rom an ISR 0

The code for main() is 9


int main(#oid) * #Set p7n#ironment()+ #SemaphoreCreate4inary( !4inarySemaphore)+ i" (!4inarySemaphore R< ;811) * pr#Set pSo"twareInterr pt()+ / / 7na&le so"tware interr pt and set / / its priority !Tas)Create( #MandlerTas), YMandlerZ, 9OG, ;811, 6, ;811 )+ #Tas)StartSched ler()+ 0 "or( ++ ) + 0

First Technology Transfer - Feb 2013

331

Co!nting ema*hore ynchronisation

A co!nting sema*hore can be !sed to co!nt e(ents

A binary sema*hore can be s!ed to latch at most one interr!*t e(ent Any s!bse;!ent e(ents that occ!r till the latched e(ent is *rocessed &ill be missed This is not the case &ith the co!nting sema*hore a**roach

The *re(io!s binary sema*hore demo can be ada*ted to one !sing a co!nting sema*hore as follo&s

Create a co!nting sema*hore in *lace of the binary sema*hore im!late m!lti*le e(ents occ!rring at high fre;!ency by getting the interr!*t ser(ice ro!tine to 1gi(e1 the sema*hore more than once *er interr!*t

The modified code for main() and for the interr!*t handler is sho&n on the next slide

First Technology Transfer - Feb 2013

332

5nterr!*t /andler and main34

The code for the soft&are interr!*t handler is 9


#oid #So"twareInterr ptMandler (#oid) * port4(S7$TJ>7 !Mi'her>riorityTas)3o)en < pd2(1S7+ !Semaphore:i#e2romISR ( !Co ntin'Semaphore, D!Mi'her>riorityTas)3o)en )+ !Semaphore:i#e2romISR ( !Co ntin'Semaphore, D!Mi'her>riorityTas)3o)en )+ !Semaphore:i#e2romISR ( !Co ntin'Semaphore, D!Mi'her>riorityTas)3o)en )+ mainC17(R$I;T7RR8>T+ port7;/$S3ITCMI;:$ISR( !Mi'her>riorityTas)3o)en )+ / / port7;/$S3ITCMI;:$ISR() is part o" the Corte!M% port layer / / ;e#er call tas)Jield() "rom an ISR 0

The code for main() is 9


int main(#oid) * #Set p7n#ironment()+ !Co ntin'Semaphore < !SemaphoreCreateCo ntin'( 6G, G)+ i" (!Co ntin'Semaphore R< ;811) * pr#Set pSo"twareInterr pt()+ / / 7na&le so"tware interr pt and set / / its priority !Tas)Create( #MandlerTas), YMandlerZ, 9OG, ;811, 6, ;811 )+ #Tas)StartSched ler()+ 0 "or( ++ ) + 0

First Technology Transfer - Feb 2013

333

=!e!es )ithin an 5 R

)hereas sema*hores can be !sed to comm!nicate e(ents2 ;!e!es can be !sed to both comm!nicate e(ents and to transfer data FreeRT% *ro(ides the !P e eSendTo2ront2romISR() and the !P e eSendTo4ac)2romISR() A#5 methods for <!st this *!r*ose The exam*le in the FreeRT% boo" $ses a *eriodic tas" that ends ? n!mbers to a ;!e!e e(ery 200 milliseconds Lenerate a soft&are interr!*t only after all ? (al!es ha(e been sent The interr!*t ser(ice ro!tine Calls x=!e!eRecei(eFrom5 R34 re*eatedly to remo(e all the (al!es from the ;!e!e The last t&o bits of each integer (al!e are !sed as an index into an array of strings and a *ointer to the string at the gi(en index *osition is &ritten to another ;!e!e !sing x=!e!e endFrom5 R34 The tas" recei(ing the string *ointers from the interr!*t ser(ice ro!tine bloc"s on the ;!e!e !ntil a message arri(es 5t *rints o!t strings as it recei(es them The code sni**ets are sho&n on the next fe& slides0

First Technology Transfer - Feb 2013

338

vInte!er+enerator
static #oid #Inte'er:enerator( #oid ?p#>arameters ) * portTic)Type !1ast7!ec tionTime+ nsi'ned port1O;: l@al eToSend < G+ int i+ /? InitialiCe the #aria&le sed &y the call to #Tas)/elay8ntil(). ?/ !1ast7!ec tionTime < !Tas):etTic)Co nt()+ "or( ++ ) * /? >eriodic tas) - e!ec tes e#ery 9GGms. ?/ #Tas)/elay8ntil( D!1ast7!ec tionTime, 9GG / portTICL$R(T7$MS )+ "or( i < G+ i F K+ i== ) * !P e eSendTo4ac)( !Inte'erP e e, D l@al eToSend, G )+ l@al eToSend==+ 0 /? 2orce an interr pt ?/ #>rintStrin'( W:enerator tas) - (&o t to 'enerate an interr pt.[nW )+ mainTRI::7R$I;T7RR8>T()+ #>rintStrin'( W:enerator tas) - Interr pt 'enerated.[n[nW )+

First Technology Transfer - Feb 2013

33?

vSoftwareInterrupt3an#ler
#oid #So"twareInterr ptMandler( #oid ) * port4(S7$TJ>7 !Mi'her>riorityTas)3o)en < pd2(1S7+ static nsi'ned lon' lRecei#ed; m&er+ static const char ?pcStrin'sAB < * WStrin' G[nW, WStrin' 6[nW, WStrin' 9[nW, WStrin' %[nW 0+ /? 1oop ntil the - e e is empty. ?/ while( !P e eRecei#e2romISR( !Inte'erP e e, D lRecei#ed; m&er, D!Mi'her>riorityTas)3o)en ) R< errP8787$7M>TJ ) * lRecei#ed; m&er D< G!G%+ !P e eSendTo4ac)2romISR( !Strin'P e e, DpcStrin'sA lRecei#ed; m&er B, D!Mi'her>riorityTas)3o)en )+ 0 mainC17(R$I;T7RR8>T()+ port7;/$S3ITCMI;:$ISR( !Mi'her>riorityTas)3o)en )+ 0

First Technology Transfer - Feb 2013

33B

vStrin!4rinter an# main()


static #oid #Strin'>rinter( #oid ?p#>arameters ) * char ?pcStrin'+ "or( ++ ) * /? 4loc) on the - e e to wait "or data to arri#e. ?/ !P e eRecei#e( !Strin'P e e, DpcStrin', portM(H$/71(J )+ #>rintStrin'( pcStrin' )+ 0 0 int main( #oid ) * SysCtlCloc)Set( SJSCT1$SJS/I@$O X SJSCT1$8S7$>11 X SJSCT1$OSC$M(I; X SJSCT1$HT(1$QMMN )+ !Inte'erP e e < !P e eCreate( 6G, siCeo"( nsi'ned lon' ) )+ !Strin'P e e < !P e eCreate( 6G, siCeo"( char ? ) )+ /? 7na&le the so"tware interr pt and set its priority. ?/ pr#Set pSo"twareInterr pt()+ /? Create the tas) to pass inte'ers to the interr pt ser#ice ro tine (priority 6) ?/ !Tas)Create( #Inte'er:enerator, WInt:enW, 9OG, ;811, 6, ;811 )+ /? Create the tas) that prints o t the strin's sent "rom the interr pt ser#ice ro tine (priority 9) ?/ !Tas)Create( #Strin'>rinter, WStrin'W, 9OG, ;811, 9, ;811 )+ #Tas)StartSched ler()+ "or( ++ ) + 0
First Technology Transfer - Feb 2013 33C

Critical ections

FreeRT% *ro(ides t&o a**roaches for im*lementing critical sections

-asic critical section realisation !sing the tas)7;T7R$CRITIC(1() and tas)7HIT$CRITIC(1() macros !s*ending 3.oc"ing4 the sched!ler

The basic critical section realisation macros

)or" by disabling interr!*ts !* to the interr!*t *riority set by con,'M(H$SJSC(11$I;T7RR8>T$>RIORITJ


#re-em*ti(e context s&itches can occ!r only from &ithin an interr!*t As long as interr!*ts remain disabled the tas" that called tas)7;T7R$CRITIC(1() &ill remain in the R!nning state !ntil it exits the critical section Critical sections can become nested The "ernel "ee*s a co!nt of nesting de*th Critical sections need to be "e*t short

Each call to tas)7;T7R$CRITIC(1() m!st be *aired &ith a corres*onding call to tas)7HIT$CRITIC(1()


33G

First Technology Transfer - Feb 2013

Critical ections - ctd0

Creating critical sections by s!s*ending the sched!ler

ho!ld be considered &here the critical section code is not *artic!larly short

5n this case disabling interr!*ts might not be an acce*table a**roach This *re(ents context s&itching2 b!t lea(es interr!*ts enabled FreeRT% A#5 f!nctions sho!ld not be called &hilst the sched!ler is disabled Calls to (Tas" !s*endAll34 and xTas"Res!meAll34 can be nested

The sched!ler is s!s*ended by in(o"ing #Tas)S spend(ll()


The "ernel "ee*s a co!nt of nexting de*th ched!ler res!med only &hen nesting de*th ret!rns to 'ero0

First Technology Transfer - Feb 2013

33J

Late"ee*er Tas"s

A gate"ee*er tas" is one that has sole o&nershi* of a reso!rce

%nly the gate"ee*er tas" can access the reso!rce directly Any other tas"ing re;!iring that *artic!lar reso!rce m!st !se the ser(ices *ro(ided by the gate"ee*er tas" e0g0

5f a gate"ee*er tas" has been im*lemented to manage access to standard o!t then

A tas" &ishing to send a message does not call a *rint f!nction directly 5t sends a message to the gate"ee*er The gate"ee*er can !se a FreeRT% ;!e!e to serialise access to the terminal )hen not &riting messages the gate"ee*er tas" is bloc"ed )hen a message arri(es2 it !nbloc"s and &rithe the message to the terminal -eca!se interr!*ts can send to ;!e!es An 5 R can also !se the ser(ices of a gate"ee*er tas"
380

First Technology Transfer - Feb 2013

Late"ee*er Tas"s - ctd0

The FreeRT% gate"ee*er tas" demo !ses a tic" hoo" f!nction to &rite o!t a message e(ery 200 tic"s The rele(ant code fragments are sho&n on the next fe& slides
static #oid pr#Stdio:ate)eeperTas)( #oid ?p#>arameters ) * char ?pcMessa'eTo>rint+ static char c4 ""erA mainM(H$MS:$17; B+ /? This is the only tas) that is allowed to write to the terminal o tp t. (ny other tas) wantin' to write to the o tp t does not access the terminal directly, & t instead sends the o tp t to this tas). ?/ "or( ++ ) * /? 3ait "or a messa'e to arri#e. ?/ !P e eRecei#e( !>rintP e e, DpcMessa'eTo>rint, portM(H$/71(J )+ /? There is no need to chec) the ret rn #al e as the tas) will &loc) inde,nitely and only r n a'ain when a messa'e has arri#ed. ?/ sprint"( c4 ""er, W\sW, pcMessa'eTo>rint )+ print"( c4 ""er )+ /? ;ow simply 'o &ac) to wait "or the ne!t messa'e. ?/ 0

First Technology Transfer - Feb 2013

381

Late"ee*er Tas"s - ctd0

prv4rintTask
static #oid pr#>rintTas)( #oid ?p#>arameters ) * int iInde!ToStrin'+ /? Two instances o" this tas) are created so the inde! to the strin' the tas) will send to the 'ate)eeper tas) is passed in the tas) parameter. ?/ iInde!ToStrin' < ( int ) p#>arameters+ "or( ++ ) * /? >rint o t the strin', &y passin' the strin' to the 'ate)eeper tas) on the - e e. The - e e is created &e"ore the sched ler is started so will already e!ist &y the time this tas) e!ec tes. ?/ !P e eSendTo4ac)( !>rintP e e, D( pcStrin'sTo>rintA iInde!ToStrin' B ), G )+ /? 3ait a pse do random time. In a more sec re application a #ersion o" rand() that is )nown to &e re-entrant sho ld &e sed - or calls to rand() sho ld &e protected sin' a critical section. ?/ #Tas)/elay( ( rand() D G!622 ) )+

First Technology Transfer - Feb 2013

382

Late"ee*er Tas"s - ctd0

vApplicationTick3ook
#oid #(pplicationTic)Moo)( #oid ) * static int iCo nt < G+ port4(S7$TJ>7 !Mi'her>riorityTas)3o)en < pd2(1S7+ /? >rint o t a messa'e e#ery 9GG tic)s. The messa'e is not written o t directly, & t sent to the 'ate)eeper tas). ?/ iCo nt==+ i"( iCo nt E< 9GG ) * /? The last parameter (!Mi'her>riorityTas)3o)en) is not act ally sed & t m st still &e s pplied. ?/ !P e eSendTo2ront2romISR( !>rintP e e, D( pcStrin'sTo>rintA 9 B ), D!Mi'her>riorityTas)3o)en )+ /? Reset the co nt ready to print o t the strin' a'ain in 9GG tic)s time. ?/ iCo nt < G+

First Technology Transfer - Feb 2013

383

Late"ee*er Tas"s - ctd0

main()

static char ?pcStrin'sTo>rintAB < * WTas) 6 ????????????????????????????????????????????????????[nW, WTas) 9 ----------------------------------------------------[nW, WMessa'e printed "rom the tic) hoo) interr pt IIIIIIIIIIIIII[nW 0+ !P e eMandle !>rintP e e+ int main( #oid ) * SysCtlCloc)Set( SJSCT1$SJS/I@$O X SJSCT1$8S7$>11 X SJSCT1$OSC$M(I; X SJSCT1$HT(1$QMMN )+ !>rintP e e < !P e eCreate( K, siCeo"( char ? ) )+ srand( KVU )+ i"( !>rintP e e R< ;811 ) * /? Tas)s created at di""erent priorities so some pre-emption will occ r. Oth parameter is inde! into list o" strin's to print ?/ !Tas)Create( pr#>rintTas), W>rint6W, 9OG, ( #oid ? ) G, 6, ;811 )+ !Tas)Create( pr#>rintTas), W>rint9W, 9OG, ( #oid ? ) 6, 9, ;811 )+ /? Create the 'ate)eeper tas) - the only tas) permitted to access standard o t. ?/ !Tas)Create( pr#Stdio:ate)eeperTas), W:ate)eeperW, 9OG, ;811, G, ;811 )+ #Tas)StartSched ler()+ 0 "or( ++ ) + 0
First Technology Transfer - Feb 2013 388

Das könnte Ihnen auch gefallen