You are on page 1of 67

Real-Time Kernels

Jean J. Labrosse

www.Micrium.com

My Background

ƒ Master’s Degree in Electrical Engineering


ƒ Wrote two books (µC/OS-II and ESBB)
ƒ Wrote many papers for magazines
– Embedded Systems Programming
– Electronic Design
– C/C++ User’s Journal
– ASME
– Xcell Journal
ƒ ESC advisory committee member
ƒ Have been designing Embedded Systems for
over 20 years
ƒ President of Micriµm
– Provider of Embedded Software Solutions

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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
ƒ Help you decide whether:
– You need a kernel
– You can use a kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Special Notes

ƒ Please turn OFF your Cell Phone


– Or set to vibrate
ƒ I assume you know C
ƒ I will use the Intel 80x86 in examples
– Some assembly language will be presented
ƒ I will use µC/OS-II in some examples
– I wrote µC/OS-II
– Other RTOSs may work differently
ƒ 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

2
Tutorial Layout

ƒ Part I
– Foreground/Background systems
– Real-Time Kernels
– Task Management
ƒ Part II
– Task Scheduling
– Context Switching
– Servicing Interrupts
– Time Delays and Timeouts

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Tutorial Layout

ƒ Part III
– Resource sharing and Mutual Exclusion
– Task Synchronization
– Inter-task Communications
ƒ Part IV
– Memory Management
– Initialization
– Execution Times
– Recommendations
– Buying a Kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

3
Part I

Foreground/Background Systems
Real-Time Kernels
Task Management

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Products without Kernels


(Foreground/Background Systems)

Foreground #2 ISR #2

Foreground #1 ISR #1 ISR #1

Background Task #1 Task #2 Task #3

Infinite loop

Time

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

4
Foreground/Background

/* Background */ /* Foreground */
void main (void) ISR (void)
{ {
Initialization; Handle asynchronous event;
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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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
ƒ Minimal interrupt latency
ƒ Low Cost
– No royalties to pay to vendors

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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 ...
– May not be responsive enough
– Changes as you change your code

Affected by if, for, while


Poll to see if ISR occurred ISR

Task #1 Task #2 Task #3 Task #4

Infinite loop

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Foreground/Background
Disadvantages

ƒ All ‘tasks’ have the same priority!


– Code executes in sequence
– If an important event occurs it’s handled at the same
priority as everything else!
– You may need to execute the same code often to
avoid missing an event.

Task #1 Task #2 Task #3 Task #4

Infinite loop

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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
ƒ Code is harder to maintain and can become
messy!

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part I

Foreground/Background Systems

Real-Time Kernels
Task Management

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

7
What is a Real-Time Kernel?

ƒ Software that manages the time of a


microprocessor or microcontroller.
– Ensures that the most important code runs first!
ƒ 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
– It’s like having multiple CPUs!
ƒ Provides valuable services to your application:
– Time delays
– Resource sharing
– Intertask communication and synchronization

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Why use a Kernel?

User Interface
ƒ To help manage your firmware:
– GUI (User Interface)
– File System
– Protocol Stack
– Application
– I/Os
RTOS I/Os

Application

Net File System


©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

8
Why use a Kernel?

ƒ To be more responsive to real-time events


ƒ To prioritize the work to be done by the CPU
ƒ To simplify system expansion
– Adding low-priority tasks generally does not
change the responsiveness to higher priority tasks!
ƒ To reduce development time
ƒ To easily split the application between
programmers
– Can simplify debugging
ƒ To get useful services from the kernel
– Services that you would want to provide to your
application code

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Can you use a Kernel?

ƒ Depends on the processor!


– 4-bit CPUs can’t
– 8-bit CPUs can
– 16-bit CPUs should
– 32-bit+ CPUs is highly recommended!
ƒ Do you have enough ROM ?
– 4K to 250K+ bytes extra

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

9
Can you use a Kernel?

ƒ Do you have enough RAM ?


– Kernel RAM
ƒ 20 to 350 bytes per task
– Task stacks
ƒ Each task requires its own stack!

ƒ Kernel will disable interrupts!


ƒ Can your application afford the extra
costs?

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

What are the Costs?

ƒ Development Seats
– $75 to $10,000 per seat (may be more)
ƒ Some Kernels require royalties
– Per-unit
ƒ Some kernels are ‘licensed’
– On a per-project basis
– For a product line
– Company wide
– Per-seat (i.e. per-developer)
– Per-CPU type
ƒ Maintenance for upgrades and bug fixes
– Typically 15-20% (of initial cost) per year

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

10
What are the Costs?

ƒ Extra ROM
– May mean bigger chip(s)
ƒ 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Designing with a Kernel


(Splitting an application into Tasks)

High Priority Task Task

Task Each Task

Importance Event Event


Task

Task Task

Infinite Loop
Low Priority Task Task

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

11
Types of Kernels
(Non-Preemptive)

Interrupt Occurs ISR make High Priority Task Ready


Vector to ISR
ISR
ISR ISR Completes
(Return to Task)

High Priority Task

Low Priority Task Low Priority Task


Completes
(Switch to HP Task)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Types of Kernels
(Preemptive)

Interrupt Occurs ISR make High Priority Task Ready


Vector to ISR
ISR
ISR ISR Completes
(Switch to HP Task)

High Priority Task (HPT)

Low Priority Task (LPT)

HP Task Completes
(Switch back to LP Task)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

12
Part I

Foreground/Background Systems
Real-Time Kernels

Task Management

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

What are Tasks?

ƒ A task is a simple program that thinks it has


the CPU all to itself.
ƒ Each Task has:
– Its own stack space
– A priority based on its importance

ƒ A task contains YOUR application code!

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

13
What are Tasks?

ƒ A task is an infinite loop:


void Task(void *pdata)
{
Do something with ‘argument’ pdata;
Task initialization;
for (;;) {
/* Processing (Your Code) */
Wait for event; /* Time to expire ... */
/* Signal from ISR ... */
/* Signal from task ... */
/* Processing (Your Code) */
}
}

ƒ A task can be in one of 5 states…

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Task States

Resident in ROM Delete


(Non-active) Task
Dormant

Waiting Create
For Task
Execution

Event Occurs Ready Context


Or Switch
Timeout

Waiting
For Running ISR
Event Wait
For
Wait for time to expire Event Task
Wait for a message Interrupted
Wait for a signal

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

14
Tasks needs to be ‘Created’

ƒ To make them ready for multitasking!


ƒ The kernel needs to have information
about your task:
– Its starting address
– Its top-of-stack (TOS)
– Its priority
– Arguments passed to the task

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

‘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);

ƒ You can create a task:


– before you start multitasking (at init-time) or,
– during (at run-time).

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

15
‘Task Create’ Pseudo-Code

Address of Address of
Task Top-Of-Stack

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 task’s stack;
Increment the number of tasks counter;
Make task ready-to-run;
if (OS is running) {
Call the scheduler;
}
}

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Creating a Task
(80x86 Large Model)

Task Stack Save Top Of Stack in TCB


80x86 CPU
(RAM) (Real Mode)

SS SP
TCB
(RAM)
(3) AX
DS
BX
ES
Ready
DI
Priority
(1) CX
DX
SI
BP DS
SP
(2) BX
ES

DX SI
CX DI
AX
Allocate & Initialize TCB
BP
IP
CS CS IP
PSW
PSW
Allocate & Initialize Stack Frame

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

16
Task Control Blocks
(TCBs)

ƒ A TCB is a data structure that is used by the


kernel for task management.
ƒ Each task is assigned a TCB when it is
‘created’.
ƒ A TCB contains:
– The task’s priority
– The task’s state (Ready, Waiting ...)
– A pointer to the task’s Top-Of-Stack (TOS)
– Other task related data
ƒ TCBs reside in RAM:
– 45 bytes for µC/OS-II and the 80x86 (Large Model)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Multiple Created Tasks


(Task Stacks and TCBs)

Task
DS

ES
DS

ES
DS

ES
DS

ES
DS

ES
Stacks
DI DI DI DI DI

SI SI SI SI SI

BP BP BP BP BP

SP SP SP SP SP

BX BX BX BX BX

DX DX DX DX DX

CX CX CX CX CX

AX AX AX AX AX

IP IP IP IP IP

CS CS CS CS CS

PSW PSW PSW PSW PSW

Task Priority Priority Priority Priority Priority TCBs


Ready Ready Ready Ready Ready

List NULL

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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
Growth Stack
0x00 Size
0x00 Free
0x00
0x00
BOS

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Changing a Task’s Priority

ƒ Kernels can allow tasks to change their


priority (or the priority of others) at run-
time

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

19
How to split an application into
Tasks?
ƒ Look for ‘parallel’ activities!
ƒ A periodic (cyclic) activity requires a task
ƒ Split application by functionality:
– Keyboard scanning
– Operator interface
– Display update
– Monitoring/Updating analog and discrete I/O
– Error handling
– Time-of-day clock
– Control
– Communications
– etc.

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

How to split an application into


Tasks?
ƒ Device Drivers can require one or more tasks
ƒ Client and Server Tasks
– Writing large amounts of data to EEPROM
(wait 5mS per byte)
– Writing to Disk or Flash
(erase cycle of some sectors can take > 1 second)

Message
Queue
Data Storage Storage
Sensors Logging Manager Media
Task Task
Command
Client Server
Data

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

20
How to split an application into
Tasks?
ƒ Reduce coupling between tasks
– A lot of inter-task communication is a sign of a bad
design!

Task Task Task


ISR
A B C

VS

Task
ISR
ABC

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

How to split an application into


Tasks?

ƒ Don’t have too few tasks!


– Defeats the purpose of having a kernel
ƒ Don’t have too many tasks!
– Increases the overhead and needs more RAM
ƒ In general, task body should consume much
more CPU time than twice the time of a
context switch
Task Exec. Time >> 2 x Context Switch Time
ƒ Keep tasks simple!
– A task can call multiple functions to do its
work

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

21
How to set Task Priorities?

ƒ Not trivial because of the complex nature of


some real-time systems
ƒ Not all tasks are time critical!
– Some tasks cannot miss their deadlines, others
can (HARD vs SOFT)
ƒ Low priority tasks:
– Keyboard scanning
– Operator interface
– Display updates
– etc.

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

How to set Task Priorities?

ƒ High priority tasks:


– Control loops
– Communications
– Error handlers (protection systems)
– I/O (analog, digital, discrete...)
– etc.
ƒ Rate Monotonic Scheduling...

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

22
How to set Task Priorities?
(Rate Monotonic Scheduling (RMS))

ƒ RMS: Tasks with the highest rate of execution


are given the highest priority.
ƒ The highest rate task may not be the most
important task.
– Some low frequency event may have a short deadline
ƒ “A Practitioner’s Handbook for Real-Time
Analysis, Guide to RMA for Real-Time Systems”,
– Mark H. Klein, Kluwer Academic Publishers, ISBN 0-7923-9361-9

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part II

Task Scheduling
Context Switching
Servicing Interrupts
Time delays and Timeouts

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Round Robin Scheduling

ƒ Tasks of equal priority can be Time Sliced


– Assumes the kernel supports multiple tasks at the
same priority
– Each task executes for a Time Quantum
– Assumes that time sliced tasks are ready-to-run
– No limit on number of tasks at same priority
ƒ The time quantum is generally configurable
ƒ A task can give up its time slice

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

24
The Ready List

ƒ The Kernel maintains a list of tasks that


are ready-to-run
– Tasks waiting for execution
ƒ The highest priority task is kept at the
beginning of the list.
ƒ Singly or Doubly linked lists ?

Ready List Ptr NULL

TCB TCB TCB TCB

Highest Lowest
Priority Priority
Task Task

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

A Different Ready List!


(µC/OS-II’s Ready List)

OSRdyGrp
7 6 5 4 3 2 1 0
OSRdyTbl[ ]
[0] 7 6 5 4 3 2 1 0

[1] 15 14 13 12 11 10 9 8

[2] 23 22 21 20 19 18 17 16

[3] 31 30 29 28 27 26 25 24
Y
[4] 39 38 37 36 35 34 33 32

[5] 47 46 45 44 43 42 41 40

[6] 55 54 53 52 51 50 49 48

[7] 63 62 61 60 59 58 57 56

Task Priority #
X
Lowest Priority Task
(Idle Task)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

25
Finding the
Highest Priority Task Ready
OSRdyGrp
0xF6 1 1 1 1 0 1 1 0
OSRdyTbl[ ]
0 0 0 0 0 0 0 0

0 1 1 1 1 0 0 0 0x78
0 0 1 0 0 0 0 0

0 0 0 0 0 0 0 0

0 0 1 0 0 1 0 0
X=3
0 0 1 0 0 0 0 0 Y=1
0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1

1 0 0 0 0 0 0 0
Task Priority

Lookup Y=1 Lookup X=3


Table Table
Bit Position
#11 11
©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Priority Resolution Table

/************************************************************
* PRIORITY RESOLUTION TABLE
*
* Note(s): 1) Index into table is bit pattern to resolve
* highest priority.
* 2) Indexed value corresponds to highest priority
* bit position (i.e. 0..7)
************************************************************/
INT8U const OSUnMapTbl[] = { (Step #2)
0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x00-0x0F
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x10-0x1F
X = @ [0x78]
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x20-0x2F (i.e. 0x78 = OSRdyTbl[1])
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x30-0x3F
6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x40-0x4F
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x50-0x5F
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x60-0x6F
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x70-0x7F
7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x80-0x8F
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x90-0x9F
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0xA0-0xAF (Step #1)
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0xB0-0xBF
6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0xC0-0xCF Y = @ [0xF6]
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0xD0-0xDF (i.e. 0xF6 = OSRdyGrp)
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0xE0-0xEF
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 // 0xF0-0xFF
};

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

26
Priority Resolution

Y = OSUnMapTbl[OSRdyGrp];
X = OSUnMapTbl[OSRdyTbl[Y]];
HighestPriority = (Y * 8) + X;

Y (i.e. 1) = OSUnMapTbl[0xF6];
X (i.e. 3) = OSUnMapTbl[0x78];
HighestPriority = (1 * 8) + 3;

HighestPriority = 11

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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 01 0 0 0 0 0 0 0 1
0
0 1 1 1 1 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 0 0

0 0 1 0 0 0 0 0

0 0 0 0 0 0 0 1
Kernel clears the Ready bit
1 0 0 0 0 0 0 0

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

27
Scheduling

OSRdyGrp OSRdyTbl[ ] OSTCBPrioTbl[ ] Old TCB


1 1 1 1 0 1 1 0 0 0 0 0 0 0 0 0 [0]
[1]
0 1 1 1 1 0 0 0
[2]
0 0 1 0 0 0 0 0
[3]
0 0 0 0 0 0 0 0 [4]
[5]
0 0 1 0 0 1 0 0
[6]
HPT Ready 0 0 1 0 0 0 0 0 [7]
(Bit 11) 0 0 0 0 0 0 0 1 [8]
[9]
1 0 0 0 0 0 0 0
[10] New TCB
[11]
(1)
Find
Highest Priority Task
Ready (2)
Index to Find TCB [60]
11 [61]
[62]
[63]

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part II

Task Scheduling

Context Switching
Servicing Interrupts
Time delays and Timeouts

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

28
Context Switch
(or Task Switch)

ƒ Once the kernel finds a NEW ‘High-Priority-


Task’, 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Context Switch
(or Task Switch)

Click on Image

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

29
Context Switch on 80x86
(Actual code for µC/OS-II)

_OSCtxSw PROC FAR


PUSHA ; Save context
PUSH ES
PUSH DS
MOV AX, SEG _OSTCBCur ; Save SS:SP
MOV DS, AX
LES BX, DWORD PTR DS:_OSTCBCur
MOV ES:[BX+2], SS
MOV ES:[BX+0], SP
MOV AX, WORD PTR DS:_OSTCBHighRdy+2 ; OSTCBCur = OSTCBHighRdy
MOV DX, WORD PTR DS:_OSTCBHighRdy
MOV WORD PTR DS:_OSTCBCur+2, AX
MOV WORD PTR DS:_OSTCBCur, DX
MOV AL, BYTE PTR DS:_OSPrioHighRdy ; OSPrioCur = OSPrioHighRdy
MOV BYTE PTR DS:_OSPrioCur, AL
LES BX, DWORD PTR DS:_OSTCBHighRdy ; Get new SS:SP
MOV SS, ES:[BX+2]
MOV SP, ES:[BX]
POP DS ; Restore new task’s context
POP ES
POPA
IRET
_OSCtxSw ENDP

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part II

Task Scheduling
Context Switching

Servicing Interrupts
Time delays and Timeouts

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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
ƒ µC/OS-II disables interrupts for less than 2 µS on a 66 MHz 80486.
– Your kernel vendor should specify the interrupt disable
time

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Interrupts

ƒ You should keep ISRs (Interrupt Service


Routines) as short as possible.
ƒ Interrupts either use an ‘interrupt stack’ or
the ‘task’s stack’.
– Size of stack must account for:
ƒ Worst case ISR nesting.
ƒ Worst case function call nesting.
ƒ Local variables

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

31
What’s in an ISR?

If a more important task is Ready,


YourISR: the Kernel will do a Context Switch
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;

There are no HP Tasks Ready,


Return to Interrupted Task!

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

What’s 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

32
Servicing Interrupts

(1) (2), Interrupts enabled Interrupt Recovery No HPT Ready


TASK TASK

(3) Vect (9), RTI

(4) Save (8), Restore

(5) Ent Exit (7), Kernel ISR Exit function


(6)
User ISR

Exit Sched. (7), Kernel ISR Exit function


Interrupt Response
(8), Restore

ISR (3): (9), RTI


Save CPU Registers (4);
Call Kernel ISR Entry function (5); HPT Task
Process ISR (6);
Call Kernel ISR Exit function (7);
Restore CPU Registers (8); HPT Ready
Return from Interrupt (9); Interrupt Recovery
Do Context Switch

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Servicing Interrupts
(µC/OS-II on 66 MHz Intel 80486)

15 to 17 µS
(1) (2), Interrupts enabled Interrupt Recovery
TASK (5 µS)

(3) Vect (9), RTI

(4) Save (8), Restore

(5) Ent Exit (7), Kernel ISR Exit function


(6)
User ISR
OSQPost() (7), Kernel ISR Exit function
Exit Sched.
(8 µS)
Interrupt Response
(2 to 4 µS) (8), Restore

(9), RTI

HPT Task
Interrupt Recovery
(9 µS)
19 to 21 µS

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

33
Part II

Task Scheduling
Context Switching
Servicing Interrupts

Time delays and Timeouts

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

The Clock Tick ISR

ƒ Every kernel requires a periodic interrupt


source
– Through a hardware timer
ƒ Between 10 and 100 ticks/sec. (Hz)
– Could be the power line frequency
ƒ 50 or 60 Hz
– 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

34
Why keep track of Clock Ticks?

ƒ To allow tasks to suspend execution for a


certain amount of time
– In integral number of ‘ticks’
ƒ OSTimeDly(ticks)
– In Hours, Minutes, Seconds and Milliseconds
ƒ OSTimeDlyHMSM(hr, min, sec, ms)

ƒ To provide timeouts for other services (more


on this later)
– Avoids waiting forever for events to occur
– Eliminates deadlocks

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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)

ƒ The list can also contain Timeouts from other


services

ListPtr TCB TCB TCB ListPtr TCB TCB TCB


NULL NULL
10 25 25 10 15 0

Linear List Delta List

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

35
Use of Time Delays

ƒ Delays a task for ‘n’ ticks


– Always forces a context switch
– Suspended task uses little or no CPU time
ƒ 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;
}
}

ƒ Not accurate ...

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Time Delays and Timeouts


(Not accurate)

HPT Task (void) LPT Task (void)


{ {
for (;;) { for (;;) {
OSTimeDly(1); OSTimeDly(1);
. .
. .
} }
} }
20 mS

Tick

20 mS 20 mS
20 mS
HPT
Tasks
> 20 mS < 20 mS
< 20 mS
LPT
Tasks

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

36
Example #1
(Time Delays)

Click on Image

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Use for Timeouts

ƒ To prevent waiting forever for events


ƒ To avoid deadlocks
ƒ Example:
– Read ‘slow’ ADC
– Timeout indicates that conversion didn’t occur
within the expected time.

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

37
Use for Timeouts

ADCTask (void)
{
void *msg;
INT8U err; 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Tasks Readied by Tick

Tick Interrupt HPT = High Priority Task

MPT = Medium Priority Task

LPT = Low Priority Task


ISR

OS

HPT

Scheduling & OS
Context Switching
(Overhead)
MPT

OS

LPT

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

38
Part III

Resource Sharing and Mutual Exclusion


Task Synchronization
Inter-Task Communications

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Resource Sharing

ƒ YOU MUST ensure that access to common


resources is protected!
– The kernel only gives you mechanisms
ƒ You protect access to common resources by:
– Disabling/Enabling interrupts
ƒ Some CPUs don’t allow you to do this in ‘user’ code
– Lock/Unlock
– Semaphores
– MUTEX (Mutual Exclusion Semaphores)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

39
Resource Sharing
(Disable and Enable Interrupts)

ƒ When access to resource is done quickly


– Must be less than Kernel interrupt disable time!
– Be careful with Floating-point!
ƒ Disable/Enable interrupts is the fastest way!
– Some kernels don’t allow you to disable interrupts

rpm = 60.0 / time;


Disable interrupts;
Global RPM = rpm;
Enable interrupts;

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Resource Sharing
(Lock/Unlock the Scheduler)

ƒ ‘Lock’ prevents the scheduler from changing tasks


– Interrupts are still enabled
– Can be used to access non-reentrant functions
– Can be used to reduce priority inversion
– Same effect as making the current task the Highest
Priority Task
– Don’t Lock for too long
ƒ Defeats the purpose of having a kernel.
ƒ ‘Unlock’ invokes the scheduler to see if a High-
Priority Task has been made ready while locked

Lock();
Code with scheduler disabled;
Unlock;

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Mutual Exclusion
(Semaphores)

Task 1
High

Resource
Semaphore

Variable(s)
Tasks Task 2 Data Structure(s)
Medium I/O Device(s)

Task 3
Low Wait for Semaphore;
Access Resource;
Release Semaphore;

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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 HPT TCB MPT TCB LPT TCB
NULL
Value = 0

Tasks Waiting on Semaphore


©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Binary and Counting Semaphores


(Time-of-Day Clock)

Your App. Get Time Of Day Seconds


Task Task Minutes
HPT Hours
Days
Counting DOW
Semaphore Clock Month
Tick ISR 1
2 Task Year
LPT Update Clock
Clock
Variables
TickISR(void) ClockTask(void)
{ {
Signal clock task semaphore; while (TRUE) {
}
Wait for signal from tick ISR;
Acquire semaphore;
Update clock;
Release semaphore;
}
}

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Counting Semaphore
(Serial Communications (Rx))

ƒ ‘Rx ISR’:
– Reads and buffers character
– Clears interrupt source
– Signals semaphore (every character)
ƒ To reduce overhead, could signal only when a special
character such as CR, LF, end-of-packet delimiter is
received.
ƒ ‘Rx Task’:
– Wait on semaphore (with timeout)
– Gets character(s) from buffer

Ring Rx
Rx ISR Buffer
Task

3
2

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

44
Semaphores
(Priority Inversion)

ƒ Delay to a task’s 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 Task needs semaphore …
Preempts Low One LPT owns it

High Priority Task

Medium Priority Done

Medium Priority Task


Task Gets
Semaphore

Low Priority Task


Medium Priority Task
Preempts Low One
©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Semaphores
(Priority Inheritance)

ƒ Low Priority task assumes priority of High


Priority task while accessing semaphore.
ƒ Some kernels have automatic priority
inheritance protocols.
Task
Kernel raises
High Priority Task Needs
LPT’s Priority
Preempts Low One Semaphore

High Priority Task


HPT is done

Medium Priority Task


Task Gets MPT is done
Semaphore

Low Priority Task LPT is done with


Semaphore

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

45
Mutual Exclusion Semaphores
(Mutex)

ƒ ‘Special’ Binary semaphore


– Initial value always 1
– Contains a list of tasks waiting for the mutex
ƒ Kernel needs to support multiple tasks at
the same priority.
ƒ Operations on mutex:
– Create (initial value is always 1) Tasks waiting for Mutex
– Wait (with timeout) NULL

– Signal
Value = 1 TCB TCB TCB
Original Task Prio
Ptr to Mutex Owner

Mutex

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part III

Resource Sharing and Mutual Exclusion

Task Synchronization
Inter-Task Communications

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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:
– Disjunctive (OR): Any event occurred
– Conjunctive (AND): All events occurred
ƒ Task(s) or ISR(s) can either Set or Clear
event flags
ƒ Only tasks can Wait for events

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Event Flags

ISRs TASKs

Set or Clear

Events
(8, 16 or 32 bits)

Wait
OR TASKs

Wait
AND TASKs

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

47
Event Flags
(Implementation)

Event Flag Group Tasks waiting for events


(8, 16 or 32 bits)

NULL
Type (AND or OR) Type (AND or OR) Type (AND or OR)

TCB TCB TCB

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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;

OSEFlagClear(eflag, mask)
eflag->Value &= ~mask;

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

48
Event Flags
(Example)

Abort
Abort ISR

RPM == 0
RPM Event
Task Flag
RPM > 3000 Group
Wait Abort
Temp < 200 OR Task
AI
Task
Fuel > 1%

Start Wait Start


User AND Task
I/F
Task Stop

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Synchronization
(Analog-Digital Conversion)

ADC
AI
Analog Inputs MUX
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 ADC_ISR(void)
Wait for signal from ADC ISR (with timeout) {
if (timed out) Signal Event
Return error code to caller Clear EOC interrupt
else }
Read ADC counts
Return ADC counts to caller
}

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

49
Part III

Resource Sharing and Mutual Exclusion


Task Synchronization

Inter-Task Communications

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Message Queues

ƒ Message passing
– Message is a pointer
– Pointer can point to a variable or a data structure
ƒ FIFO (First-In-First-Out) type queue
– 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
– Highest-priority task waiting on queue will get the
message
ƒ Receiving task can timeout if no message
is received within a certain amount of time

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

50
Message Queues
(Implementation)

Tasks waiting for Mutex

NULL

#Entries = 4
Queue Size = 6
Queue Start TCB TCB TCB

Out Pointer

In Pointer NULL

Message
Pointers to Data
Queue

Out Pointer
Queue Storage Area

Circular
Pointers to Data
Buffer

In Pointer

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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;

void OSQPostFront(q, message, *err)


/* Same as OSQPost() except implements LIFO */

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

52
Message Queues &
Buffer Pools
Message
Rx Queue
Interrupt Rx
UART Rx ISR
Task

Free List
Free List NULL

Buffer Pool

RxISR(void) RxTask(void)
{ {
Read character from UART PACKET *pmsg;
if (1st character of message)
Get a buffer from Buffer Manager while (1)
Put character in buffer pmsg = OSQPend(RxQ, timeout)
if (End of Packet character) Process packet received
Send packet to RxTask for processing Return packet buffer to Buffer Manager
} }

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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
Error
Task
Task

ISR

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

53
Message Mailbox
(RPM Measurement)

Previous
Counts
RPM
Delta
Counts RPM Avg. RPM
ISR Delta Task Under Speed
Counts
Counts=Fin * t Over Speed
16-Bit Max. RPM
Fin Timer RPMTask()
{
while (1)
RPM_ISR() Wait for message from ISR (with timeout);
{ if (timed out)
Read Timer; RPM = 0;
DeltaCounts = Counts else
– PreviousCounts; RPM = 60 * Fin / counts;
PreviousCounts = Counts Compute average RPM;
Post DeltaCounts; Check for overspeed/underspeed;
} Keep track of peak RPM;
etc.
}

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Example #2
(Intertask Communications)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

54
Part IV

Memory Management
Initialization
Execution Times
Recommendations
Buying a Kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Memory Manager

ƒ Most kernels provide fixed-sized memory


block management
– Prevents fragmentation
ƒ 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.

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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;

Memory
Partition
Control Block
pmem NULL
NBlocks
BlockSize
BlocksLeft

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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 NULL
NBlocks
BlockSize
BlocksLeft

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

56
Memory Manager
(Implementation)

OSMemFree(pmem, void *pblock)


pmem->BlocksLeft++;
Add block to free list;

pblock

Memory
Partition
Control Block
pmem NULL
NBlocks
BlockSize
BlocksLeft

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Memory Manager
(Multiple Partitions)

Memory
Partition
Control Block
pmem1 NULL
Block Size
#Blocks
#Free Blocks

pmem2 NULL
Block Size
#Blocks
#Free Blocks

pmem3 NULL
Block Size
#Blocks
#Free Blocks

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

57
Part IV

Memory Management
Initialization
Execution Times
Recommendations
Buying a Kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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 */

/* Install interrupt vectors */

/* Create at least 1 task (Start Task) */


/* Additional User code */

OSStart(); /* Start multitasking */


}
©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

58
Initialization

ƒ You should initialize the ‘ticker’ in the first task


to run.
– Don’t 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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part IV

Memory Management
Initialization
Execution Times
Recommendations
Buying a Kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

59
Execution Times
(µC/OS-II on a 66 MHz 80486)

µC/OS-II, The Real-Time Kernel: 80486 @ 66 MHz


KERNEL SERVICE Max. Interrupt Disable (μS) Minimum ( μS) Maximum (μS)
OSIntEnter() 1 1 1
OSIntExit() 2 3 9
OSQCreate() 2 20 20
OSQPend() 1 8 29
OSQPost() 2 8 23
OSSchedLock() 1 1 1
OSSchedUnlock() 1 2 12
OSSemCreate() 2 12 12
OSSemPend() 1 3 26
OSSemPost() 2 3 22
OSTaskChangePrio() 2 15 23
OSTaskDel() 2 18 27
OSTaskResume() 2 7 15
OSTaskSuspend() 2 9 17
OSTimeDly() 2 13 13
OSTimeGet() 1 2 2
OSTimeSet() 1 2 2
OSTimeTick() (30 tasks) 1 155 299

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Example #3
(Stack Checking & Task Execution Times)

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

60
Part IV

Memory Management
Initialization
Execution Times
Recommendations
Buying a Kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Recommendations

ƒ Don’t have too many tasks


– Increases the overhead
– Increases RAM
ƒ Assign priority by importance
– Consider rate-monotonic scheduling (RMS)
ƒ Don’t allocate large arrays on the stack of a
task
ƒ Use only reentrant functions and compilers
ƒ Don’t write recursive code
– Eats up stack space quickly!

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

61
Recommendations

ƒ Guard resources with either:


– Disable/Enable interrupts
– Semaphores
– Server tasks
– Lock/Unlock the scheduler
ƒ Keep ISRs short
– Get/put data from/to device
– Clear source and return from interrupt
– Have task handle the data
– Avoid long calculations and especially floating-
point math.

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Recommendations

ƒ Keep task interaction to a minimum


– You have a poor design if you have a lot of inter-
task 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
ƒ Avoid deleting kernel objects at run-time!

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

62
Recommendations
(Use an Off-The-Shelf Kernel)

ƒ Don’t “Roll Your Own” kernel!


– You ARE the RTOS vendors #1 competitor
– 50% of the RTOSs are built In-House
ƒ You CAN design a ‘basic’ kernel in a weekend
over a couple of boxes of Pizza and Beer!
ƒ You CAN’T (in a weekend):
– Fully test a kernel
– Document it
ƒ API reference
ƒ How the kernel works
– Port it to multiple platforms
– Have hundreds of people validate it

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Part IV

Memory Management
Initialization
Execution Times
Recommendations
Buying a Kernel

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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.
ƒ Execution Time:
– Try to get from the kernel vendor:
ƒ the maximum interrupt disable time
ƒ the context switch time
ƒ the execution times of services

ƒ Memory requirements:
– How much RAM/ROM?
– Can you scale the kernel to reduce RAM/ROM?

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Buying a Kernel?

ƒ Cost:
– Up-front price?
– Any per-unit royalties?
– Maintenance cost?
ƒ Is the source code included?
– 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!
ƒ Other ports available?
– You may want to port your application or, some of
its modules to other processors

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

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,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Buying a Kernel?

ƒ Vendor provides integrated products?


– Compilers/Assemblers/Linkers
– File system
ƒ DOS compatible files
– I/O Drivers
– Networking
ƒ TCP/IP
– Reentrant libraries
– Board Support Packages (BSPs)
– Quality and completeness of documentation
– Debugger
ƒ Kernel awareness
ƒ Profiling

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

65
Kernel Awareness Debuggers

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Run-Time Task Profilers

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

66
References
“A Practitioner’s Handbook for Real-Time
Analysis: Guide to RMA for Real-Time
Systems”
Mark H. Klein, Kluwer Academic Publishers Chinese Korean
ISBN 0-7923-9361-9

“µC/OS-II, The Real-Time Kernel,


2nd Edition”
Jean J. Labrosse, CMP Books
ISBN 1-57820-103-9

Chinese Korean
“Embedded Systems Building Blocks,
Complete and Ready-to-Use Modules in C”
Jean J. Labrosse, CMP Books
ISBN 0-97930-604-1

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Thank You.

Don’t Forget.
Please Fill in the Evaluation Sheet.

©
© 2006,
2006, Micriµm,
Micriµm, All
All Rights
Rights Reserved
Reserved Real-Time
Real-Time Kernels
Kernels

Real-Time Kernels
Jean J. Labrosse

67

You might also like