Top Banner
5-1 ® Real-Time Multitasking Real-Time Multitasking 5.1 Introduction Task Basics Task Control Error Status System Tasks
53

5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

Mar 29, 2015

Download

Documents

Braden Ballard
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-1®

Real-Time MultitaskingReal-Time Multitasking

5.1 Introduction

Task Basics

Task Control

Error Status

System Tasks

Page 2: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-2®

What is Real-Time?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.

Page 3: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-3®

Requirements of a Real-time SystemRequirements 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.

Page 4: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-4®

Design OptionsDesign Options

Page 5: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-5®

Unitasking ApproachUnitasking 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();...}

}

Page 6: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-6®

Multitasking ApproachMultitasking Approach

Create a separate task to manipulate each joint:

Each task alternates between “ready” and “waiting”.

VxWorks allows a task to wait for:

– A specified time delay

– An event (e.g. an interrupt)

joint (){for (;;)

{waitForMove(); /* Until joint needs moving

*/moveJoint();}

}

Page 7: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-7®

Task StatesTask States

Page 8: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-8®

Multitasking KernelMultitasking 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.htaskLib.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

Page 9: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-9®

Kernel OperationKernel Operation

Page 10: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-10®

Context SwitchContext 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.

Page 11: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-11®

Types of Context SwitchesTypes 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.

Page 12: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-12®

Priority SchedulingPriority 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.

Page 13: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-13®

Priority Based PreemptionPriority Based Preemption

Equal priority tasks won’t preempt each other(by default).

Page 14: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-14®

Round-Robin SchedulingRound-Robin Scheduling

Page 15: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-15®

Slicing TimeSlicing 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.

Page 16: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-16®

Performance EnhancementsPerformance Enhancements All tasks reside in a common address space.

All tasks run in supervisor (privileged) mode.

Page 17: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-17®

Multitasking FacilitiesMultitasking Facilities

Page 18: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-18®

How VxWorks Operating System Meets How VxWorks Operating System Meets Real-time RequirementsReal-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.

Page 19: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-19®

Real-Time MultitaskingReal-Time Multitasking

Introduction

5.2 Task Basics

Task Control

Error Status

System Tasks

Page 20: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-20®

OverviewOverview

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( )).

Page 21: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-21®

Creating a TaskCreating a Task

Page 22: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-22®

Creating a TaskCreating a Task

int taskSpawn (name, priority, options, stackSize, entryPt, arg1, …, arg10)

name Task name, if NULL gives a default name.

priority Task priority 0-255.

options Task options e.g. VX_UNBREAKABLE.

stackSize Size of stack to be allocated in bytes.

entryPt Address of code to start executing (initial PC).

arg1, ..., arg10 Up to 10 arguments to entry-point routine.

Returns a task id or ERROR if unsuccessful.

Page 23: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-23®

Task ID’sTask 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 taskLibtaskLib routines:

taskIdSelf( ) Get ID of calling task.

taskIdListGet( ) Fill array with ID’s of all existing tasks.

taskIdVerify( ) Verify a task ID is valid.

Page 24: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-24®

Task NamesTask 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 tt.

– Promotes interpretation as a task name.

– Default name is a tt followed by an ascending integer.

Doesn’t have to be unique (but usually is).

Relevant taskLibtaskLib routines:

taskName( ) Get name from tid.

taskNameToId( ) Get tid from task name.

Page 25: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-25®

Task PrioritiesTask 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.

Page 26: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-26®

Task StacksTask 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.

Page 27: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-27®

Stack OverflowsStack 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.

Page 28: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-28®

Task OptionsTask 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.

Page 29: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-29®

Task CreationTask 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.

Page 30: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-30®

Task DeletionTask 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.

Page 31: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-31®

Resource ReclamationResource 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.

Page 32: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-32®

Real-Time MultitaskingReal-Time Multitasking

Introduction

Task Basics

5.3 Task Control

Error Status

System Tasks

Page 33: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-33®

Task RestartTask Restart

taskRestart (tid)

Task is terminated and respawned with original arguments and tid.

Usually used for error recovery.

Page 34: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-34®

Task Suspend/ResumeTask 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.

Page 35: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-35®

Task DelayTask 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.

Page 36: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-36®

Reentrancy and Task VariablesReentrancy 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 taskVarLibtaskVarLib manual pages for details.

Page 37: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-37®

Task HooksTask 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 taskHookLibtaskHookLib for details.

Page 38: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-38®

Task InformationTask 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)show (tNetTask, 1)

Page 39: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-39®

Task BrowserTask 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 ShowShow box.

Page 40: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-40®

What is POSIX?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 Real-time 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.

Page 41: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-41®

What does VxWorks Support?What does VxWorks Support?

Library Description

aioPxLibAsynchronous I/O

semPxLib POSIX Semaphores

mqPxLibPOSIX Message Queues

mmanPxLib POSIX Memory Management

schedPxLib POSIX Scheduler Interface

sigLibPOSIX Signals

timerLib, clockLib POSIX Timer/Clock Interface

dirLib File/Directory Information

Page 42: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-42®

Real-Time MultitaskingReal-Time Multitasking

Introduction

Task Basics

Task Control

5.4 Error Status

System Tasks

Page 43: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-43®

Error StatusError 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.

Page 44: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-44®

Errno and Context SwitchesErrno and Context Switches

At each context switch, the kernel saves and restores the value of errno.

Page 45: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-45®

Setting ErrnoSetting 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)}

...}

Page 46: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-46®

Examining ErrnoExamining Errno Examine errno to find out why a routine failed.

errno is only valid after an error occurs.

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

}

Page 47: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-47®

Interpreting ErrnoInterpreting Errno

VxWorks uses the 32-bit value errno as follows:

31 15 0

– VxWorks module numbers are defined in vwModNum.hvwModNum.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.hvwModNum.h to be memLibmemLib) and

– Error number 0x01 (defined in memLib.hmemLib.h to be “not enough memory”).

module error number

Page 48: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-48®

Error MessagesError Messages

VxWorks uses an error symbol table (statSymTbl) to convert error numbers to error messages.

To obtain the error string corresponding to errno:

To print the error message associated with an error number to the WindSh console:

-> printErrno (0x110001)S_memLib_NOT_ENOUGH_MEMORY

{char errStr [NAME_MAX];strerror_r (errno, errStr);...}

Page 49: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-49®

User-Defined Error CodesUser-Defined Error Codes

To allow strerror_r() to support your error messages:

1. Create a user header file directory.

2. Create a file xxModNum.hxxModNum.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.ostatTbl.o.

5. Include the component development tool components > symbol table development tool components > symbol table components > error status tablecomponents > error status table in VxWorks. Add statTbl.o to the EXTRA_MODULES macro.

6. Rebuild VxWorks.

Page 50: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-50®

Real-Time MultitaskingReal-Time Multitasking

Introduction

Task Basics

Task Control

Error Status

5.5 System Tasks

Page 51: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-51®

System TasksSystem 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.

Page 52: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-52®

SummarySummary

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

Page 53: 5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks.

5-53®

SummarySummary

Task manipulation routines in taskLib:

– taskSpawn/taskDelete

– taskDelay

– taskSuspend/taskResume

Task information

– ti/show

– Task Browser

Additional task context:

– errno

– Task variables

– Task hooks