Jean J. Labrosse
www.Micrium.com
My Background
Masters Degree in Electrical Engineering Wrote two books (C/OS-II and ESBB) Wrote many papers for magazines
Embedded Systems Programming Electronic Design C/C++ Users Journal ASME Xcell Journal
ESC advisory committee member Have been designing Embedded Systems for over 20 years President of Micrim
Provider of Embedded Software Solutions
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
1
My Objectives
Have you understand:
What a real-time kernel is How a kernel works How to use some of the features of a kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Special Notes
Please turn OFF your Cell Phone
Or set to vibrate
Please ask questions at any time. Please complete the evaluation sheet
at the end of the class or, if you have to leave early!
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
2
Tutorial Layout
Part I
Part II
Foreground/Background systems Real-Time Kernels Task Management Task Scheduling Context Switching Servicing Interrupts Time Delays and Timeouts
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Tutorial Layout
Part III
Part IV
Resource sharing and Mutual Exclusion Task Synchronization Inter-task Communications Memory Management Initialization Execution Times Recommendations Buying a Kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
3
Part I
Foreground/Background Systems
Real-Time Kernels Task Management
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
(Foreground/Background Systems)
Foreground #2
ISR #2
Foreground #1
ISR #1
ISR #1
Background
Task #1
Task #2
Task #3
Infinite loop
Time
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
4
Foreground/Background
/* Background */ void main (void) { Initialization; FOREVER { Read analog inputs; Read discrete inputs; Perform monitoring functions; Perform control functions; Update analog outputs; Update discrete outputs; Scan keyboard; Handle user interface; Update display; Handle communication requests; Other... } }
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Foreground/Background
Advantages Used in low cost Embedded Applications Memory requirements only depends on your application Single stack area for:
Function nesting Local variables ISR nesting
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
5
Foreground/Background
Disadvantages Background response time is the background execution time
Non-deterministic
Affected by if, for, while ...
Task #1
Task #2
Task #3
Task #4
Infinite loop
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Foreground/Background
Disadvantages
Task #1
Task #2
Task #3
Task #4
Infinite loop
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
6
Foreground/Background
Disadvantages You have to implement all services:
Time delays and timeouts Timers Message passing Resource management
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Part I
Foreground/Background Systems
Real-Time Kernels
Task Management
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
7
Allows Multitasking:
Do more than one thing at the same time. Application is broken down into multiple tasks each handling one aspect of your application Its like having multiple CPUs!
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
RTOS
I/Os
Application
Net
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
File System
Real-Time Kernels
Jean J. Labrosse
8
Adding low-priority tasks generally does not change the responsiveness to higher priority tasks!
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
4-bit CPUs cant 8-bit CPUs can 16-bit CPUs should 32-bit+ CPUs is highly recommended!
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
9
Kernel will disable interrupts! Can your application afford the extra costs?
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
10
Extra RAM
May mean bigger chip(s)
Learning curve
Couple of days to a few weeks
Need reentrant functions Need to be careful with shared resources Adds CPU overhead
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Task Importance
Each Task
Event Event
Task
Task
Task
Infinite Loop
Task
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
11
Types of Kernels
(Non-Preemptive)
ISR make High Priority Task Ready ISR Completes (Return to Task)
ISR
ISR
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Types of Kernels
(Preemptive)
Interrupt Occurs Vector to ISR ISR make High Priority Task Ready ISR Completes (Switch to HP Task)
ISR
ISR
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
12
Part I
Task Management
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
13
*/ */ */ */ */
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Task States
Resident in ROM (Non-active) Dormant Waiting For Execution Event Occurs Or Timeout Delete Task
Create Task
Ready
Context Switch
Waiting
For
Event Wait for time to expire Wait for a message Wait for a signal
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Running
Real-Time Kernels
Jean J. Labrosse
14
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Creating a Task
You create a task by calling a service provided by the kernel:
OSTaskCreate(void (*task)(void *p_arg), void *p_arg, void *pstk, INT8U prio);
before you start multitasking (at init-time) or, during (at run-time).
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
15
ERR_CODE OSTaskCreate (task, p_arg, ptos, prio) { if (a TCB is available) Initialize the TCB; else Priority of your Return an error code; Task Initialize the tasks stack; Increment the number of tasks counter; Make task ready-to-run; if (OS is running) { Call the scheduler; } }
Real-Time Kernels Real-Time Kernels
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Creating a Task
(80x86 Large Model) Task Stack
(RAM)
80x86 CPU
(Real Mode)
SS SP
TCB
DS ES DI SI
(3)
(RAM)
AX BX CX DX DS ES SI DI BP CS PSW IP
Ready Priority
(1)
(2)
BP SP BX DX CX AX IP CS PSW
Real-Time Kernels
Jean J. Labrosse
16
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
DS ES DI SI BP SP BX DX CX AX IP CS PSW
DS ES DI SI BP SP BX DX CX AX IP CS PSW
DS ES DI SI BP SP BX DX CX AX IP CS PSW
DS ES DI SI BP SP BX DX CX AX IP CS PSW
DS ES DI SI BP SP BX DX CX AX IP CS PSW
Task Stacks
Task List
Priority Ready
Priority Ready
Priority Ready
Priority Ready
Priority Ready
TCBs
NULL
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
17
Stack Checking
Stacks can be checked at run-time to see if you allocated sufficient RAM Allows you to know the worst case stack growth of your task(s) Assumes stack is cleared when task is created
Could check for other patterns than 0x00
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Stack Checking
(Implementation)
INT32U OSTaskStkChk(prio) #elements = 0; pbos = Point at bottom of task stack; ptos = Point at top of task stack; while (*pbos == 0x00 && pbos != ptos) #elements++; pbos++; return (#elements * sizeof(element));
TOS Used Stack Size Free
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
18
Deleting a Task
Tasks can be deleted (return to the dormant state) at run-time
Task can no longer be scheduled
Code is NOT actually deleted Can be used to abort (or kill) a task TCB freed and task stack could be reused.
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
19
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Sensors
Storage Media
Command
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
20
ISR
VS
ISR Task ABC
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
In general, task body should consume much more CPU time than twice the time of a context switch Keep tasks simple! A task can call multiple functions to do its work
Task Exec. Time >> 2 x Context Switch Time
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
21
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Control loops Communications Error handlers (protection systems) I/O (analog, digital, discrete...) etc.
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
22
A Practitioners Handbook for Real-Time Analysis, Guide to RMA for Real-Time Systems,
Mark H. Klein, Kluwer Academic Publishers, ISBN 0-7923-9361-9
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Part II
Task Scheduling
Context Switching Servicing Interrupts Time delays and Timeouts
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
23
What is Scheduling?
Deciding whether there is a more important task to run. Occurs:
When a task decides to wait for time to expire When a task sends a message or a signal to another task When an ISR sends a message or a signal to a task
Occurs at the end of all nested ISRs
Outcome:
Context Switch if a more important task has been made ready-to-run or returns to the caller or the interrupted task
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
The time quantum is generally configurable A task can give up its time slice
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
24
The highest priority task is kept at the beginning of the list. Singly or Doubly linked lists ?
Ready List Ptr
TCB TCB TCB TCB
NULL
OSRdyTbl[ ]
[0] [1] [2] [3] [4] [5] [6] [7]
7 15 23 31 39 47 55 63 6 14 22 30 38 46 54 62 5 13 21 29 37 45 53 61 4 12 20 28 36 44 52 60 3 11 19 27 35 43 51 59 2 10 18 26 34 42 50 58 1 9 17 25 33 41 49 57 0 8 16 24 32 40 48 56
X
Lowest Priority Task (Idle Task)
Task Priority #
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
25
0xF6
OSRdyTbl[ ]
0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0x78
Y=1
0 0 1 0
X=3
1 1
Task Priority
Lookup Table
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Y=1
Lookup Table
X=3
Bit Position #11
11
Real-Time Kernels
Jean J. Labrosse
26
Priority Resolution
HighestPriority = 11
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Scheduling
(Delaying a Task)
void TaskAtPrio0 (void) Task at Priority 0 runs { while (TRUE) { . OSTimeDlyHMSM(0, 0, 1, 0); . Task needs to suspend for 1 second . } OSRdyGrp OSRdyTbl[ ] } 1 1 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 1
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
27
Scheduling
OSRdyGrp
1 1 1 1 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0
OSRdyTbl[ ]
0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
OSTCBPrioTbl[ ]
[0] [1] [2] [3] [4] [5] [6]
Old TCB
0 0 1
New TCB
[11]
(1)
Find Highest Priority Task Ready
(2)
Index to Find TCB
[60] [61] [62] [63]
11
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Part II
Task Scheduling
Context Switching
Servicing Interrupts Time delays and Timeouts
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
28
Context Switch
(or Task Switch) Once the kernel finds a NEW High-PriorityTask, the kernel performs a Context Switch. The context is the volatile state of a CPU
Generally the CPU registers 80486 and Pentiums also have Floating-Point registers In Protected Mode the context would also include the MMU
Every kernel does the context switch about the same way.
Some CPUs have special instructions for this
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Context Switch
(or Task Switch)
Click on Image
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
29
; Save SS:SP
; OSTCBCur = OSTCBHighRdy
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Part II
Servicing Interrupts
Time delays and Timeouts
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
30
Interrupts
Interrupts are always more important than tasks! Interrupts are always recognized
Except when they are disabled by the kernel or your application Your application can disable interrupts for as much time as the kernel does
Your kernel vendor should specify the interrupt disable time
C/OS-II disables interrupts for less than 2 S on a 66 MHz 80486.
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Interrupts
You should keep ISRs (Interrupt Service Routines) as short as possible. Interrupts either use an interrupt stack or the tasks stack.
Size of stack must account for:
Worst case ISR nesting. Worst case function call nesting. Local variables
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
31
Whats in an ISR?
If a more important task is Ready, the Kernel will do a Context Switch YourISR: Save CPU Registers; Notify kernel of ISR entry; Process ISR (Your code!); /* Take care of device */ /* Buffer data */ /* Clear interrupt */ /* Signal task to process data */ Notify kernel about end of ISR; Restore CPU Registers; Return from Interrupt;
Whats in an ISR?
Your ISR must tell the kernel that you are starting an ISR
ISR_Entry() ISR_Nesting_Counter++;
Your ISRs must tell the kernel that you are done processing an interrupt
Could cause a context switch or, Return to the interrupted task
ISR Exit() ISR_Nesting_Counter--; if (ISR_Nesting_Counter == 0) Find highest priority task ready; Perform context switch;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
32
Servicing Interrupts
(1) TASK (3) Vect (4) Save (5) Ent (6) User ISR (2), Interrupts enabled Interrupt Recovery TASK (9), RTI (8), Restore Exit (7), Kernel ISR Exit function
No HPT Ready
Exit Interrupt Response ISR (3): Save CPU Registers (4); Call Kernel ISR Entry function (5);
Sched.
(7), Kernel ISR Exit function (8), Restore (9), RTI HPT Task
Servicing Interrupts
(1) TASK (3) Vect (4) Save (5) Ent (6) User ISR OSQPost() (8 S) (2), Interrupts enabled
Exit
Sched.
(7), Kernel ISR Exit function (8), Restore (9), RTI HPT Task
Interrupt Response (2 to 4 S)
Interrupt Recovery (9 S)
19 to 21 S
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
33
Part II
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Called a Clock Tick or System Tick Higher the rate, the more the overhead!
The tick ISR calls a service provided by the kernel to signal a tick
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
34
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Time Delays
The kernel maintains a list of tasks waiting for time to expire
Delayed tasks are placed in a delayed list The list can be a Delta List
Insertion/extraction takes time ISR short except for worst case (all zeros)
Linear List
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Delta List
Real-Time Kernels Real-Time Kernels
Real-Time Kernels
Jean J. Labrosse
35
If the tick rate is 100 Hz (10 mS), a keyboard scan every 100 mS requires 10 ticks:
Keyboard_Scan_Task (void) { for (;;) { OSTimeDly(10); /* Every 100 mS */ Scan keyboard; } }
Tick
20 mS 20 mS 20 mS
HPT Tasks
> 20 mS < 20 mS < 20 mS
LPT Tasks
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
36
Example #1
(Time Delays)
Click on Image
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
37
Timeout of 10 ticks.
for (;;) { Start ADC; msg = OSMboxPend(.., .., 10, &err); if (err == OS_NO_ERR) { Read ADC and Scale; } else { /* Problem with ADC converter! */ } } }
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
ISR
OS
HPT
Scheduling & Context Switching (Overhead) OS
MPT
OS
LPT
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
38
Part III
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Resource Sharing
YOU MUST ensure that access to common resources is protected!
The kernel only gives you mechanisms
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
39
Resource Sharing
rpm = 60.0 / time; Disable interrupts; Global RPM = rpm; Enable interrupts;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Resource Sharing
Unlock invokes the scheduler to see if a HighPriority Task has been made ready while locked
Real-Time Kernels
Jean J. Labrosse
40
Mutual Exclusion
(Semaphores) Used when time to access a resource is longer than the kernel interrupt disable time! Binary semaphores are used to access a single resource Counting semaphores are used to access multiple resources
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Mutual Exclusion
(Semaphores)
Task 1 High
Semaphore
Resource
Variable(s) Data Structure(s) I/O Device(s)
Tasks
Task 2 Medium
Task 3 Low
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
41
Semaphores
Two types: Binary and Counting. Operations on semaphores:
Create (sets initial value) Wait (with timeout) Signal
Contains a value (0..65535) Contains a list of tasks waiting for the semaphore
Semaphore Value = 0
Tasks Waiting on Semaphore
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
HPT TCB
MPT TCB
Semaphores
(Implementation)
SEM *OSSemCreate(value) sem = Allocate a Semaphore Control Block (SCB); sem->Value = value; sem->Waitinglist = no tasks waiting; Return semaphore handle to caller;
ERR_CODE OSSemWait(sem, timeout) if (sem->Value > 0) sem->Value--; return no error to caller; else Place calling task in wait list; Run NEXT highest priority task ready; if (timed out) return timed-out status to caller; else return no error to caller;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
42
Semaphores
(Implementation)
ERR_CODE OSSemSignal(sem) if (sem->WaitingList == Task(s) waiting) Make highest priority task waiting ready; Run highest priority task ready; else sem->Value++; return no error to caller;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
App. Task
HPT
1 2
Clock Task
LPT
Update Clock
Clock Variables
ClockTask(void) { while (TRUE) { Wait for signal from tick ISR; Acquire semaphore; Update clock; Release semaphore; } }
Real-Time Kernels Real-Time Kernels
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
43
A Counting Semaphore?
(Situation without Counting Semaphore) Tick interrupt is never missed and always runs All higher priority interrupts take more than 20 mS to execute! Time-of-Day clock task misses 1 tick!
Clock loses track of time!
20 mS Tick ISR All Higher Priority Tasks Clock Task
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Counting Semaphore
(Serial Communications (Rx)) Rx ISR:
Reads and buffers character Clears interrupt source Signals semaphore (every character)
Rx Task:
To reduce overhead, could signal only when a special character such as CR, LF, end-of-packet delimiter is received.
Rx Task
3 2
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
44
Semaphores
(Priority Inversion) Delay to a tasks execution caused by interference from lower priority tasks All tasks of medium priority would delay access of the HPT to the resource! LPT Releases
Semaphore High Priority Task Preempts Low One Task needs semaphore LPT owns it
Medium Priority Task Preempts Low One Real-Time Kernels Real-Time Kernels
Semaphores
(Priority Inheritance) Low Priority task assumes priority of High Priority task while accessing semaphore. Some kernels have automatic priority inheritance protocols.
High Priority Task Preempts Low One Task Needs Semaphore Kernel raises LPTs Priority
HPT is done
Real-Time Kernels
Jean J. Labrosse
45
Kernel needs to support multiple tasks at the same priority. Operations on mutex:
Create (initial value is always 1) Wait (with timeout) Signal
Value = 1 Original Task Prio Ptr to Mutex Owner Tasks waiting for Mutex NULL
TCB
TCB
TCB
Mutex
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Part III
Task Synchronization
Inter-Task Communications
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
46
Event Flags
Synchronization of tasks with the occurrence of multiple events Events are grouped
8, 16 or 32 bits per group
Types of synchronization:
Task(s) or ISR(s) can either Set or Clear event flags Only tasks can Wait for events
Disjunctive (OR): Any event occurred Conjunctive (AND): All events occurred
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Event Flags
ISRs
TASKs
OR
Wait
TASKs
AND
Wait
TASKs
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
47
Event Flags
(Implementation)
NULL
Type (AND or OR) Type (AND or OR) Type (AND or OR)
TCB
TCB
TCB
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Event Flags
(Implementation)
EFLAG *OSEFlagCreate(init_value) eflag = Create event flag group; eflag->Value = init_value; eflag->WaitingList = No task waiting; Return event flag group handle to caller;
OSEFlagSet(eflag, mask) eflag->Value |= mask; for (ALL tasks waiting on this group) if (Task conditions are satisfied) Make task ready-to-run; if (any task made ready) { Run highest priority task ready;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
48
Event Flags
(Example)
Abort ISR
Abort
RPM Task
RPM == 0 RPM > 3000 Temp < 200 Fuel > 1% Event Flag Group
OR
Wait
AI Task
Abort Task
Start Stop
AND
Wait
Start Task
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Synchronization
(Analog-Digital Conversion)
ADC Analog Inputs MUX AI Driver
ISR
Read_Analog_Input_Channel_Cnts(channel#, *adc_counts) { Select the desired analog input channel Wait for MUX output to stabilize Start the ADC Conversion Wait for signal from ADC ISR (with timeout) if (timed out) Return error code to caller else Read ADC counts Return ADC counts to caller }
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
49
Part III
Inter-Task Communications
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Message Queues
Message passing FIFO (First-In-First-Out) type queue
Message is a pointer Pointer can point to a variable or a data structure Size of each queue can be specified to the kernel
LIFO (Last-In-First-Out) also possible Tasks or ISR can send messages Only tasks can receive a message
Receiving task can timeout if no message is received within a certain amount of time
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
50
Message Queues
(Implementation)
Tasks waiting for Mutex NULL #Entries = 4 Queue Size = 6 Queue Start Out Pointer In Pointer NULL
TCB
TCB
TCB
Message Queue
Pointers to Data
Circular Buffer
In Pointer
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Message Queues
(Implementation)
QUEUE *OSQCreate(size) q = Allocate a Queue Control Block (QCB); q->Start = Allocate storage for messages; q->Entries = 0; q->OutPointer = beginning of queue; q->InPointer = beginning of queue; q->Size = size; q->WaitingList = No tasks waiting; Return queue handle to caller;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
51
Message Queues
(Implementation)
void *OSQPend(q, timeout, *err) if (q->Entries > 0) Return oldest message deposited in the queue; Return no error to caller; else Place calling task in wait list; Run NEXT highest priority task ready; if (timed out) Return timed out to caller; else Return message to caller;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Message Queues
(Implementation)
void OSQPost(q, message, *err) if (q->WaitingList == Task(s) waiting) Make highest priority task waiting ready; Give message to task; Run highest priority task ready; else Deposit message into queue; Return no error to caller;
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
52
Rx ISR
Rx Task
RxISR(void) { Read character from UART if (1st character of message) Get a buffer from Buffer Manager Put character in buffer if (End of Packet character) Send packet to RxTask for processing }
RxTask(void) { PACKET *pmsg; while (1) pmsg = OSQPend(RxQ, timeout) Process packet received Return packet buffer to Buffer Manager }
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Message Queue
(Error Handling) Error conditions are detected by tasks and ISRs then sent to an error handler The error handler acts as a server to client tasks and ISRs The error handler can:
Issue warnings and/or shutdowns Initiate corrective action(s)
Task
Message Queue
Task ISR
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Error Task
Real-Time Kernels
Jean J. Labrosse
53
Message Mailbox
(RPM Measurement)
ISR
16-Bit Timer
RPM Task
Counts=Fin * t Fin
RPM_ISR() { Read Timer; DeltaCounts = Counts PreviousCounts; PreviousCounts = Counts Post DeltaCounts; }
RPMTask() { while (1) Wait for message from ISR (with timeout); if (timed out) RPM = 0; else RPM = 60 * Fin / counts; Compute average RPM; Check for overspeed/underspeed; Keep track of peak RPM; etc. } Real-Time Kernels Real-Time Kernels
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Example #2
(Intertask Communications)
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
54
Part IV
Memory Management
Initialization Execution Times Recommendations Buying a Kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Memory Manager
Most kernels provide fixed-sized memory block management Multiple partitions can be created with each having a different block size You MUST ensure that you return blocks to the proper partition. Partitions can be extended from a larger block.
Prevents fragmentation
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
55
Memory Manager
(Implementation)
MEM_BLK *OSMemCreate(n_blocks, block_size) pmem = Allocate a memory control block; Allocate storage: n_blocks * block_size; Link all blocks; pmem->BlocksLeft = n_blocks; pmem->NBlocks = n_blocks; pmem->BlockSize = block_size; Return pointer to memory control block;
NULL
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Memory Manager
(Implementation)
void *OSMemGet(pmem, *err) if (pmem->BlocksLeft > 0) Get pointer to next free block; Adjust free list pointer; pmem->BlocksLeft--; *err = no error; return pointer to allocated block; else *err = no more free blocks return NULL pointer;
pblock Memory Partition Control Block pmem
NBlocks BlockSize BlocksLeft
NULL
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
56
Memory Manager
(Implementation)
pblock
NULL
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Memory Manager
(Multiple Partitions)
Memory Partition Control Block pmem1
Block Size #Blocks #Free Blocks
NULL
pmem2
Block Size #Blocks #Free Blocks
NULL
pmem3
Block Size #Blocks #Free Blocks
NULL
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
57
Part IV
Memory Management
Initialization
Execution Times Recommendations Buying a Kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Initialization
Kernels provide an initialization function You must create at least one task before starting multitasking Kernels provide a startup function
void main (void) { /* User initialization OSInit(); */
/* Kernel Initialization */ */
/* Start multitasking
Real-Time Kernels Real-Time Kernels
*/
Real-Time Kernels
Jean J. Labrosse
58
Initialization
You should initialize the ticker in the first task to run.
Dont want to be interrupted until fully initialized Setup hardware timer Enable timer interrupt
void StartTask (void) { /* Task Initialization */ /* Setup hardware timer for CLOCK tick */ /* Enable GLOBAL interrupts */ /* Create OTHER tasks as needed */ while (1) { /* Task body (YOUR code) } }
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
*/
Part IV
Execution Times
Recommendations Buying a Kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
59
Execution Times
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Example #3
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
60
Part IV
Recommendations
Buying a Kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Recommendations
Dont have too many tasks
Increases the overhead Increases RAM
Dont allocate large arrays on the stack of a task Use only reentrant functions and compilers Dont write recursive code
Eats up stack space quickly!
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
61
Recommendations
Guard resources with either:
Disable/Enable interrupts Semaphores Server tasks Lock/Unlock the scheduler Get/put data from/to device Clear source and return from interrupt Have task handle the data Avoid long calculations and especially floatingpoint math.
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Recommendations
Keep task interaction to a minimum
You have a poor design if you have a lot of intertask communication
Always good to know ahead of time roughly how much CPU time each task takes
Difficult to determine and generally not constant (if, for, while, do - while etc.) Analyze the most time critical tasks Useful for RMS/RMA
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
62
Recommendations
You CAN design a basic kernel in a weekend over a couple of boxes of Pizza and Beer! You CANT (in a weekend):
Fully test a kernel Document it
API reference How the kernel works
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Part IV
Buying a Kernel
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
63
Buying a Kernel?
General features:
Get a Preemptive kernel Get a kernel that allows you to specify a different stack size for each task. Try to get from the kernel vendor:
the maximum interrupt disable time the context switch time the execution times of services
Execution Time:
Memory requirements:
How much RAM/ROM? Can you scale the kernel to reduce RAM/ROM?
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Buying a Kernel?
Cost:
Is this important to you? Good security in case vendor goes out of business Allows you to make changes/improvements
No support if you change the code!
You may want to port your application or, some of its modules to other processors
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
64
Buying a Kernel?
Technical Support?
Training Application notes Technical assistance Consulting services available Web site
Miscellaneous
Kernel is third party certifiable (FAA/FDA )?
Vendor specific:
Reputation? References?
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Buying a Kernel?
Vendor provides integrated products?
Compilers/Assemblers/Linkers File system
DOS compatible files
Reentrant libraries Board Support Packages (BSPs) Quality and completeness of documentation Debugger
Kernel awareness Profiling
Real-Time Kernels Real-Time Kernels
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
65
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
66
References
A Practitioners Handbook for Real-Time Analysis: Guide to RMA for Real-Time Systems
Mark H. Klein, Kluwer Academic Publishers
ISBN 0-7923-9361-9
Chinese
Korean
ISBN 1-57820-103-9
Korean
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Thank You.
Dont Forget.
Please Fill in the Evaluation Sheet.
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved
Real-Time Kernels
Jean J. Labrosse
67