+ All Categories
Home > Documents > L24_26 Realtime Executives

L24_26 Realtime Executives

Date post: 04-Apr-2018
Category:
Upload: wolfrum74
View: 229 times
Download: 0 times
Share this document with a friend

of 61

Transcript
  • 7/31/2019 L24_26 Realtime Executives

    1/61

    CS C 424 Software for Embedded systems

    Software for embedded systems

    Cs424First Semester

    2012-13

    Realtime Executives

  • 7/31/2019 L24_26 Realtime Executives

    2/61

    CS C 424 Software for Embedded systems

    RTOS- Introduction Needs complex software architecture to handle

    multiple tasks coordination

    communication

    interrupt handling

    Distinction:

    Desktop OS

    OS is in control at all times and runs applications

    OS runs in different address space

    RTOS

    OS and embedded software are integrated

    ES starts and activates the OS

    Both run in the same address space

    RTOS is less protected

    RTOS includes only service routines needed by the ES application

    RTOS vendors: VsWorks , VTRX, Nucleus, LynxOS, uC/OS

    Most conform to POSIX (IEEE standard for OS interfaces)

    Desirable RTOS properties: use less memory, application programminginterface, debugging tools, support for variety of microprocessors, already-debugged network drivers

  • 7/31/2019 L24_26 Realtime Executives

    3/61

    CS C 424 Software for Embedded systems

    Tasks and Task States

    A task a simple subroutine

    ES application makes calls to the RTOS functions to start tasks,passing to the OS, start address, stack pointers, etc. of the tasks

    Task States:

    Running

    Ready (possibly: suspended, pended)

    Blocked (possibly: waiting, dormant, delayed) Tasks can block them selves.

    Moved to ready state via other tasks interrupt signaling (when block-factor is removed/satisfied)

  • 7/31/2019 L24_26 Realtime Executives

    4/61

    CS C 424 Software for Embedded systems

    Scheduler Keeps track of the state of each task.

    Schedules/shuffles tasks between Running and Ready states Will not fiddle with task priorities

    When a task is unblocked with a higher priority over the runningtask, the scheduler switches context immediately (for all pre-emptive RTOSs)

  • 7/31/2019 L24_26 Realtime Executives

    5/61

    CS C 424 Software for Embedded systems

    Task states

    Blocked

    Running

    Ready

    What ever thetask needs,

    happens

    Another readytask is ofhigher priority

    This is highestpriority ready

    task

    Task needssomething tohappen beforeit continues

  • 7/31/2019 L24_26 Realtime Executives

    6/61

    CS C 424 Software for Embedded systems

    Scheduler and task states

    How does the scheduler know when a task has become blocked orunblocked?

    Tasks tell the scheduler on what events they are waiting.

    What happens if all the tasks are blocked?

    Scheduler waits indefinitely for some thing to happen.

    What if two tasks with same priority are ready?

    Bad design. Different RTOS handle in different way.

    What happens if one task is running and another high priority taskunblocks?

    Preemptive RTOS gets to ready state and higher priority task gets torunning state.

    Non preemptive RTOS pulls current task to ready state when that taskblocks itself.

  • 7/31/2019 L24_26 Realtime Executives

    7/61

    CS C 424 Software for Embedded systems

    //"Button taskvoid vButtontask(void) //Higher priority{

    while (TRUE){

    !! Block until user pushes button!! Button pressed. Respond to user

    }}

    //"levels taskvoid vlevelsTask(void) //low priority{

    While (TRUE){

    !! Read levels of floats!! calculate average float level}

    }

    Example

  • 7/31/2019 L24_26 Realtime Executives

    8/61

    CS C 424 Software for Embedded systems

    Task sequence

  • 7/31/2019 L24_26 Realtime Executives

    9/61

    CS C 424 Software for Embedded systems

    void main(void){

    //Initialize the RTOSInitRTOS();

    //Tell tghe RTOS about our tasksStartTask(vRespondTobutton,HIGH_PRIORITY);StartTask(vcalculateTankLevel,LOW_PRIORITY);

    //Start the RTOSStartRTOS()://This function never returns

    }

    RTOS initialization

  • 7/31/2019 L24_26 Realtime Executives

    10/61

    CS C 424 Software for Embedded systems

    Task2 Task3

    Task1

    Global data

    RTOS

    RTOS

    Data

    structures

    Task 2 stack

    Task 2 registers Task 3 registers

    Task 1 registers

    Task 3 stack

    Task 1 stack

    RTOS data organization

  • 7/31/2019 L24_26 Realtime Executives

    11/61

    CS C 424 Software for Embedded systems

    struct

    { long ltanklevel;long lTimeUpdated;

    }tankdata[MAX_TANKS]//Button taskvoid vRespondToButton (void) //High priority{

    !!Block until user pushes a buttoni=ID of the button pressed

    printf("", tankdata[i]);}

    //levels taskvoid vcalculaeTankLevels(void){

    int i=0;while (TRUE){

    !!Read levels of tank

    !! do calculations//store the result

    tankdata[i].lTimeUpdated==CurrentTime// Bad place for task switchingtankdata[i].lTanklevel= !1result of calculation}

    }

    Shared data

    Bug!!

  • 7/31/2019 L24_26 Realtime Executives

    12/61

    CS C 424 Software for Embedded systems

    void task1(void)

    { //vCountErrors(9);

    //}void task2(void){

    //vCountErrors(11);

    //}

    static int cErrors;void vCountErrors (intcnewErrors){

    cErrors +=cNewerrors;

    }

    Code sharing by tasks

    Bug!

  • 7/31/2019 L24_26 Realtime Executives

    13/61

    CS C 424 Software for Embedded systems

    Reentrancy

    Reentrancy A function that works correctly regardless of the number oftasks that call it between interrupts

    Characteristics (checks) of reentrant functions

    1. Only access shared variable in an atomic-way, or when variable is on calleesstack

    2. A reentrant function calls only reentrant functions

    3. A reentrant function uses system hardware (shared resource) atomically

  • 7/31/2019 L24_26 Realtime Executives

    14/61

    CS C 424 Software for Embedded systems

    Reentrancy

    Inspecting code to determine Reentrancy:

    Where are data stored in C? Shared, non-shared, or stacked?

    Is this code reentrant? What about variablefError? Is printf reentrant?

    If shared variables are not protected, could theybe accessed using single assembly instructions(guaranteeing non-atomicity)?

  • 7/31/2019 L24_26 Realtime Executives

    15/61

    CS C 424 Software for Embedded systems

    Semaphores

  • 7/31/2019 L24_26 Realtime Executives

    16/61

    CS C 424 Software for Embedded systems

    Semaphores and Shared Data

    Semaphore a variable/lock/flag used tocontrol access to shared resource (to avoidshared-data problems in RTOS)

    Protection at the start is via primitive function,

    called take, indexed by the semaphoreProtection at the end is via a primitive

    function, called release, also indexed similarly

    Simple semaphores Binary semaphores are

    often adequate for shared data problems inRTOS

  • 7/31/2019 L24_26 Realtime Executives

    17/61

    CS C 424 Software for Embedded systems

    Semaphores

    struct

    {long ltanklevel;long lTimeUpdated;

    } tankData[MAX_TANKS]//Button taskvoid vRespondToButton(void){

    int i;while (TRUE){!! Block until user pushes the buttoni=!!get ID of the button pressedTakeSemahore();printf(""tankData[i].lTimeUpdated, ltankLevel);ReleaseSemaphore();

    }}

    //levels task

    //Low priorityvoid vcalculatetankLevels(void){

    int i=0;while (TRUE){..;..;

    TakeSemaphore();!! Set ankdata[i].lTimeUpdated;!! set tankdata[i].lTakLevel;ReleaseSemaphore();}

    }

  • 7/31/2019 L24_26 Realtime Executives

    18/61

    CS C 424 Software for Embedded systems

    Execution flow with semaphores

  • 7/31/2019 L24_26 Realtime Executives

    19/61

    CS C 424 Software for Embedded systems

    Semaphores and Shared Data#define TASK_PRIORITY_READ 11#define TASK_PRIORITY_CONTROL 12

    #define STK_SIZE 1024static unsigned int ReadStk[STK_SIZE];static unsigned int ControlStk[STK_SIZE];static int itemperatures[2];OS_EVENT *p_semtemp;

    void main(void){

    //Init the RTOS

    OSInit();//Tell the RTOS about the tasksOSTaskCreate (vReadTemparatureTask,NULLP,

    (void*) Readstk[STK_SIZE],TASK_PRIORITY_READ);OSTaskCreate (vControlTask,NULLP,(void*) &Controlstk [STK_SIZE], TASK_PRIORITY_CONTROL) ;

    OSStart();}

    void ReadTask(void){

    while (TRUE){OSTimeDly (5)OSSemPend

    (p_SemTemp,WAIT_FOREVER);!!1 read in iTemperatures[0];!!read in iTemperatures[1];OSSemPost (p_semtemp);}

    }

    void Controltask(void){p_semtemp=OSSemInit(1);while (TRUE){

    OSSempend(p_semptemp,WAIT_FOREVER);

    if (iTemperatures[0]!=iTemparatures[1])!! Set of alaram;OSSemPost (p_semtemp);!!1 Do other useful work..;

    }}

    Bug!

    Put this before

    OSStart()!

  • 7/31/2019 L24_26 Realtime Executives

    20/61

    CS C 424 Software for Embedded systems

    Semaphores and Shared Data

    void task1(void){

    ..;

    ..;vCountErrors(9);..;..;

    }void task2(void){

    ..;

    ..;vCountErrors(11);..;..;

    }static int cErrors;

    static NU_SEMAPHORE semErrors;void vCountErrors (int cnewErrors){NU_Obtain_Semaphore (&semErrors,NU_SUSPEND);cErrors += cNewErrors;NU_Release_Semaphore (&semerrors);

    }

    Re-entrant

  • 7/31/2019 L24_26 Realtime Executives

    21/61

    CS C 424 Software for Embedded systems

    Multiple semaphores

    A lower priority task may block higher

    priority task on a semaphore.

    Have more granulaity

    Have one semaphore for each type of

    resource. Try avoidig a block of higher priority task

    unless it is must.

  • 7/31/2019 L24_26 Realtime Executives

    22/61

    CS C 424 Software for Embedded systems

    Semaphore as a signaling device//Place to construct a reportstatic char a_chprint[10][12];

    //Count the lines in the report

    static int iLinesTotal;//count of lines printed so farsatic int ilinesPrinted;

    //semaphore to wait for report to finishstatic OS_EVENT *semprinter;void vPrintertask(void){

    BYTE byError //Place for an error returnint wmsg;

    //Initialize the semaphore as already takensemprinter=OSSemInit(0);while (TRUE){

    //wait for a message telling what report to formatwMsg=(int) OSPend(QprinterTask,WAIT_FOREVER,&byError);!! Format the report into a_chprintiLinesTotal=!!count of lines in the report

    //print the first line of the reportiLinesprinted=0;vhardwareprinterOutputLine (a_chprint[iLinesprinted++]);

    //wait for print job to finishOSSempend (semprinter,WAIT_FOREVER);

    }}

    void vprinterInterrupt(void)

    {if (ilinesPrinted==ilinesTotal)

    //The report is done. release the semaphoreOSSempost (semPrinter);

    else//print the next linevhardwareprinterOutputLine (a_chprint

    [iLinesprinted++]) ;}

  • 7/31/2019 L24_26 Realtime Executives

    23/61

    CS C 424 Software for Embedded systems

    Precautions with Semaphore

    The initial values of semaphores when not setproperly or at the wrong place

    The symmetry of takes and releases must matchor correspond each take must have acorresponding release somewhere in the ES

    application Taking the wrong semaphore unintentionally (issue

    with multiple semaphores)

    Holding a semaphore for too long can cause waiting

    tasks deadline to be missed Priorities could be inverted and usually solved by

    priority inheritance/promotion

    Causing the deadly embrace problem (cycles)

  • 7/31/2019 L24_26 Realtime Executives

    24/61

    CS C 424 Software for Embedded systems

    Priority inversion

    Resolved by priorityinheritance by someRTOS

    They temporarilyboost the priority oftask C to that of taskA whenevr task Cholds the semaphoreand task A is waitingfor it.

  • 7/31/2019 L24_26 Realtime Executives

    25/61

    CS C 424 Software for Embedded systems

    Deadly embrace

    int a;int b;AMXID hSemaphoreA;AMXID hSemaphoreB;void vtask1(void){

    ajsmrsv(hsemaphoreA,0,0);ajsmrsv (hsemaphoreB,0,0);

    a=b;ajsmrls (hSemaphoreB);ajsmrls (hSemaphoreA);

    }

    void vtask2 (void){

    ajsmrsv (ajsmrsv(hsemaphoreB,0,0);ajsmrsv (hsemaphoreA,0,0);b=a;ajsmrls (hSemaphoreA);ajsmrls (hSemaphoreB);

    }

  • 7/31/2019 L24_26 Realtime Executives

    26/61

    CS C 424 Software for Embedded systems

    Semaphore Variants

    Binary semaphores single resource, one-at-a time,alternating in use (also for resources)

    Counting semaphores multiple instances ofresources, increase/decrease of integer semaphorevariable

    Mutex protects data shared while dealing withpriority inversion problem

  • 7/31/2019 L24_26 Realtime Executives

    27/61

    CS C 424 Software for Embedded systems

    Protecting shared data

    Disabling/Enabling interrupts (for task

    code and interrupt routines), faster

    Taking/Releasing semaphores (cant usethem in interrupt routines), slower,

    affecting response times of those tasksthat need the semaphore

    Disabling task switches (no effect oninterrupt routines), holds all other tasks

    response

  • 7/31/2019 L24_26 Realtime Executives

    28/61

    CS C 424 Software for Embedded systems

    More RTOS services

  • 7/31/2019 L24_26 Realtime Executives

    29/61

    CS C 424 Software for Embedded systems

    Message Queues, Mailboxes and Pipes

    Basic techniques for inter-task communicationand data sharing

    Semaphores.

    Message Queues

    Mailboxes Pipes

  • 7/31/2019 L24_26 Realtime Executives

    30/61

    CS C 424 Software for Embedded systems

    Sample queue//RTOS queue function prototypesvoid AddToQueue (init iData);

    void ReadFromQueue(int *p_iData);void pTask1(void){

    ;;if (!!problem arises)

    vLogError(ERROR_TYPE_X);!!Other things that need to be donesoon

    ;;

    }void Task2(void)

    {;;if (!!problem arises)

    vLogError(ERROR_TYPE_Y);!! other things that need to be done

    soon}

    void vLogError(int iErrorType)

    {AddToQueue (iErrorType);

    }static int cErrors;void ErrorsTask(void){

    int iErrorType;while (TRUE){

    ReadFromQueue (&iErrorType);++cErrors;!! Send cErrors and iError type on

    network

    }}

  • 7/31/2019 L24_26 Realtime Executives

    31/61

    CS C 424 Software for Embedded systems

    Queues

    Queue initialization (like semaphore initialization) must bededicated to a separate task to a) guarantee correct start-up values and b) avoid uncertainty about task prioritiesand order of execution which might affect the queuescontent

    Queues must be tagged (identify which queue isreferenced)

    Need code to manage the queue (when full and empty) ifRTOS doesnt block reading/writing task on empty/full,plus returning an error code

    RTOS may limit the amount of info to write/read to queuein any single call

  • 7/31/2019 L24_26 Realtime Executives

    32/61

    CS C 424 Software for Embedded systems

    More realistic use of a queue

    void vLogError(int iErrorType){

    //Return code from writing from queueBYTE byReturn;byReturn=OSQPost(pOseQueue,(void*)

    iErrorType);if (byReturn!=OS_NO_ERR)!! handle the situation that arises when the

    queue is full}static int cErrors;void ErrorsTask (void)

    {int iErrorType;BYTE byErr;while(FOREVER){

    iErrorType=(int)OSQPend(pOseQueue,WAIT_FOREEVER,&byErr);

    ++cErrors;}

    }

    //RTOS queue function prototypesOS_EVENT *OSQCreate(void *PPStart,BYTE bySize;

    unsigned char OSQPost (OS_EVENT *pOse,void*pvMsg);void *OSQPend (OS_EVENT *pOse,WORD wTimeout,BYTE *pByErr);#define WAIT_FOREEVER 0

    //Our message queuestatic OS_EVENT *pOseQueue;

    #define SIZEOF_QUEUE 25

    void *apvQueue[SIZEOF_QUEUE];void main(){;pOseQueue=OSQCreate (apvQueue,SIZEOF_QUEUE);;!!start task1;!!start task2;;

    }void task1(void){;if (!!problem arises)

    vLogError(ERROR_TYPE_X);!! other things that need to be done

    ;

    }

    void task2(void){

    ;if (!!problem arises)

    vLogError(ERROR_TYPE_Y);!! other things that need to be done

    ;}

  • 7/31/2019 L24_26 Realtime Executives

    33/61

    CS C 424 Software for Embedded systems

    Passing pointers on queues

    void vMainTask(void){

    int *pTemperatures;BYTE byErr;while (TRUE){

    ptemparatures=(int*)

    OSQPend(pOseQueue,WAIT_FOREEVER,&byErr);if (pTemparaturews[0] !=

    pTemparatures[1]!!Set off howling alaram;free (pTemperatures);

    }}

    /RTOS queue function prototypesOS_EVENT *OSQCreate(void *PPStart,BYTE bySize);

    unsigned char OSQPost (OS_EVENT *pOse,void *pvMsg);void *OSQPend (OS_EVENT *pOse,WORD wTimeout, BYTE*pByErr);#define WAIT_FOREEVER 0

    //Our message queuestatic OS_EVENT *pOseQueuetemp;void vReadTemperaturesTask (void){int ptemperatures;while (TRUE){!!1Wait untilit is time to read next temp.

    //Get a new buffer for next set of temps.ptemperatures=(int*) malloc(2*sizeof *ptemparatures);

    ptemparature[0]=!! read the valueptemparature[1]=!! read the value

    //Add a pointer to the new temps to the queue

    OSQPost (pOseQueueTemp, (void*)ptemparatures);}

    }

  • 7/31/2019 L24_26 Realtime Executives

    34/61

    CS C 424 Software for Embedded systems

    Using Mailboxes:

    Similar to queues

    Typical RTOS function for managing mailboxes create, write, read, check-mail, destroy

    Variations in RTOS implementations of mailboxes Either a single-message mailbox or multi-message mailbox (set # entries

    at start)

    # of messages per mailbox could be unlimited, but total # in the systemcould be (with possibility of shuffling/distributing messages amongmailboxes)

    Mailboxes could be prioritized

    Examples:(from the RTOS MultiTask! )

    int sndmsg (unsigned int uMbid, void *p_vMsg, unsigned int uPriority);

    void *rcvmsg(unsigned int uMbid, unsigned int uTimeout);

    void *chkmsg(unsigned int uMbid);

  • 7/31/2019 L24_26 Realtime Executives

    35/61

    CS C 424 Software for Embedded systems

    Pipes:

    Similar to a physical pipe RTOS can create, read from, write to, destroy pipes

    Details of implementation depends on RTOS

    Pipes can have varying length messages (unlike fixed lengthfor queues / mailboxes)

    Pipes could be byte-oriented and read/write by tasksdepends on # bytes specified

    In standard C, read/write of pipes use fread/fwrite functions,respectively

  • 7/31/2019 L24_26 Realtime Executives

    36/61

    CS C 424 Software for Embedded systems

    Timer Functions

    RTOS provides these timing services or functions Some points:

    Time measured in ticks

    Relies on microprocessors hardware timer and its interruptcycles

    Length of a tick depends on the hardware timers design trade-off

    Accurate timing short tick intervals OR use dedicated timerfor purpose

  • 7/31/2019 L24_26 Realtime Executives

    37/61

    CS C 424 Software for Embedded systems

    Events

    In standard OS, an event is typically an indication which is related totime

    In RTOS, an event is a boolean flag, which is set and reset bytasks/routines for other tasks to wait on

    RTOS is supposed to manage several events for the waiting tasks.Blocked or waiting tasks are unblocked after the event occurrence,and the event is reset

  • 7/31/2019 L24_26 Realtime Executives

    38/61

    CS C 424 Software for Embedded systems

    Using events

    //Handle for the trigger group of events#Define TRIGGER_MASK 0X0001#Define TRIGGER_SET 0X0001#Define TRIGGER_RESET 0X0000

    void main(void){

    ajevcre(&amxIdTrigger ,0,"EVTR");;;

    }void Interrupt vTriggerISR(void)

    {//Set the eventajevsig(amxIdTrigger,TRIGGER_MASK,TRIGGER_SET);

    ;}void vScanTask(void){

    ;;while (TRUE)

    {//Wait for the user to pull the triggerajewat(amxIdTrigger,TRIGGER_MASK,TRIGGER_SET,WAIT_FOR_ANY,WAIT_FOREVER);//Reset the trigger eventajevsig(amxIdTrigger,TRIGGER_MASK,TRIGGER_RESET);;}

    }

  • 7/31/2019 L24_26 Realtime Executives

    39/61

    CS C 424 Software for Embedded systems

    Features of events

    More than one task can wait on the same event Events can be grouped, and tasks may wait on a subset of

    events in a group

    Resetting events is either done by the RTOS automaticallyor your embedded software

    Tasks can wait on only one semaphore, queue, mbox orpipe, but on many events simultaneously.

    Semaphores are faster, but unlike queues, mboxes, andpipes, they carry 1-bit info

    Queues, mboxes, and pipes are message posting/retrieval

    is compute-intensive

  • 7/31/2019 L24_26 Realtime Executives

    40/61

    CS C 424 Software for Embedded systems

    Memory Management

    In general RTOS offer C lang equivalent of malloc and free forMM, which are slow and unpredictable

    Real time system engineers prefer the faster and morepredictable alloc/free functions for fixed size buffers.

    E.g., MultiTask!RTOS allocates pools of fixed size buffers, using

    getbuf() [with timed task blocking on no buffers] and reqbuf()[with no blocking and return of NULL pointer on no buffers]

    relbuf() to free buffers in a given pool (buffer pointer must bevalid)

    Note that most embedded sw is integrated with the RTOS (sameaddress space) and the ES starts the microprocessor; hence your

    ES must tell the memory-pool

  • 7/31/2019 L24_26 Realtime Executives

    41/61

    CS C 424 Software for Embedded systems

    Initialize memory pool

    Init_mem_pool function in muti task

    P_vMemory

    uBuffCount

    uBuffSize

    #Define LINE_POOL 1#DEFINE MAX_LINE_LENGTH 40#DEFINE MAX_LINES 80static chara_Lines[MAX_LINES][MAX_LINE_LENGTH]void main(void){;;

    Init_mem_pool(LINE_POOL,a_Lines,MAX_LINES, MAX_LINE_LENGTH,TASK_POOL);;

    }

  • 7/31/2019 L24_26 Realtime Executives

    42/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

    Rules that IRs must comply with (but not a taskcode)

    Rule 1: An IR cant call RTOS function that will causeit to block like

    wait on semaphoresreading empty queues or mailboxes

    wait on events..

  • 7/31/2019 L24_26 Realtime Executives

    43/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

    Rule 2:An IR cant call RTOS functions that will causethe RTOS to switch other tasks (except otherIRs);

    Breaking this rule will cause the RTOS to switchfrom the IR itself to handle the task, leaving theIR code incomplete or delay lower priorityinterrupts

    ISR i RTOS E i t

  • 7/31/2019 L24_26 Realtime Executives

    44/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

    ISR i RTOS E i t

  • 7/31/2019 L24_26 Realtime Executives

    45/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

  • 7/31/2019 L24_26 Realtime Executives

    46/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

    One solution to Rule 2

    Let the RTOS intercept all the interrupts, aided by an RTOSfunction which tells the RTOS where the IRs are and thecorresponding interrupt hardware

    The RTOS then activates the calling IR or the highestpriority IR

    Control returns to the RTOS, and the RTOS schedulerdecides which task gets the microprocessor (allowing theIR to run to completion)

  • 7/31/2019 L24_26 Realtime Executives

    47/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

  • 7/31/2019 L24_26 Realtime Executives

    48/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS EnvironmentSecond solution to Rule 2:

    Let the IR call a function in the RTOS to inform the RTOS ofan interrupt

    After the IR is done, control goes back to the RTOS, whereanother function calls the scheduler to schedule the next task

    Third solution to Rule 2:

    Let RTOS maintain a separate queue of specialized, interrupt-supporting functions which are called by the IR (on theappropriate interrupt). When these functions complete,control goes back to that IR

  • 7/31/2019 L24_26 Realtime Executives

    49/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

  • 7/31/2019 L24_26 Realtime Executives

    50/61

    CS C 424 Software for Embedded systems

    Interrupt Routines in an RTOS Environment

    Nested Interrupts

    If a running IR is interrupted by another (higher) priority interrupt (kindof interrupt stacking), the RTOS should unstack the IRs to allow all IRsto complete before letting the scheduler switch to any task code

  • 7/31/2019 L24_26 Realtime Executives

    51/61

    CS C 424 Software for Embedded systems

    ISRs in RTOS Environment

  • 7/31/2019 L24_26 Realtime Executives

    52/61

    CS C 424 Software for Embedded systems

    Basic design using a Real time OS

    pick a software architectureconstruct a specification of the ES to meet such requirements / properties

    Problem Decomposition into Tasks

    Write Short IRs

  • 7/31/2019 L24_26 Realtime Executives

    53/61

    CS C 424 Software for Embedded systems

    Problem Decomposition into Tasks How many tasks?

    Considerations (+)More tasks offer better control of overall response time

    (+)Modularity different task for different device handling or functionality

    (+)Encapsulation data and functionality can be encapsulated withinresponsible task

    (-) More tasks means data-sharing, hence more protection worries and longresponse time due to associated overheads

    (-) More task means intertask messaging, with overhead due to queuing,mailboxing, and pipe use

    (-) More tasks means more space for task stacks and messages

    (-) More tasks means frequent context switching (overhead) and lessthroughput

    (-) More tasks means frequent calls to the RTOS functions (major overhead adds up)

  • 7/31/2019 L24_26 Realtime Executives

    54/61

    CS C 424 Software for Embedded systems

    Priorities

    Priorities (advantage of using RTOS software architecture):

    Decomposing based on functionality and time criticality, separates EScomponents into tasks (naturally), for quicker response time using taskprioritization

    high priority for time-critical ones, and low priority for others

    Encapsulating functionality in Tasks

    A dedicated task to encapsulate the handling of each shared device (e.g.,printer display unit) or a common data structure (e.g., an error log)

  • 7/31/2019 L24_26 Realtime Executives

    55/61

    CS C 424 Software for Embedded systems

    Avoid Creating and Destroying Tasks

    Avoid Creating and Destroying Tasks

    Creating tasks takes more system time

    Destroying tasks could leave destroy pointers-to-messages, remove semaphoreothers are waiting on (blocking them forever)

    Rule-of-thumb: Create all tasks needed at start, and keep them if memory ischeap!

    Turn Time-Slicing Off Useful in conventional OSs for fairness to user programs

    In ESs fairness is not an issue, response-time is!

    Time-slicing causes context switching time consuming and diminishesthroughput

    Where the RTOS offers an option to turn time-slicing off, turn it off!

  • 7/31/2019 L24_26 Realtime Executives

    56/61

    CS C 424 Software for Embedded systems

    Restrict the use of RTOS functions/features

    Restrict the use of RTOS functions/features

    Customize the RTOS features to your needs

    If possible write ES functions to interface with RTOS select features to minimizeexcessive calls to several RTOS functions (increases opportunity for errors)

    Develop a shell around the RTOS functions, and let your own ES tasks call theshell (and not the RTOS directly) improves portability since only the shell maybe rewritten from RTOS to RTOS

  • 7/31/2019 L24_26 Realtime Executives

    57/61

    CS C 424 Software for Embedded systems

    There are 255 EVMs which have to be connected toa central processing unit (CP).

    CP holds the IDs of voters, their thumb signaturesand voted option.

    Communicates with EVMs through messages.

    Role of EVM:

    When user places thumb, EVM generates asignature.

    Sends the signature to CP.

    Receives the assertion/negation message sent byCP. CP asserts if the signature is correct and the

    user has not voted. CP negates otherwise. Glows select one from right and when user selects

    one option, it prevalidates (i.e one option is keptpressed for 5 sec) and sends the selection to CP.

    Receives ACK sent by CP in response to EVMsmessage.

    EVM glows done! and ready to take next user.

    Role of CP:

    Maintains IDs of voters, their thumb signatures andvoted options.

    Gets messages from all EVMs and responds theaction taken.

    Receives the signature from EVM.

    Verifies if the signature is correct and the user hasnot voted. Sends assert/negate message in responseto this

    Receives candidate selection from EVM . updates the

    selection and acknowledges to EVM

    Example

    C1

    C3

    C3

    C4

    Place thumb

    here

    Select one

    from right Done!

    Invalid!

  • 7/31/2019 L24_26 Realtime Executives

    58/61

    CS C 424 Software for Embedded systems

    Message_Receiver

    Receives the messages from every EVM .

    Puts into received messages queue

    Suspends itself for next message to arrive.

    Message Decoder

    Decodes the received message

    Updates the action buffer with the

    information decoded from message.

    Ex: EVM ID, verify operation, signature.

    Adds a session number

    Set verify event

    Suspends till the next message to be

    decoded

    Signature verifier

    Receives a record from the buffer needing

    an action to verify the signature.

    Interacts with data access layer and verifies

    the signature.

    Extracts the ID of the person.

    Updates the buffer with the ID

    Updates the buffer state.

    Posts data to be sent to EVM to message

    encoder

    Clear verify event

    Waits on verify event.

    Tasks

    Vote_registration

    Receives a record from the buffer needing to store

    candidate selectionInteracts with data access layer and updates the data

    Removes the record from buffer once the registration is

    successful

    Posts acknowledgement data to be sent to EVM to

    message encoder

    Message Encoder

    Receives data

    Frames appropriate messagePosts into Transmit Queue

    Waits for a message to be encoded

    Message_Transmitter

    Pulls a message from transmit queue

    Transmits to the EVM to be notified.

    Sleeps if there are no messages to be transmitted

    Watchdog

    Checks action buffer every one second for any time outs.

    Generates error message and posts to message encoder

    Deletes the record from action buffer.

  • 7/31/2019 L24_26 Realtime Executives

    59/61

    CS C 424 Software for Embedded systems

    Received Queue

    Message Receiver posts received message

    Message decoder waits on this object and pulls the messages for decoding.

    Action buffer

    A buffer with one record for each transaction from EVM

    This can be a FIFO .

    Randomly accessible as the tasks will update each session

    Message decoder posts /updates a record

    All action tasks (signature verifier/Vote_registration/watch dog..) wait on the buffer data to do

    actions and update them.

    Transmit Queue

    Message encode posts after a message is framed

    Message transitter pulls out each message and sends.

    Events

    OnMessage Received (message receiver waits on this event)

    Onmessageposted in RXQ(message posted in RXQ)

    OnBufferPosted (several action tasks wait on this)On verify event (verifier waits on this event)

    Onvoterselect (Encodeed message is to set the voter selection)

    OnTxQueuePosted(Message transmitter waits on this)

    Objects

  • 7/31/2019 L24_26 Realtime Executives

    60/61

    CS C 424 Software for Embedded systems

    Interaction

    sd task interaction

    EVM

    Message receiver MessageDecoder signatureVerifier Messagetransmi...MessageEncoder Vote_registration

    OnMessageReceived()

    PostMessageinReceivequeue()

    OnmessagePostedinreceivequeue()

    Decode and post in action buffer()

    Onverifyset()

    Verify the signature and update action buffer()

    Encode message()

    Post ACK message in TXqueue()

    Onvoter select()

    Update database and set action buffer,

    send message to encoder()Encode ACK message()

    Post ACK message ()

  • 7/31/2019 L24_26 Realtime Executives

    61/61

    An embedded software primer by David E

    Simon, Addison Wesley Real-Time Systems by Jane Liu, Pearson

    ed.,2000.

    References


Recommended