Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "5-2 ® Real-Time Multitasking 5.1Introduction Task Basics Task Control Error Status System Tasks."— Presentation transcript:

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

2 5-3 ® 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.

3 5-4 ® 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.

4 5-5 ® Design Options

5 5-6 ® 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();. }

6 5-7 ® Multitasking 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(); }

7 5-8 ® Task States

8 5-9 ® 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 taskLib.h –Declared as WIND_TCB data structure in taskLib.h –O.S. control informatione.g. state, task priority, delay timer, breakpoint list, error status, I/O redirections, etc. –CPU Context Informatione.g. PC, SP, CPU registers, FPU registers

9 5-10 ® Kernel Operation

10 5-11 ® 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.

11 5-12 ® 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.

12 5-13 ® 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.

13 5-14 ® Priority Based Preemption Equal priority tasks wont preempt each other (by default).

14 5-15 ® Round-Robin Scheduling

15 5-16 ® 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.

16 5-17 ® Performance Enhancements All tasks reside in a common address space. All tasks run in supervisor (privileged) mode.

17 5-18 ® Multitasking Facilities

18 5-19 ® 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.

19 5-20 ® Real-Time Multitasking Introduction 5.2Task Basics Task Control Error Status System Tasks

20 5-21 ®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( )).

21 5-22 ® Creating a Task

22 5-23 ® Creating a Task int taskSpawn (name, priority, options, stackSize, entryPt, arg1, …, arg10) nameTask name, if NULL gives a default name. priorityTask priority optionsTask options e.g. VX_UNBREAKABLE. stackSizeSize of stack to be allocated in bytes. entryPtAddress of code to start executing (initial PC). arg1,..., arg10Up to 10 arguments to entry-point routine. Returns a task id or ERROR if unsuccessful.

23 5-24 ® Task IDs 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). taskLib Relevant taskLib routines: taskIdSelf( )Get ID of calling task. taskIdListGet( )Fill array with IDs of all existing tasks. taskIdVerify( )Verify a task ID is valid.

24 5-25 ® Task Names Provided for human convenience. –Typically used only from the shell (during development). –Within programs, use task Ids. t By (often ignored) convention, task names start with a t. –Promotes interpretation as a task name. t –Default name is a t followed by an ascending integer. Doesnt have to be unique (but usually is). taskLib Relevant taskLib routines: taskName( )Get name from tid. taskNameToId( )Get tid from task name.

25 5-26 ® 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 applications behavior more difficult to analyze.

26 5-27 ® 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.

27 5-28 ® 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.

28 5-29 ® Task Options Can be bitwise ored together when the task is created: VX_FP_TASKAdd floating point support. VX_NO_STACK_FILLDont fill stack with 0xees. VX_UNBREAKABLEDisable breakpoints. VX_DEALLOC_STACKDeallocate 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.

29 5-30 ® 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.

30 5-31 ® 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.

31 5-32 ® Resource Reclamation Contrary to the philosophy of sharing system resources among all tasks. Can be an expensive process, which must be the applications 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.

32 5-33 ® Real-Time Multitasking Introduction Task Basics 5.3Task Control Error Status System Tasks

33 5-34 ® Task Restart taskRestart (tid) Task is terminated and respawned with original arguments and tid. Usually used for error recovery.

34 5-35 ® 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.

35 5-36 ® 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.

36 5-37 ® 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. taskVarLib See the taskVarLib manual pages for details.

37 5-38 ® 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. taskHookLib See manual pages on taskHookLib for details.

38 5-39 ® 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) -> show (tNetTask, 1)

39 5-40 ® Task Browser Show To obtain information about a specific task, double-click on the tasks summary line in the main task browser display, or enter the tasks ID in the Show box.

40 5-41 ® 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 b 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.

41 5-42 ® What does VxWorks Support? LibraryDescription aioPxLib Asynchronous I/O semPxLib POSIX Semaphores mqPxLib POSIX Message Queues mmanPxLib POSIX Memory Management schedPxLib POSIX Scheduler Interface sigLib POSIX Signals timerLib, clockLib POSIX Timer/Clock Interface dirLib File/Directory Information

42 5-43 ® Real-Time Multitasking Introduction Task Basics Task Control 5.4Error Status System Tasks

43 5-44 ® 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.

44 5-45 ® Errno and Context Switches At each context switch, the kernel saves and restores the value of errno.

45 5-46 ® 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 - dont redefine it */ return (ERROR) }... }

46 5-47 ® Examining 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( ); }

47 5-48 ® Interpreting Errno VxWorks uses the 32-bit value errno as follows: vwModNum.h –VxWorks module numbers are defined in vwModNum.h. –Each module defines its own error numbers in its header file. For example, an errno of 0x would be: vwModNum.hmemLib –Module number 0x11 (defined in vwModNum.h to be memLib) and memLib.h –Error number 0x01 (defined in memLib.h to be not enough memory). module error number

48 5-49 ® Error 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);... }

49 5-50 ® User-Defined Error Codes To allow strerror_r() to support your error messages: 1.Create a user header file directory. xxModNum.h 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) statTbl.o 4.Rebuild the system error table, statTbl.o. development tool components > symbol table components > error status table 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.

50 5-51 ® Real-Time Multitasking Introduction Task Basics Task Control Error Status 5.5System Tasks

51 5-52 ® System Tasks Task NamePriorityFunction tUsrRoot0First task. Initializes included facilities, spawns user application, and exits. tLogTask0Message logging. tExcTask0Server which executes miscellaneous task-level functions at high priority. tWdbTask3WDB run-time agent. tNetTask50Task-level network functions. tFtpdTask55FTP server.

52 5-53 ®Summary Real-time multitasking requirements: –Preemptive priority-based scheduler –Low overhead Task properties stored in tasks 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

53 5-54 ®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

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

Similar presentations

Ads by Google