Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Realtime Executives
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 programming interface, debugging tools, support for variety of microprocessors, alreadydebugged network drivers
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 running task, the scheduler switches context immediately (for all preemptive RTOSs)
Task states
Blocked
This is highest priority ready task Task needs something to happen before it continues
Ready
Running
Example
//"Button task void vButtontask(void) //Higher priority { while (TRUE) { !! Block until user pushes button !! Button pressed. Respond to user } } //"levels task void vlevelsTask(void) //low priority { While (TRUE) { !! Read levels of floats !! calculate average float level } }
Task sequence
RTOS initialization
void main(void) { //Initialize the RTOS InitRTOS(); //Tell tghe RTOS about our tasks StartTask(vRespondTobutton,HIGH_PRIORITY); StartTask(vcalculateTankLevel,LOW_PRIORITY); //Start the RTOS StartRTOS(): //This function never returns
Task1
Global data
Task 1 registers
Task2
Task3
Task 2 stack
Task 2 registers
Task 3 stack
Task 3 registers
Shared data
struct { long ltanklevel; long lTimeUpdated; }tankdata[MAX_TANKS] //Button task void vRespondToButton (void) //High priority { !!Block until user pushes a button i=ID of the button pressed printf("", tankdata[i]); } //levels task void vcalculaeTankLevels(void) { int i=0; while (TRUE) { !!Read levels of tank !! do calculations //store the result tankdata[i].lTimeUpdated==CurrentTime // Bad place for task switching tankdata[i].lTanklevel= !1result of calculation }
Bug!!
Bug!
Reentrancy
Reentrancy A function that works correctly regardless of the number of tasks that call it between interrupts
Reentrancy
Inspecting code to determine Reentrancy: Where are data stored in C? Shared, nonshared, or stacked? Is this code reentrant? What about variable fError? Is printf reentrant? If shared variables are not protected, could they be accessed using single assembly instructions (guaranteeing non-atomicity)?
Semaphores
Semaphores
struct { long ltanklevel; long lTimeUpdated; } tankData[MAX_TANKS] //Button task void vRespondToButton(void) { int i; while (TRUE) { !! Block until user pushes the button i=!!get ID of the button pressed TakeSemahore(); printf(""tankData[i].lTimeUpdated, ltankLevel); ReleaseSemaphore(); } } //levels task //Low priority void vcalculatetankLevels(void) { int i=0; while (TRUE) { ..; ..; TakeSemaphore(); !! Set ankdata[i].lTimeUpdated; !! set tankdata[i].lTakLevel; ReleaseSemaphore(); } }
void main(void) { //Init the RTOS OSInit(); //Tell the RTOS about the tasks OSTaskCreate (vReadTemparatureTask,NULLP, void Controltask(void) (void*) Readstk[STK_SIZE],TASK_PRIORITY_READ); { OSTaskCreate (vControlTask,NULLP, p_semtemp=OSSemInit(1); (void*) &Controlstk [STK_SIZE], TASK_PRIORITY_CONTROL) ; while (TRUE) OSStart(); { } OSSempend (p_semptemp,WAIT_FOREVER); if (iTemperatures[0]!=iTemparatures[1]) !! Set of alaram; Bug! OSSemPost (p_semtemp); !!1 Do other useful work Put this before ..; OSStart()! } }
Re-entrant
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.
Priority inversion
Resolved by priority inheritance by some RTOS They temporarily boost the priority of task C to that of task A whenevr task C holds the semaphore and task A is waiting for it.
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); }
Semaphore Variants
Binary semaphores single resource, one-at-a time, alternating in use (also for resources) Counting semaphores multiple instances of resources, increase/decrease of integer semaphore variable Mutex protects data shared while dealing with priority inversion problem
Sample queue
//RTOS queue function prototypes void vLogError(int iErrorType) void AddToQueue (init iData); { void ReadFromQueue(int *p_iData); AddToQueue (iErrorType); void pTask1(void) } { static int cErrors; ; void ErrorsTask(void) ; { if (!!problem arises) int iErrorType; vLogError(ERROR_TYPE_X); while (TRUE) !!Other things that need to be done { soon ReadFromQueue (&iErrorType); ; ++cErrors; ; !! Send cErrors and iError type on } network void Task2(void) } { } ; ; if (!!problem arises) vLogError(ERROR_TYPE_Y); !! other things that need to be done soon CS C 424 Software for Embedded systems }
Queues
Queue initialization (like semaphore initialization) must be dedicated to a separate task to a) guarantee correct startup values and b) avoid uncertainty about task priorities and order of execution which might affect the queues content Queues must be tagged (identify which queue is referenced) Need code to manage the queue (when full and empty) if RTOS doesnt block reading/writing task on empty/full, plus returning an error code RTOS may limit the amount of info to write/read to queue in any single call
vLogError(ERROR_TYPE_Y); !! other things that need to be done ; } void vLogError(int iErrorType) { #define SIZEOF_QUEUE 25 //Return code from writing from queue void *apvQueue[SIZEOF_QUEUE]; BYTE byReturn; void main() byReturn=OSQPost(pOseQueue,(void*) { iErrorType); ; if (byReturn!=OS_NO_ERR) pOseQueue=OSQCreate (apvQueue,SIZEOF_QUEUE); !! handle the situation that arises when the ; queue is full !!start task1; }static int cErrors; !!start task2; void ErrorsTask (void) ; { } int iErrorType; void task1(void) BYTE byErr; { while(FOREVER) ; { if (!!problem arises) iErrorType=(int) vLogError(ERROR_TYPE_X); OSQPend(pOseQueue,WAIT_FOREEVER,&byErr); !! other things that need to be done ++cErrors; ; } } }systems CS C 424 Software for Embedded
} }
Using Mailboxes:
Similar to queues Typical RTOS function for managing mailboxes
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 length for queues / mailboxes) Pipes could be byte-oriented and read/write by tasks depends on # bytes specified In standard C, read/write of pipes use fread/fwrite functions, respectively
Timer Functions
RTOS provides these timing services or functions
Some points:
Time measured in ticks Relies on microprocessors hardware timer and its interrupt cycles Length of a tick depends on the hardware timers design trade-off Accurate timing short tick intervals OR use dedicated timer for purpose
Events
In standard OS, an event is typically an indication which is related to time In RTOS, an event is a boolean flag, which is set and reset by tasks/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
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 event ajevsig(amxIdTrigger,TRIGGER_MASK,TRIGGER_SET); ; } void vScanTask(void) { ; ; while (TRUE) { //Wait for the user to pull the trigger ajewat(amxIdTrigger,TRIGGER_MASK,TRIGGER_SET,WAIT_FOR_ANY,WAIT_FOREVER); //Reset the trigger event ajevsig(amxIdTrigger,TRIGGER_MASK,TRIGGER_RESET); ; } }
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 automatically or your embedded software Tasks can wait on only one semaphore, queue, mbox or pipe, but on many events simultaneously. Semaphores are faster, but unlike queues, mboxes, and pipes, they carry 1-bit info Queues, mboxes, and pipes are message posting/retrieval is compute-intensive
Memory Management
In general RTOS offer C lang equivalent of malloc and free for MM, which are slow and unpredictable Real time system engineers prefer the faster and more predictable 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 be valid) Note that most embedded sw is integrated with the RTOS (same address space) and the ES starts the microprocessor; hence your ES must tell the memory-pool
P_vMemory
uBuffCount
uBuffSize
Priorities
Priorities (advantage of using RTOS software architecture):
Decomposing based on functionality and time criticality, separates ES components into tasks (naturally), for quicker response time using task prioritization high priority for time-critical ones, and low priority for others
Example
There are 255 EVMs which have to be connected to a central processing unit (CP). CP holds the IDs of voters, their thumb signatures and voted option. Communicates with EVMs through messages. Role of EVM:
When user places thumb, EVM generates a signature. Sends the signature to CP. Receives the assertion/negation message sent by CP. 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 kept pressed for 5 sec) and sends the selection to CP. Receives ACK sent by CP in response to EVMs message. EVM glows done! and ready to take next user. Maintains IDs of voters, their thumb signatures and voted options. Gets messages from all EVMs and responds the action taken. Receives the signature from EVM. Verifies if the signature is correct and the user has not voted. Sends assert/negate message in response to this Receives candidate selection from EVM . updates the selection and acknowledges to Software for Embedded systems CS C 424 EVM
C1 C3
Place thumb here Select one from right
C3 C4
Done!
Invalid!
Role of CP:
Tasks
Message_Receiver Vote_registration Receives the messages from every EVM . Receives a record from the buffer needing to store Puts into received messages queue candidate selection Suspends itself for next message to arrive. Interacts with data access layer and updates the data Removes the record from buffer once the registration is successful Message Decoder Posts acknowledgement data to be sent to EVM to Decodes the received message message encoder Updates the action buffer with the information decoded from message. Message Encoder Ex: EVM ID, verify operation, signature. Receives data Adds a session number Frames appropriate message Posts into Transmit Queue Set verify event Waits for a message to be encoded Suspends till the next message to be decoded Message_Transmitter Signature verifier Receives a record from the buffer needing Pulls a message from transmit queue an action to verify the signature. Transmits to the EVM to be notified. Interacts with data access layer and verifies Sleeps if there are no messages to be transmitted the signature. Watchdog Extracts the ID of the person. Updates the buffer with the ID Checks action buffer every one second for any time outs. Updates the buffer state. Generates error message and posts to message encoder Posts data to be sent to EVM to message Deletes the record from action buffer. encoder Clear verify event Waits on verify event. CS C 424 Software for Embedded systems
Objects
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)
Interaction
sd task interaction Message receiver EVM MessageDecoder signatureVerifier MessageEncoder Messagetransmi... Vote_registration
OnMessageReceived()
PostMessageinReceivequeue() OnmessagePostedinreceivequeue()
Onvoter select() Update database and set action buffer, send message to encoder()
References
An embedded software primer by David E Simon, Addison Wesley Real-Time Systems by Jane Liu, Pearson ed.,2000.