Real-Time Multitasking
5.1 Introduction
Task Basics
Task Control
Error Status
System Tasks
®
5-2
What is Real-Time?

Real-time denotes the ability of a control system to keep
up with the system being controlled.

A system is described as being deterministic if its
response time is predictable.

The lag time between the occurrence of an event and the
response to that event is called latency.

Deterministic response is the key to real-time
performance.
®
5-3
Requirements of a Real-time System

Ability to control many external components:
– Independent components
– Asynchronous components
– Synchronous components

High speed execution:
– Fast response
– Low overhead

Deterministic operation:
– A late answer is a wrong answer.
®
5-4
Design Options
®
5-5
Unitasking Approach

One task controlling all the components in a loop.
arm ()
{
for (;;)
{
if (shoulder needs moving)
moveShoulder();
if (elbow needs moving)
moveElbow();
if (wrist needs moving)
moveWrist();
.
.
.
}
}
®
5-6
Multitasking Approach

Create a separate task to manipulate each joint:
joint ()
{
for (;;)
{
waitForMove(); /* Until joint needs moving */
moveJoint();
}
}

Each task alternates between “ready” and “waiting”.

VxWorks allows a task to wait for:
– A specified time delay
– An event (e.g. an interrupt)
®
5-7
Task States
®
5-8
Multitasking Kernel

The Wind kernel is that part of VxWorks which directly
manages tasks.

Allocates the CPU to tasks according to the VxWorks
scheduling algorithm (to be discussed).

Uses Task Control Blocks (TCBs) to keep track of tasks.
– One per task
– Declared as WIND_TCB data structure in taskLib.h
– O.S. control information
e.g. state, task priority,
delay timer, breakpoint
list, error status, I/O
redirections, etc.
– CPU Context Information
e.g. PC, SP, CPU registers,
FPU registers
®
5-9
Kernel Operation
®
5-10
Context Switch

When one task stops executing and a new task starts, a
context switch or reschedule has occurred.

To schedule a new task to run, the kernel must:
1. Save context of currently executing task into its TCB.
2. Restore context of next task to execute from its TCB.

Complete context switch must be very fast.
®
5-11
Types of Context Switches

Synchronous context switches occur because the
executing task
– pends, delays, or suspends itself.
– makes a higher priority task ready to run.
– (less frequently) lowers its own priority, or exits.

Asynchronous context switches occur when an ISR:
– makes a higher priority task ready to run.
– (less frequently) suspends the current task or lowers its priority.

Synchronous context switches require saving fewer
registers than asynchronous context switches, and so
are faster.
®
5-12
Priority Scheduling

Different application jobs may have different
precedences, which should be observed when allocating
the CPU.

Preemptive scheduling is based on task priorities chosen
to reflect job precedence.

The highest priority task ready to run (not pended or
delayed) is allocated the CPU.

Rescheduling can occur at any time as a result of:
– Kernel calls
– Interrupts (e.g., system clock tick)

The context switch is not delayed until the next system
clock tick.
®
5-13
Priority Based Preemption

Equal priority tasks won’t preempt each other
(by default).
®
5-14
Round-Robin Scheduling
®
5-15
Slicing Time

To allow equal priority tasks to preempt each other, time
slicing must be turned on:
kernelTimeSlice(ticks)
If ticks = 0, time slicing is turned off.

Priority scheduling always takes precedence.
– Round-robin only applies to tasks of the same priority.

Priority-based rescheduling can happen any time.
– Round-robin rescheduling can only happen every few clock ticks.
®
5-16
Performance Enhancements

All tasks reside in a common address space.

All tasks run in supervisor (privileged) mode.
®
5-17
Multitasking Facilities
®
5-18
How VxWorks Operating System Meets
Real-time Requirements

Able to control many external components
– Multitasking allows solution to mirror the problem.
– Independent functions are assigned to different tasks.
– Intertask communication allows tasks to cooperate.

High speed execution
– Tasks are light-weight, enabling fast context switch.
– No “system call” overhead.

Deterministic operation
– Preemptive priority scheduling assures response for high priority
tasks.
®
5-19
Real-Time Multitasking
Introduction
5.2 Task Basics
Task Control
Error Status
System Tasks
®
5-20
Overview

Low level routines to create and manipulate tasks are
found in taskLib.

A VxWorks task consists of:
– A stack (for local storage of automatic variables and parameters
passed to routines).
– A TCB (for OS control).

Do not confuse executable code with the task(s) which
execute it:
– Code is downloaded before tasks are spawned.
– Several tasks can execute the same code
(e.g., printf( )).
®
5-21
Creating a Task
®
5-22
Creating a Task
int taskSpawn (name, priority, options,
stackSize, entryPt, arg1, …, arg10)

name
priority
options
Task name, if NULL gives a default name.
Task priority 0-255.
Task options e.g. VX_UNBREAKABLE.
stackSize
entryPt
arg1, ..., arg10
Size of stack to be allocated in bytes.
Address of code to start executing (initial PC).
Up to 10 arguments to entry-point routine.
Returns a task id or ERROR if unsuccessful.
®
5-23
Task ID’s

Assigned by kernel when task is created.

Unique to each task.

Efficient 32-bit handle for task.

May be reused after task exits.

A task id of zero refers to task making call (self).

Relevant taskLib routines:
taskIdSelf( )
Get ID of calling task.
taskIdListGet( ) Fill array with ID’s of all existing tasks.
taskIdVerify( ) Verify a task ID is valid.
®
5-24
Task Names

Provided for human convenience.
– Typically used only from the shell (during development).
– Within programs, use task Ids.

By (often ignored) convention, task names start with a t.
– Promotes interpretation as a task name.
– Default name is a t followed by an ascending integer.

Doesn’t have to be unique (but usually is).

Relevant taskLib routines:
taskName( )
taskNameToId( )
Get name from tid.
Get tid from task name.
®
5-25
Task Priorities

Range from 0 (highest) to 255 (lowest).

Determining how to set task priorities is a difficult
subject, and beyond the scope of this course. However:
– Timing requirements rather than hazy ideas about task
importance should govern priorities.
– A substantial body of theory exists.

One can manipulate priorities dynamically with:
taskPriorityGet (tid, &priority)
taskPrioritySet (tid, priority)
– Doing so may make your application’s behavior more difficult to
analyze.
®
5-26
Task Stacks

Allocated from system memory pool when task is
created.

Fixed size after creation.

The kernel reserves some space from the stack, making
the stack space actually available slightly less than the
stack space requested.

Exceeding stack size (“stack crash”) causes
unpredictable system behavior.
®
5-27
Stack Overflows

To check for a stack overflow use the Browser:
– Press the check-stack button:
– Examine the high water mark indicator in the stack display
window.
High water mark indicator
(Unix) Current usage shown by
shaded bar and number inside.
High water mark shown by
shaded bar. (Windows)
Current usage shown by number
inside bar.
®
5-28
Task Options

Can be bitwise or’ed together when the task is created:
VX_FP_TASK
Add floating point support.
VX_NO_STACK_FILL
Don’t fill stack with 0xee’s.
VX_UNBREAKABLE
Disable breakpoints.
VX_DEALLOC_STACK
Deallocate stack and TCB when task exits
(automatically set for you).

Use taskOptionsGet( ) to inquire about a tasks options.

Use taskOptionsSet( ) to unset VX_DEALLOC_STACK.
®
5-29
Task Creation

During time critical code, task creation can be
unacceptably time consuming.

To reduce creation time, a task can be spawned with the
VX_NO_STACK_FILL option bit set.

Alternatively, spawn a task at system start-up which
blocks immediately, and waits to be made ready when
needed.
®
5-30
Task Deletion
taskDelete (tid)

Deletes the specified task.

Deallocates the TCB and stack.
exit(code)

Equivalent to a taskDelete( ) of self.

code parameter is stored in the TCB field exitCode.

TCB may be examined for post-mortem debugging by
– Unsetting the VX_DEALLOC_STACK option or,
– Using a delete hook.
®
5-31
Resource Reclamation

Contrary to the philosophy of sharing system resources
among all tasks.

Can be an expensive process, which must be the
application’s responsibility.

TCB and stack are the only resources automatically
reclaimed.

Tasks are responsible for cleaning up after themselves.
– Deallocating memory.
– Releasing locks on shared resources.
– Closing files which are open.
– Deleting child tasks when parent task exits.
®
5-32
Real-Time Multitasking
Introduction
Task Basics
5.3 Task Control
Error Status
System Tasks
®
5-33
Task Restart
taskRestart (tid)

Task is terminated and respawned with original
arguments and tid.

Usually used for error recovery.
®
5-34
Task Suspend/Resume
taskSuspend (tid)

Makes task ineligible to execute.

Can be added to pended or delayed state.

It is safest to have a task suspend itself.
taskResume (tid)

Removes suspension.

Usually taskSuspend() and taskResume() are used for
debugging and development purposes.
®
5-35
Task Delay

To delay a task for a specified number of system clock
ticks:
STATUS taskDelay (tics)

To poll every 1/7 second:
FOREVER
{
taskDelay (sysClkRateGet( ) / 7)
...
}
– Accurate only if clock rate is a multiple of seven ticks/second.
– Can suffer from “drift.”

Use sysClkRateSet( ) to change the clock rate.
®
5-36
Reentrancy and Task Variables

If tasks access the same global or static variables, the
resource can become corrupted (called a race condition).

Possible Solutions:
– Use only stack variables in applications.
– Protect the resource with a semaphore.
– Use task variables to make the variable private to a task.

Task Variables cause a 32-bit value to be saved and
restored on context switches, like a register.

Caveat: task variables increase context switch times.

See the taskVarLib manual pages for details.
®
5-37
Task Hooks

User-defined code can be executed on every context
switch, at task creation, or at ask deletion:
taskSwitchHookAdd ( )
taskCreateHookAdd ( )
taskDeleteHookAdd ( )

VxWorks uses a switch hook to implement task variables.

See manual pages on taskHookLib for details.
®
5-38
Task Information
ti (taskNameOrId)

Like i( ), but also displays:
– Stack information
– Task options
– CPU registers
– FPU registers (if the VX_FP_TASK option bit is set).

Can also use show ( ):
-> show (tNetTask, 1)
®
5-39
Task Browser

To obtain information
about a specific task,
double-click on the task’s
summary line in the main
task browser display, or
enter the task’s ID in the
Show box.
®
5-40
What is POSIX?

Originally, an IEEE committee convened to create a
standard interface to UNIX for:
– Increased portability.
– Convenience.

VxWorks supports almost all of the 1003.1b POSIX Realtime Extensions.

The POSIX real-time extensions are based on implicit
assumptions about the UNIX process model which do not
always hold in VxWorks. In VxWorks,
– Context switch times are very fast.
– Text, data, and bss segments are stored in a common, global
address space.
®
5-41
What does VxWorks Support?
Library
aioPxLib
semPxLib
mqPxLib
mmanPxLib
schedPxLib
sigLib
timerLib, clockLib
dirLib
Description
Asynchronous I/O
POSIX Semaphores
POSIX Message Queues
POSIX Memory Management
POSIX Scheduler Interface
POSIX Signals
POSIX Timer/Clock Interface
File/Directory Information
®
5-42
Real-Time Multitasking
Introduction
Task Basics
Task Control
5.4 Error Status
System Tasks
®
5-43
Error Status

Global integer errno is used to propagate error
information:
– Low level routine detecting an error sets errno.
– Calling routine can examine errno to discover why the routine
failed.
®
5-44
Errno and Context Switches
At each context switch, the kernel saves and restores
the value of errno.
®
5-45
Setting Errno

Lowest level routine to detect an error sets errno and
returns ERROR:
STATUS myRoutine()
{
...
if (myNumFlurbishes >= MAX_FLURBISH)
{
errno = S_myLib_TOO_MANY_FLURBISHES;
return (ERROR);
}
...
pMem = malloc (sizeof(myStruct));
if (pMem == NULL)
{
/* malloc() sets errno - do’nt redefine it */
return (ERROR)
}
...
}
®
5-46
Examining Errno

Examine errno to find out why a routine failed.
if ( reactorOk( ) == ERROR )
{
switch (errno)
{
case S_rctorLib_TEMP_DANGER_ZONE:
startShutdown( );
break;
case S_rctorLib_TEMP_CRITICAL_ZONE:
logMsg(“Run!”);
break;
case S_rctorLib_LEAK_POSSIBLE:
checkVessel( );
break;
default: startEmergProc( );
}
}

errno is only valid after an error occurs.
®
5-47
Interpreting Errno

VxWorks uses the 32-bit value errno as follows:
31
15
module
0
error number
– VxWorks module numbers are defined in vwModNum.h.
– Each module defines its own error numbers in its header file.

For example, an errno of 0x110001 would be:
– Module number 0x11 (defined in vwModNum.h to be memLib) and
– Error number 0x01 (defined in memLib.h to be “not enough
memory”).
®
5-48
Error Messages

VxWorks uses an error symbol table (statSymTbl) to
convert error numbers to error messages.

To obtain the error string corresponding to errno:
{
char errStr [NAME_MAX];
strerror_r (errno, errStr);
...
}

To print the error message associated with an error
number to the WindSh console:
-> printErrno (0x110001)
S_memLib_NOT_ENOUGH_MEMORY
®
5-49
User-Defined Error Codes

To allow strerror_r() to support your error messages:
1. Create a user header file directory.
2. Create a file xxModNum.h in the user header directory:
#define M_myLib
(501 << 16)
3. Define error macros in your header files (which must be in the
user header directory):
#define S_myLib_BAD_STUFF
(M_myLib|1)
4. Rebuild the system error table, statTbl.o.
5. Include the component development tool components > symbol table
components > error status table in VxWorks. Add statTbl.o to the
EXTRA_MODULES macro.
6. Rebuild VxWorks.
®
5-50
Real-Time Multitasking
Introduction
Task Basics
Task Control
Error Status
5.5 System Tasks
®
5-51
System Tasks
Task Name
Priority
Function
tUsrRoot
0
First task. Initializes included
facilities, spawns user application,
and exits.
tLogTask
0
Message logging.
tExcTask
0
Server which executes miscellaneous
task-level functions at high priority.
tWdbTask
3
WDB run-time agent.
tNetTask
50
Task-level network functions.
tFtpdTask
55
FTP server.
®
5-52
Summary

Real-time multitasking requirements:
– Preemptive priority-based scheduler
– Low overhead

Task properties stored in task’s TCB.
– OS control information (priority, stack size, options, state, ...).
– Saved CPU context (PC, SP, CPU registers, ...).

taskSpawn( ) lets you specify intrinsic properties:
– Priority
– Stack size
– Options
®
5-53
Summary

Task manipulation routines in taskLib:
– taskSpawn/taskDelete
– taskDelay
– taskSuspend/taskResume

Task information
– ti/show
– Task Browser

Additional task context:
– errno
– Task variables
– Task hooks
®
5-54
Descargar

Real-Time Multitasking