Anda di halaman 1dari 67

Real-Time Kernels

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 Real-Time 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time Kernels

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

Real-Time Kernels Real-Time Kernels

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 Real-Time Kernels

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

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

Real-Time Kernels Real-Time Kernels

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 */ ISR (void) { Handle asynchronous event; }

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

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

Real-Time Kernels Real-Time Kernels

Foreground/Background
Disadvantages

All tasks have the same priority!


Code executes in sequence If an important event occurs its 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time Kernels

Part I

Foreground/Background Systems

Real-Time Kernels
Task Management

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 Its like having multiple CPUs!

Provides valuable services to your application:


Time delays Resource sharing Intertask communication and synchronization

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

File System

Real-Time Kernels Real-Time 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 To reduce development time To easily split the application between programmers To get useful services from the kernel
Can simplify debugging

Adding low-priority tasks generally does not change the responsiveness to higher priority tasks!

Services that you would want to provide to your application code


Real-Time Kernels Real-Time Kernels

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Can you use a Kernel?


Depends on the processor!

Do you have enough ROM ?


4K to 250K+ bytes extra

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 Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
9

Can you use a Kernel?


Do you have enough RAM ?
Kernel RAM Task stacks
20 to 350 bytes per task Each task requires its own stack!

Kernel will disable interrupts! Can your application afford the extra costs?

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

What are the Costs?


Development Seats
Per-unit

Some Kernels require royalties Some kernels are licensed


On a per-project basis For a product line Company wide Per-seat (i.e. per-developer) Per-CPU type

$75 to $10,000 per seat (may be more)

Maintenance for upgrades and bug fixes


Typically 15-20% (of initial cost) per year

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time Kernels

Designing with a Kernel


High Priority Task Task

(Splitting an application into Tasks)

Task Importance

Each Task
Event Event

Task

Task

Task
Infinite Loop

Low Priority Task

Task

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
11

Types of Kernels
(Non-Preemptive)
ISR make High Priority Task Ready ISR Completes (Return to Task)

Interrupt Occurs Vector to ISR

ISR

ISR

High Priority Task

Low Priority Task

Low Priority Task Completes (Switch to HP Task)

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Types of Kernels
(Preemptive)
Interrupt Occurs Vector to ISR ISR make High Priority Task Ready ISR Completes (Switch to HP Task)

ISR

ISR

High Priority Task (HPT)

Low Priority Task (LPT)

HP Task Completes (Switch back to LP Task)

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
12

Part I

Foreground/Background Systems Real-Time Kernels

Task Management

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

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

Real-Time Kernels Real-Time Kernels

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

Wait For Event

Running

ISR Task Interrupted

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

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

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
15

Task Create Pseudo-Code


Address of Task Address of 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 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)

Save Top Of Stack in TCB

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

Allocate & Initialize TCB

Allocate & Initialize Stack Frame


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 tasks priority The tasks state (Ready, Waiting ...) A pointer to the tasks Top-Of-Stack (TOS) Other task related data

TCBs reside in RAM:


45 bytes for C/OS-II and the 80x86 (Large Model)

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Multiple Created Tasks


(Task Stacks and TCBs)

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 Real-Time 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 Size Free

Stack Growth 0x00 0x00 0x00 0x00 BOS

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time Kernels

Changing a Tasks Priority


Kernels can allow tasks to change their priority (or the priority of others) at runtime

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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.
Real-Time Kernels Real-Time Kernels

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Sensors

Data Logging Task Client


Data

Storage Manager Task Server

Storage Media

Command

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 A Task B Task C

ISR

VS
ISR Task ABC

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

How to split an application into Tasks?


Dont have too few tasks!
Defeats the purpose of having a kernel Increases the overhead and needs more RAM

Dont have too many tasks!

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 Real-Time 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! Low priority tasks:
Keyboard scanning Operator interface Display updates etc. Some tasks cannot miss their deadlines, others can (HARD vs SOFT)

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

How to set Task Priorities?


High priority tasks:

Rate Monotonic Scheduling...

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 Real-Time 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.

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

Some low frequency event may have a short deadline

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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 Real-Time 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time 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
TCB TCB TCB TCB

NULL

Highest Priority Task


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Lowest Priority Task

Real-Time Kernels Real-Time Kernels

A Different Ready List!


(C/OS-IIs Ready List)
OSRdyGrp
7 6 5 4 3 2 1 0

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 Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
25

Finding the Highest Priority Task Ready


OSRdyGrp

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 Real-Time 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[] = { 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 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0x20-0x2F 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 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 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, // 0xD0-0xDF 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

(Step #2) X = @ [0x78]


(i.e. 0x78 = OSRdyTbl[1])

(Step #1) Y = @ [0xF6]


(i.e. 0xF6 = OSRdyGrp)

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

Real-Time Kernels Real-Time 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 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

Kernel clears the Ready bit

0 1

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

HPT Ready (Bit 11)

0 0 1

[7] [8] [9] [10]

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

Real-Time Kernels Real-Time Kernels

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 Real-Time Kernels

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

Real-Time Kernels Real-Time Kernels

Context Switch
(or Task Switch)

Click on Image
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
29

Context Switch on 80x86


(Actual code for C/OS-II)
_OSCtxSw PUSHA PUSH PUSH MOV MOV LES MOV MOV MOV MOV MOV MOV MOV MOV LES MOV MOV POP POP POPA IRET _OSCtxSw PROC FAR ; Save context ES DS AX, SEG _OSTCBCur DS, AX BX, DWORD PTR DS:_OSTCBCur ES:[BX+2], SS ES:[BX+0], SP AX, WORD PTR DS:_OSTCBHighRdy+2 DX, WORD PTR DS:_OSTCBHighRdy WORD PTR DS:_OSTCBCur+2, AX WORD PTR DS:_OSTCBCur, DX AL, BYTE PTR DS:_OSPrioHighRdy BYTE PTR DS:_OSPrioCur, AL BX, DWORD PTR DS:_OSTCBHighRdy SS, ES:[BX+2] SP, ES:[BX] DS ES

; Save SS:SP

; OSTCBCur = OSTCBHighRdy

; OSPrioCur = OSPrioHighRdy ; Get new SS:SP

; Restore new tasks context

ENDP Real-Time Kernels Real-Time Kernels

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 Real-Time 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
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

Real-Time Kernels Real-Time Kernels

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 Real-Time Kernels

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;

There are no HP Tasks Ready, Return to Interrupted Task!


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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 Real-Time Kernels

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

Process ISR (6);


Call Kernel ISR Exit function (7); Restore CPU Registers (8); Return from Interrupt (9);
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Interrupt Recovery Real-Time Kernels Real-Time Kernels

HPT Ready Do Context Switch

Servicing Interrupts
(1) TASK (3) Vect (4) Save (5) Ent (6) User ISR OSQPost() (8 S) (2), Interrupts enabled

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


15 to 17 S
Interrupt Recovery (5 S) (9), RTI (8), Restore Exit (7), Kernel ISR Exit function

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 Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
33

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 Real-Time 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time 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 10 TCB 25 TCB NULL 25 10 15 0 ListPtr TCB TCB TCB NULL

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

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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Time Delays and Timeouts


(Not accurate)
HPT Task (void) { for (;;) { OSTimeDly(1); . . } }
20 mS

LPT Task (void) { for (;;) { OSTimeDly(1); . . } }

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 Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
36

Example #1
(Time Delays)

Click on Image

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Use for Timeouts


To prevent waiting forever for events To avoid deadlocks Example:
Read slow ADC Timeout indicates that conversion didnt occur within the expected time.

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time Kernels

Tasks Readied by Tick


Tick Interrupt
HPT = High Priority Task MPT = Medium Priority Task

ISR
OS

LPT = Low Priority Task

HPT
Scheduling & Context Switching (Overhead) OS

MPT
OS

LPT

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
38

Part III

Resource Sharing and Mutual Exclusion


Task Synchronization Inter-Task Communications

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 dont allow you to do this in user code

Lock/Unlock Semaphores MUTEX (Mutual Exclusion Semaphores)

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 dont allow you to disable interrupts

rpm = 60.0 / time; Disable interrupts; Global RPM = rpm; Enable interrupts;

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 Dont Lock for too long
Defeats the purpose of having a kernel.

Unlock invokes the scheduler to see if a HighPriority Task has been made ready while locked

Lock(); Code with scheduler disabled; Unlock;


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

Real-Time Kernels Real-Time Kernels

Mutual Exclusion
(Semaphores)

Task 1 High
Semaphore

Resource
Variable(s) Data Structure(s) I/O Device(s)

Tasks

Task 2 Medium

Task 3 Low

Wait for Semaphore; Access Resource; Release Semaphore;


Real-Time Kernels Real-Time Kernels

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

LPT TCB NULL

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

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

Real-Time Kernels Real-Time Kernels

Binary and Counting Semaphores


(Time-of-Day Clock)
Your Task Counting Semaphore
Tick ISR

App. Task
HPT

Get Time Of Day

1 2

Clock Task
LPT

Seconds Minutes Hours Days DOW Month Year

Update Clock

Clock Variables

TickISR(void) { Signal clock task semaphore; }

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

Real-Time Kernels Real-Time Kernels

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.

Wait on semaphore (with timeout) Gets character(s) from buffer


Rx ISR
Ring Buffer

Rx Task

3 2
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

High Priority Task


Medium Priority Done

Medium Priority Task


Task Gets Semaphore

Low Priority Task


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

High Priority Task

HPT is done

Medium Priority Task


Task Gets Semaphore MPT is done

Low Priority Task


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

LPT is done with Semaphore Real-Time Kernels Real-Time 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) 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

Real-Time Kernels Real-Time Kernels

Part III

Resource Sharing and Mutual Exclusion

Task Synchronization
Inter-Task Communications

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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:

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

Real-Time Kernels Real-Time Kernels

Event Flags

ISRs

TASKs

Set or Clear Events (8, 16 or 32 bits)

OR

Wait

TASKs

AND

Wait

TASKs

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
47

Event Flags
(Implementation)

Event Flag Group (8, 16 or 32 bits)

Tasks waiting for events

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

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

Real-Time Kernels Real-Time Kernels

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

User I/F Task

Start Stop

AND

Wait

Start Task

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

ADC_ISR(void) { Signal Event Clear EOC interrupt }

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
49

Part III

Resource Sharing and Mutual Exclusion Task Synchronization

Inter-Task Communications

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

Out Pointer Queue Storage Area Pointers to Data

Circular Buffer

In Pointer
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

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

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

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
52

Message Queues & Buffer Pools


UART
Rx Interrupt Message Queue

Rx ISR

Rx Task

Free List Free List

NULL Buffer Pool

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

Real-Time Kernels Real-Time 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

Task ISR
2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Error Task

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
53

Message Mailbox
(RPM Measurement)

Previous Counts RPM Delta Counts Delta Counts

ISR
16-Bit Timer

RPM Task

Avg. RPM Under Speed Over Speed Max. RPM

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 Real-Time Kernels

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

Real-Time Kernels Real-Time Kernels

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 Real-Time 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


NBlocks BlockSize BlocksLeft

NULL

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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
NBlocks BlockSize BlocksLeft

NULL

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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


NBlocks BlockSize BlocksLeft

NULL

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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 Real-Time Kernels

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

Real-Time Kernels Real-Time 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(); }


2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

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

*/

Real-Time Kernels Real-Time Kernels

Part IV

Execution Times
Recommendations Buying a Kernel

Memory Management Initialization

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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 OSIntEnter() OSIntExit() OSQCreate() OSQPend() OSQPost() OSSchedLock() OSSchedUnlock() OSSemCreate() OSSemPend() OSSemPost() OSTaskChangePrio() OSTaskDel() OSTaskResume() OSTaskSuspend() OSTimeDly() OSTimeGet() OSTimeSet() OSTimeTick() (30 tasks) Max. Interrupt Disable (S) Minimum ( S) 1 1 2 3 2 20 1 8 2 8 1 1 1 2 2 12 1 3 2 3 2 15 2 18 2 7 2 9 2 13 1 2 1 2 1 155 Maximum (S) 1 9 20 29 23 1 12 12 26 22 23 27 15 17 13 2 2 299

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Example #3

(Stack Checking & Task Execution Times)

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
60

Part IV

Recommendations
Buying a Kernel

Memory Management Initialization Execution Times

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Recommendations
Dont have too many tasks
Increases the overhead Increases RAM

Assign priority by importance


Consider rate-monotonic scheduling (RMS)

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 Real-Time Kernels

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.

Keep ISRs short

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

Avoid deleting kernel objects at run-time!

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
62

Recommendations

(Use an Off-The-Shelf Kernel) Dont 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 CANT (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


Real-Time Kernels Real-Time Kernels

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Part IV

Buying a Kernel

Memory Management Initialization Execution Times Recommendations

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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. 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

Real-Time Kernels Real-Time Kernels

Buying a Kernel?
Cost:

Is the source code included?

Up-front price? Any per-unit royalties? Maintenance 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!

Other ports available?

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 Real-Time 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, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time 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
Real-Time Kernels Real-Time Kernels

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels
Jean J. Labrosse
65

Kernel Awareness Debuggers

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Run-Time Task Profilers

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

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

C/OS-II, The Real-Time Kernel, 2nd Edition


Jean J. Labrosse, CMP Books

ISBN 1-57820-103-9

Chinese Embedded Systems Building Blocks,


Jean J. Labrosse, CMP Books

Korean

Complete and Ready-to-Use Modules in C ISBN 0-97930-604-1

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Thank You.

Dont Forget.
Please Fill in the Evaluation Sheet.

2006, Micrim, All Rights Reserved 2006, Micrim, All Rights Reserved

Real-Time Kernels Real-Time Kernels

Real-Time Kernels
Jean J. Labrosse
67

Anda mungkin juga menyukai