1 / 53

Real-Time Multitasking

Real-Time Multitasking. 5.1 Introduction Task Basics Task Control Error Status System Tasks. What is Real-Time?. Real-time denotes the ability of a control system to keep up with the system being controlled.

nakia
Download Presentation

Real-Time Multitasking

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Real-Time Multitasking 5.1 Introduction Task Basics Task Control Error Status System Tasks

  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.

  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.

  4. Design Options

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

  6. 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. Task States

  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

  9. Kernel Operation

  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.

  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.

  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.

  13. Priority Based Preemption • Equal priority tasks won’t preempt each other(by default).

  14. Round-Robin Scheduling

  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.

  16. Performance Enhancements • All tasks reside in a common address space. • All tasks run in supervisor (privileged) mode.

  17. Multitasking Facilities

  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.

  19. Real-Time Multitasking Introduction 5.2 Task Basics Task Control Error Status System Tasks

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

  21. Creating a Task

  22. Creating 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.

  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.

  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( ) Get name from tid. taskNameToId( ) Get tid from task name.

  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.

  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.

  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.

  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.

  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.

  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.

  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.

  32. Real-Time Multitasking Introduction Task Basics 5.3 Task Control Error Status System Tasks

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

  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.

  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.” • UsesysClkRateSet( )to change the clock rate.

  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.

  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.

  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)

  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.

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

  42. Real-Time Multitasking Introduction Task Basics Task Control 5.4 Error Status System Tasks

  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.

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

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

  46. 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. error number module Interpreting Errno • VxWorks uses the 32-bit value errno as follows: 31 15 0 • 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”).

  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: • 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. 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.

  50. Real-Time Multitasking Introduction Task Basics Task Control Error Status 5.5 System Tasks

More Related