Home

MQX-User Manual

image

Contents

1. Function Name handle watchdog expiry Returned Value none Comments This function is called when a watchdog has expired void handle watchdog expiry pointer td ptr Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 103 Using MQX printf nwatchdog expired for task bp td ptr FUNCTION Function Name waste time Returned Value input value times 10 Comments i This function loops the specified number of times essentially wasting time _mgx uint waste time _mgx_uint n mqx uint i volatile _mgx uint result result 0 for i 0 i lt n i result 1 return result 10 TASK Task Name main task Comments This task creates a watchdog then loops performing work for longer and longer periods until the watchdog fires void main task uint 32 initial data MOX TICK STRUCT ticks _mgx uint result mqx uint n _time init ticks amp ticks 10 result watchdog create component BSP TIMER INTERRUPT VECTOR handle watchdog expiry if result MOX OK printf nError creating watchdog component _mgx exit 0 n 100 while TRUE result watchdog start ticks amp ticks n waste time n
2. Read data from the log printf nLog contains Mn while log read MY LOG LOG READ OLDEST AND DELETE 2 LOG ENTRY STRUCT PTR amp entry MOX OK Freescale MQX Real Time Operating System User Guide Rev 3 116 Freescale Semiconductor Using MQX printf Time 1d 03d 03d c c i d n entry HEADER SECONDS mgx uint entry HEADER MILLISECONDS mgx uint entry HEADER MICROSECONDS uchar entry C amp Oxff entry I Delete the log log destroy MY LOG mgx exit 0 3 11 1 8 1 Compiling the Application and Linking It with MQX 1 Goto this directory mqx examples log 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note 4 Type ten characters on the input console The program logs the characters and displays the log entry on the console FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 11 2 Lightweight Logs Lightweight logs are similar to logs see Section 3 11 1 Logs but with the following differences e All entries in all lightweight logs are the same size e You can create a lightweight log at a particular memory location e Lightweight logs
3. Create a message pool message pool msgpool create sizeof SERVER MESSAGE NUM CLIENTS 0 0 Create clients for i 0 i NUM CLIENTS i task create 0 CLIENT TASK i while TRUE msg ptr msgq receive server qid 0 printf c An msg ptr gt DATA O Return the message msg ptr gt HEADER TARGET QID msg ptr gt HEADER SOURCE QID msg_ptr gt HEADER SOURCE QID server qid msgq send msg ptr 3 7 7 10 4 Code for Client Task client c include lt string h gt include lt mgx h gt include lt bsp h gt include server h TASK Task Name client task Comments This task creates a message queue and allocates a message in the message pool It sends the message to the server task and waits for a reply It then frees the message void client task uint 32 index Freescale MQX Real Time Operating System User Guide Rev 3 78 Freescale Semiconductor Using MQX SERVER MESSAGE PTR msg ptr queue id client qid client qid msgq open queue number CLIENT QUEUE BASE index 0 while TRUE Allocate a message msg ptr SERVER MESSAGE PTR msg alloc message pool if msg ptr NULL printf nCould not allocate a message n _mgx exit 0 if msg ptr HEADER SOURCE QID client qid msg ptr gt HEADER TARGET OID msgq get id 0 SERVER QUEUE
4. Task Name main_task Comments This task logs 10 keystroke entries in a lightweight log then prints out the log END void main task uint 32 initial data LWLOG ENTRY STRUCT entry mgx uint result _mgx uint ij uchar C Create the lightweight log component result lwlog create component if result MOX OK printf Main task lwlog create component failed _mgx exit 0 Create a log result lwlog create MY LOG 10 0 if result MOX OK printf Main task lwlog create failed _mgx_exit 0 Write data to the log printf Enter 10 characters Mn for i 0 i lt 10 i c getchar result lwlog write MY LOG mgx max type c _mqx max type i 0 0 O 0 0 if result MOX OK printf Main task lwlog write failed Freescale MQX Real Time Operating System User Guide Rev 3 120 Freescale Semiconductor Using MQX Read data from the log printf nLog contains Mn while lwlog read MY LOG LOG READ OLDEST AND DELETE amp entry MOX OK printf Time dif MOX LWLOG TIME STAMP IN TICKS psp print ticks PSP TICK STRUCT PTR amp entry TIMESTAMP else printf S1d 031d 031d entry SECONDS entry MILLISECONDS entry MICROSECONDS Hendif printf c c I d n uchar entry DATA 0 amp Oxff mgx uint entry DATA
5. msgq close Closes a message queue msgq get count Gets the number of messages in a message queue msgq get id Converts a queue number and processor number to a queue ID Freescale MQX Real Time Operating System User Guide Rev 3 72 Freescale Semiconductor Table 3 18 Summary Using Messages continued msgq get notification function Gets the notification function that is associated with a message queue msgq get owner Gets the task ID of the task that owns a message queue msgq open Opens a private message queue msgq open system Opens a system message queue msgq peek Gets a pointer to the message that is at the head of a message queue does not dequeue the message msgq poll Poll non blocking for a message in a message queue msgq receive Receives a message from a message queue and waits for a specified number of milliseconds msgq receive for Receives a message from a message queue and waits for a specified tick time period msgq receive ticks Receives a message from a message queue and waits for a specified number of ticks msgq receive until Receives a message from a message queue and waits Using MQX for a specified tick time msgq send Sends a message to a message queue msgq send broadcast Sends a message to multiple message queues msgq send priority Sends a priority mes
6. 2 5 4 Controlling an MMU For some CPUs you must initialize the memory management unit MMU before you enable caches MOX functions let you initialize enable and disable an MMU and add a memory region to it You can control an MMU by using MMU page tables 2 5 5 Lightweight Memory Management If an application is constrained by data and code size requirements lightweight memory can be used It has fewer interface functions and smaller code and data sizes As a result some areas have less robustness removal of header checksums and are slower task destruction times If you change a compile time configuration option MQX uses the lightweight memory component when it allocates memory For more information see Section 3 14 Configuring MQX at Compile Time 2 6 Task Synchronization 2 6 1 Lightweight Events Lightweight events LWEvents are an optional component They are a low overhead way for tasks to synchronize using bit state changes Lightweight events require a minimal amount of memory and run quickly 2 6 2 Events Events are an optional component They support the dynamic management of objects that are formatted as bit fields Tasks and interrupt service routines can use events to synchronize and convey simple information in the form of bit state changes There are named and fast event groups Event groups can have autoclearing event bits whereby MQX clears the bits immediately after they are set An application can
7. Gets the absolute time in second millisecond time Freescale MQX Real Time Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 93 Using MQX Table 3 21 Summary Using the Time Component continued _time get ticks time get elapsed time get elapsed ticks time get hwticks time get hwticks per tick time get microseconds time get nanoseconds time get resolution time get ticks per sec time init ticks time normalize xdate time notify kernel time set time set hwticks per tick time set ticks time set resolution time set timer vector time set ticks per sec time ticks to xdate time to date time to ticks time xdate to ticks Gets the absolute time in tick time includes ticks and hardware ticks Gets the second millisecond time that has elapsed since the application started on this processor Gets the tick time that has elapsed since the application started on this processor Gets the number of hardware ticks since the last tick Gets the number of hardware ticks per tick Gets the calculated number of microseconds since the last periodic timer interrupt Gets the calculated number of nanoseconds since the last periodic timer interrupt Gets the resolution of the periodic timer interrupt Gets the frequency in ticks per second of the clock interrupt Initializes a tick time structure with a number of ti
8. Table 3 34 Summary Using Queues queue dequeue Removes the element that is at the start of the queue queue enqueue Adds the element to the end of the queue queue get size Gets the number of elements in the queue queue head Gets but doesn t remove the element that is at the start of the queue queue init Initializes the queue queue insert Inserts the element in the queue queue is empty Determines whether the queue is empty Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 125 Using MQX Table 3 34 Summary Using Queues continued queue next Gets but doesn t remove the next element in the queue queue test Tests the queue queue unlink Removes the specific element from the queue 3 12 1 1 Queue Data Structures The queue component requires two data structures which are defined in mgx h QUEUE STRUCT keeps track of the size of the queue and pointers to the start and end of the queue MQX initializes the structure when a task creates the queue QUEUE ELEMENT STRUCT defines the structure of a queue element The structure is the header structure of an application defined object that the task wants to queue 3 12 1 2 Creating a Queue A task creates and initializes a queue by calling _queue_init with a pointer to a queue object and the maximum size of the queue 3 12 1 3 Adding Elements To a Queue A task adds an el
9. first_user_ISR first_user_ISR 1 last_user_ISR Table 3 25 Summary Handling Interrupts and Exceptions _int_disable Disables hardware interrupts _int_enable Enables hardware interrupts _int_get_isr Gets the ISR for a vector number _int_get_isr_data Gets the data pointer associated with an interrupt _int_get_isr_depth Gets the current ISR nesting depth _int_get_kernel_isr Gets the kernel ISR for an interrupt _int_get_previous_vector_ Gets a pointer to the interrupt vector table that is stored table when MQX starts _int_get_vector_table Gets a pointer to the current interrupt vector table _int_install_isr Installs an application defined ISR int_install_kernel_isr Installs a kernel ISR _int_install_unexpected_isr Installs _int_unexpected_isr as the default ISR _int_kernel_isr The default kernel ISR _int_set_isr_data Sets the data associated with a specific interrupt _int_set_vector_table Changes the location of the vector table 3 10 1 Initializing Interrupt Handling When the MQX starts it initializes its ISR table which has an entry for each interrupt number Each entry consists of Freescale MQX Real Time Operating System User Guide Rev 3 106 Freescale Semiconductor Using MQX A pointer to the ISR to call Data to pass as a parameter to the ISR A pointer to an exception handler for that ISR Initially the ISR for each entry is the default ISR int default isr which
10. 3 9 6 1 Creating the Watchdog Component Before a task can use the watchdog component the application must explicitly create it by calling watchdog create component with the interrupt vector of the periodic timer device and a pointer to the function that MQX will call if a watchdog expires 3 9 6 2 Starting or Restarting a Watchdog A task starts or restarts its watchdog by calling either e watchdog start with the number of milliseconds before the watchdog expires e watchdog start ticks with the number of ticks before the watchdog expires If the task does not restart or stop its watchdog before the watchdog expires MQX calls the expiry function 3 9 6 3 Stopping a Watchdog A task can stop its watchdog with watchdog stop 3 9 6 4 Example Using Watchdogs A task creates the watchdog component on the periodic timer interrupt vector and specifies the expiry function handle watchdog expiry Then it starts a watchdog that will expire after two seconds To prevent its watchdog from expiring the task must either stop or restart the watchdog within two seconds watchdog c include lt mgx h gt include lt bsp h gt include lt watchdog h gt define MAIN TASK 10 extern void main task uint 32 extern void handle watchdog expiry pointer TASK TEMPLATE STRUCT MOX template list MAIN TASK main task 2000 8 Main MQX AUTO START TASK OL O 0 0 O 0 0 0 OL 0 FUNCTION
11. Gets a pointer to the last memory block that caused mem test pool to indicate an error mem get highwater Gets the highest memory address that has been allocated in the default memory pool it might have since been freed mem get highwater pool Gets the highest memory pool address that has been allocated it might have since been freed Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 37 Using MQX Table 3 3 Summary Managing Memory with Variable Size Blocks continued _mem_get_size Gets the size of a memory block the size might be larger than the requested size _mem_swap_endian Converts to the other endian format mem test Tests the default memory pool this is checking the internal checksums to determine whether the integrity of the memory has been violated usually the cause of failure is that an application writes past the end of a memory block mem test and set Tests and sets a memory location mem test pool Tests the memory pool for errors as described for mem test mem transfer Transfers ownership of a memory block to another task mem zero Sets all or part of a memory block to zero 3 6 2 Managing Lightweight Memory with Variable Size Blocks Lightweight memory functions are similar to the functions for regular memory that are described in Section 3 6 1 Managing Memory with Variable Si
12. Logs are an optional component that lets you store and retrieve application specific information Each log entry has a timestamp and sequence number You can use the information to test debug verify and analyze performance 2 11 2 Lightweight Logs Lightweight logs are similar to logs but use only fixed sized entries They are faster than the conventional application logs and are used by kernel log 2 11 3 Kernel Log Kernel log is an optional component that lets you record MQX activity You can create kernel log at a specific location or let MQX choose the location You can configure kernel log to record all MQX function calls context switches and interrupt servicing Performance tool uses kernel log 2 11 4 Stack Usage MQX has core functions that let you dynamically examine the interrupt stack and the stack usage by all tasks so that you can determine whether you have allocated enough stack space 2 12 Error Handling 2 12 1 Task Error Codes Each task has a task error code which is associated with the task s context Specific MQX functions read and update the task error code 2 12 2 Exception Handling You can specify a default ISR that runs for all unhandled interrupts and an ISR specific exception handler that runs if the ISR generates an exception Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 21 MQX at a Glance 2 12 3 Run Time Testing MQX provides core run time
13. time diff picoseconds time diff seconds time diff ticks time from date time get Converts tick time to second millisecond time Adds days to tick time Adds hours to tick time Adds minutes to tick time Adds milliseconds to tick time Adds nanoseconds to tick time Adds picoseconds to tick time Adds seconds to tick time Adds microseconds to tick time Suspends the active task for the specified number of milliseconds Suspends the active task for the specified tick time period including hardware ticks Suspends the active task for the specified number of ticks Suspends the active task until the specified tick time Removes a task specified by its task ID from the timeout queue Removes a task specified by its task descriptor from the timeout queue Gets the second millisecond time difference between two second millisecond time structures Gets the time difference in days between two tick times Gets the difference in hours between two tick times Gets the difference in microseconds between two tick times Gets the difference in milliseconds between two tick times Gets the difference in minutes between two tick times Gets the difference in nanoseconds between two tick times Gets the difference in picoseconds between two tick times Gets the difference in seconds between two tick times Gets the tick time difference between two tick times Gets second millisecond time from date time
14. 38 Freescale Semiconductor Using MQX Table 3 4 Summary Managing Lightweight Memory with Variable Size Blocks Iwmem free Frees a lightweight memory block Iwmem get size Gets the size of a lightweight memory block the size might be larger than the requested size Iwmem set default pool Sets the pool to be used for the default lightweight memory pool Iwmem test Tests all lightweight memory pools Iwmem transfer Transfers ownership of a lightweight memory block to another task 3 6 3 Managing Memory with Fixed Size Blocks Partitions With the partition component you can manage partitions of fixed size memory blocks whose size the task specifies when it creates the partition There are dynamic partitions in the default memory pool that can grow and static partitions outside the default memory pool that cannot grow 3 6 3 1 Creating the Partition Component for Dynamic Partitions You can explicitly create the partition component with partition create component If you do not explicitly create it MQX creates it the first time an application creates a partition There are no parameters 3 6 3 2 Creating Partitions There are two types of partitions Type of partition Created from By calling Dynamic Default memory pool partition create Static Outside default memory pool partition create at If you create a static partition you must ensure that the memor
15. explicit scheduling Application defined scheduling that uses task queues See also FIFO scheduling and round robin scheduling F FALSE Not TRUE that is zero family of processors See processor family fast event group An event group that is identified by a number rather than by a name also called an indexed event group See also named event group fast semaphore A semaphore that is identified by a number rather than by a name also called an indexed semaphore See also named semaphore Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 163 FIFO scheduling First in first out queuing protocol With FIFO scheduling the active task is the highest priority task that has been ready the longest See also explicit scheduling and round robin scheduling fragmentation of memory Small deallocated freed memory blocks have become interspersed with allocated memory blocks H hardware tick A periodic timer interrupt uses a counter hardware tick occurs when the counter increments or decrements home processor See local host The hardware and its operating system for example a desktop personal computer on which you develop your application See also farget Idle task The MQX task that runs if no other tasks are ready image An application has one image for each processor on which the application runs The image includes application code and MQX code indexed event g
16. target h 130 task environment getting and setting 20 task error codes 11 getting and setting 20 task exceptions 98 task exit handlers 21 task ID specifying for active task MQX NULL TASK ID 20 task IDs getting 20 task parameters getting and setting 19 task queues 7 9 explicit scheduling 23 synchronizing tasks 33 example 68 task stacks usage getting 111 task template indexes getting 19 task template list 14 example 15 index from ID getting 19 MQX template list 15 task ID from name getting 19 task templates 14 creating tasks 19 structure 14 TASK TEMPLATE STRUCT 14 tasks aborting 21 autostart 13 15 example 16 creating at initialization 13 at runtime 19 Freescale MQX Real Time Operating System User Guide Rev 3 180 Freescale Semiconductor example 21 remotely 71 destroying 21 remotely 71 dispatch 25 DSP 15 floating point 15 logging specific tasks 109 managing 6 18 preemption 25 priority assigning 14 restarting 21 states 25 task environment getting and setting 20 task exception handler 98 task exit handler 21 task IDs getting 20 terminating 21 time slice 15 terminating tasks 21 test and set 26 testing 11 example 114 using testing 113 tick time format 82 time absolute 83 getting 83 setting 83 elapsed 82 in microseconds 83 in nanoseconds 83 resolution 83 elapsed versus absolute 83 format date 83 extended 84 millisecon
17. 3 Freescale Semiconductor 127 Using MQX Table 3 36 Summary Run Time Testing continued _msgq_test Message queues _mutex_test Mutexes _name test Name component _partition_test Memory with fixed size blocks partitions _queue test Application implemented queue sem test Semaphores taskq test Task queues timer test Timers watchdog test Watchdogs 3 12 3 1 Example Doing Run Time Testing The application uses all MQX components A low priority task tests all the components If it finds an error it stops the application test c include mgx h include lt fio h gt include lt event h gt include lt log h gt include lt lwevent h gt include lt lwlog h gt include lt lwmem h gt include lt lwtimer h gt include lt message h gt include lt mutex h gt include lt name h gt include lt part h gt include lt sem h gt include lt timer h gt include lt watchdog h gt extern void background test task uint 32 TASK TEMPLATE STRUCT MQX template list 10 background test task 800 8 Main MQX AUTO START TASK OL 0 0 0 0 0 0 0 OL 0 F JATASKAS 210 a a e S A AA A sr Ms EE Task Name background test task Comments This task is meant to run in the background testing for integrity of MQX component data structures SEND ese 335 23 SS A ae SSS Se ute AS Freescale MQX Real Time Operating System User Guide
18. 70 using 59 MMU 7 30 monitor types getting 117 MQX compile time options 118 configuring 118 directory structure 124 initializing 6 13 organization of 5 starting 6 13 MQX initialization structure 13 default 14 example 14 MQX init struct 14 MQX CHECK ERRORS 119 MQX CHECK MEMORY ALLOCATION ERRORS 119 MQX CHECK VALIDITY 119 MQX COMPONENT DESTRUCTION 119 MQX DEFAULT TIME SLICE IN TICKS 119 MQX EXIT ENABLED 119 MQX HAS TIME SLICE 119 MQX INCLUDE FLOATING POINT IO 119 mqx init c 14 131 133 MQX init struct 14 MQX INITIALIZATION STRUCT 13 Freescale MQX Real Time Operating System User Guide Rev 3 178 Freescale Semiconductor MQX IS MULTI PROCESSOR 119 MQX KERNEL LOGGING 119 MQX LWLOG TIME STAMP IN TICKS 120 MQX MEMORY FREE LIST SORTED 120 MQX MONITOR STACK 120 MQX MUTEX HAS POLLING 120 MQX NULL TASK ID 20 MQX PROFILING ENABLE 120 MQX RUN TIME ERR CHECK ENABLE 120 MQX TASK CREATION BLOCKS 120 MQX TASK DESTRUCTION 120 MQX template list 15 MQX TICK STRUCT 82 MQX TIMER USES TICKS ONLY 121 MQX USE 32BIT MESSAGE QIDS 121 MQX USE 32BIT TYPES 121 MQX USE INLINE MACROS 121 MQX USE LWMEM ALLOCATOR 121 mutex attributes 55 allocating 56 waiting protocols 55 mutex component creating 55 mutexes 8 33 allocating 56 deinitializing 57 destroying 57 example 57 initializing 56 default values 56 non default values 56 locking 57 trying to lock 57 mutex componen
19. 72 IPC Task 71 72 starting 74 IPC PROTOCOL INIT STRUCT 73 IPC ROUTING STRUCT 72 ISR exceptions 97 ISRs 10 93 application ISRs 94 changing defaults 97 functions ISRs cannot call 95 should not call 96 installing example 98 kernel ISR 93 periodic timer installing 83 restrictions 95 K kernel data getting 117 kernel ISR 93 default 93 getting 94 kernel log 10 enabling and disabling at compile time 119 example 109 logging disabling 109 Performance Tool 10 108 stack usage getting 111 using 107 L lightweight event bits 39 clearing 40 setting 40 using 39 waiting for 39 lightweight event component 8 33 39 using 39 lightweight event groups 39 creating 39 destroying 40 using 39 waiting for event bits 39 lightweight log component creating 104 lightweight logs 10 creating 105 example 106 reading 105 resetting 106 structure 105 using 104 writing 105 enabling and disabling 106 lightweight memory 8 variable size blocks 27 lightweight semaphores 8 33 destroying 43 example producer consumer 44 task synchronization and mutual exclusion 50 using 43 lightweight timers 9 cancelling 89 periodic queues 89 starting 89 using 88 89 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 177 lightweightevent groups setting event bits 40 lightweight memory blocks allocating 27 lightweight memory pools 27
20. BSP building new 129 compiling 133 directories 126 bsp h 130 bsp_prv h 130 building BSP new 129 C cache 7 29 flushing definition of 29 invalidating definition of 30 unified 29 cancelling timers 86 lightweight 89 client server example 63 closing event group connections 36 message queues 60 semaphore connections 49 comp c 131 compile time options configuring MQX 118 Index compiling BSP new 133 components core 5 optional 5 configuring MQX with compile time options 118 connections event groups to closing 36 opening 36 semaphores to closing 49 opening 49 copying bytes 26 coyright for MQX getting 117 CPU types getting and setting 117 creating application queues 112 event component 35 event groups 35 IPC component 72 lightweight event groups 39 lightweight log component 104 lightweight logs 105 lightweight semaphores 43 lightweight memory pools 27 log component 101 logs 101 kernel log 108 lightweight 105 memory pools 26 message component 60 message pools 60 mutex component 55 name component 113 partitions 28 semaphore component 48 semaphores 48 task queues 67 tasks at initialization 13 at runtime 19 example 21 remotely 71 timer component 85 watchdog component 90 creator getting 19 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 175 D date format 83 extended 84 DATE STR
21. FAQs Can I send messages between a PC and my target hardware Yes Create a program to run on your PC that sends and receives data packets to from the application either serially over PCI or over ethernet As long as the packets are formatted correctly MQX passes on any that it receives My task successfully calls msgq send several times with a newly allocated message each time Eventually _msgq_send fails You have probably run out of messages Each time you allocate a new message to send check whether the return is NULL If it is the receiving task is probably not freeing the messages or is not getting an opportunity to run 6 8 Mutexes What happens when the task that owns a mutex data structure is destroyed Do tasks that are waiting to lock the mutex wait forever No All components have cleanup functions When a task is terminated the cleanup function determines what resources the task is using and frees them If a task has a mutex locked MQX unlocks the mutex when it terminates the task A task should not own the mutex structure memory it should create the structure as a global variable or allocate it from a system memory block 6 9 Semaphores What happens if force destroy a strict semaphore If the force destroy flag is set when you destroy a strict semaphore MQX does not destroy the semaphore until all the waiting tasks get and post the semaphore If the semaphore is non strict MOX immediately readies a
22. Freescale MQX Real Time Operating System User Guide Rev 3 104 Freescale Semiconductor Using MQX watchdog stop printf Wn d n 3 9 6 4 1 Compiling the Application and Linking It with MOX 1 Goto this directory mqx examples watchdog 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note When the watchdog expires the Main task prints a message to the output device FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 10 Handling Interrupts and Exceptions MQX handles hardware interrupts and exceptions with interrupt service routines ISRs An ISR is not a task it is a small high speed routine that reacts quickly to hardware interrupts or exceptions ISRs are usually written in C The duties of an ISR might include Servicing a device clearing an error condition signaling a task When MQX calls an ISR it passes a parameter which the application defines when the application installs the ISR The parameter might for example be a pointer to a configuration structure that is specific to the device CAUTION The parameter should not point to data on a task s stack because this memory
23. MQX_CHECK_ERRORS 1 1 0 0 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 137 Using MQX MQX CHECK MEMORY ALLOCATION 1 1 0 0 ERRORS MQX CHECK VALIDITY 1 1 0 0 MQX COMPONENT DESTRUCTION 1 0 1 0 0 MQX DEFAULT TIME SLICE IN TICKS 0 O 1 1 1 MQX EXIT ENABLED 1 0 1 0 0 MQX HAS DYNAMIC PRIORITIES 1 O 1 0 0 MQX HAS EXIT HANDLER 1 O 1 0 0 MQX HAS TASK ENVIRONMENT 1 0 1 0 0 MQX HAS TIME SLICE 1 O 1 0 0 MQX INCLUDE FLOATING POINT IO 0 O 1 0 0 MQX IS MULTI PROCESSOR 1 O 1 0 0 MQX KD HAS COUNTER 1 0 1 O 1 0 MQX KERNEL LOGGING 1 1 0 0 MQX LWLOG TIME STAMP IN TICKS 1 0 1 1 MQX MEMORY FREE LIST SORTED 1 1 0 0 MQX MONITOR STACK 1 1 0 0 MQX MUTEX HAS POLLING 1 O 1 0 0 MQX PROFILING ENABLE 0 1 0 0 MQX ROM VECTORS 0 0 1 0 1 1 MQX RUN TIME ERR CHECK ENABLE O 1 0 0 MQX SPARSE ISR TABLE 0 0 1 0 1 MQX SPARSE ISR SHIFT in range 1 8 3 any lower higher MQX TASK CREATION BLOCKS 1 1 0 0 1 for multiprocessor applications MQX TASK DESTRUCTION 1 O 1 0 0 MQX TD HAS ERROR CODE 1 O 1 0 0 MQX TD HAS PARENT 1 0 1 0 0 MQX TD HAS STACK LIMIT 1 O 1 0 0 MQX TD HAS TASK TEMPLATE PTR 1 0 1 0 0 MQX TD HAS TEMPLATE INDEX 1 O 1 0 0 MQX TIMER USES TICKS ONLY 0 0 1 1 1 MQX USE 32BIT MESSAGE QIDS 0 0 1 1 1 MQX USE IDLE TASK 1 O 1 0 1 0 MQX USE INLINE MACROS 1 0 1
24. POSIX 1 basic OS interfaces POSIX 4 real time extensions and POSIX 4a threads extensions post verb When a task posts a semaphore or lightweight semaphore it releases the semaphore See also wait lock and unlock MQX An RTOS for single processor multi processor and distributed processor embedded real time applications preempt When MQX preempts the active task the task is no longer the active task MQX then performs a dispatch operation See also dispatch priority based preemptive scheduling See FIFO scheduling priority inheritance Priority inheritance prevents priority inversion While a task has locked a semaphore or a mutex that has priority inheritance MQX boosts the priority of the task to the priority of the highest priority task that is waiting for the semaphore or mutex See also priority protection priority inversion Might occur if tasks of different priority synchronize on objects such as semaphores The relative priorities of tasks are effectively inverted because a higher priority task is blocked waiting for a lower priority task to release the object See also priority inheritance priority protection priority protection Priority protection prevents priority inversion mutex can have a priority If the priority of a task that requests to lock the mutex task A is not at least as high as the mutex priority MQX raises the priority of task A to the mutex priority for as long as task A has the
25. Rev 3 128 Freescale Semiconductor void background test task uint 32 parameter partition id partition _lwmem pool id lwmem pool id pointer error ptr pointer error2 ptr _mgx uint error _mgx uint result while TRUE result event test amp error ptr if result MOX OK printf nFailed event test Ox X result _mgx exit 1 result log test amp error if result MOX OK printf nFailed log test 0x X result _mgx exit 2 result _lwevent test amp error ptr amp error2 ptr if result MOX OK printf nFailed lwevent test 0x X result _mgx exit 3 result _lwlog test amp error if result MOX OK printf nFailed lwlog test 0x X result _mgx exit 4 result _lwsem test amp error ptr amp error2 ptr if result MOX OK printf nFailed lwsem test 0x X result _mgx exit 5 result _lwmem test amp lwmem pool id amp error ptr if result MOX OK printf nFailed lwmem test 0x X result _mgx exit 6 result _lwtimer test amp error ptr amp error2 ptr if result MOX OK printf nFailed lwtimer test 0x X result _mgx exit 7 result mem test all amp error ptr if result MOX OK printf nFailed mem test all printf nError 0x X pool 0x X result mgx uint error ptr _mgx exit 8 Freescale MQX Real T
26. You can either define your own initialization values of the MQX initialization structure or use the default initialization that is provided with each BSP The default initialization variable is called MQX init struct and is in mqx init c in the appropriate BSP directory The function has been compiled and linked with MQX CAUTION For task aware debugging host tools to work the MQX initialization structure variable must be called MQX init struct The examples in this chapter use the following MQX init struct MOX INITIALIZATION STRUCT MOX init struct PROCESSOR NUMBER BSP DEFAULT PROCESSOR NUMBER START OF KERNEL MEMORY BSP DEFAULT START OF KERNEL MEMORY END OF KERNEL MEMORY BSP DEFAULT END OF KERNEL MEMORY INTERRUPT STACK SIZE BSP DEFAULT INTERRUPT STACK SIZE TASK TEMPLATE LIST pointer MQX template list MOX HARDWARE INTERRUPT LEVEL MAX BSP DEFAULT MQX HARDWARE INTERRUPT LEVEL MAX MAX MSGPOOLS BSP DEFAULT MAX MSGPOOLS MAX MSGQS BSP DEFAULT MAX MSGQS IO CHANNEL BSP DEFAULT IO CHANNEL IO OPEN MODE BSP DEFAULT IO OPEN MODE y NOTE Initialize both elements of the RESERVED field to zero 3 2 2 Task Template List The task template list which is a list of task templates TASK_TEMPLATE_STRUCT defines an initial set of templates from which tasks can be created on the processor At in
27. creating 27 limited spin 42 55 locking mutexes 57 log component creating 101 lightweight 104 LOG ENTRY STRUCT 101 logs 10 creating 101 lightweight 105 log component 101 lightweight 104 example 102 kernel log 109 log numbers reserved for 101 logging disabling kernel log 109 reading 101 lightweight 105 resetting 102 lightweight 106 stack usage getting kernel log 111 structure 101 lightweight 105 using 100 kernel log 107 lightweight 104 writing 101 lightweight 105 LWLOG ENTRY STRUCT 105 M make 133 managing tasks 6 memory variable size blocks 7 cache 7 29 initialization default memory pool 13 lightweight 8 MMU 7 30 pools 7 25 lightweight 27 variable size blocks 25 virtual controlling 30 with fixed size blocks highwater mark 29 with variable size blocks highwater mark 26 memory blocks 7 25 allocating 25 memory pools 7 25 creating 26 memory default memory pool 25 message component 8 creating 60 message headers endian conversion 79 message passing 33 message pools 9 creating 60 using 60 message queues 8 62 count getting 63 example 63 notification function 63 opening 63 private 63 queue ID 62 using 62 messages 8 allocating 25 61 exchanging between processors 70 freeing 61 message component creating 60 receiving private message queues using 63 remotely 70 system message queues using 63 sending 62 remotely
28. msg ptr 2HEADER SIZE sizeof MESSAGE HEADER STRUCT strlen char ptr msg ptr gt DATA 1 msg ptr DATA 0 A index printf Client Task d n index msgq send msg ptr Wait for the return message msg ptr msgq receive client qid 0 Free the message msg free msg ptr 3 7 7 10 5 Compiling the Application and Linking It with MQX 1 Goto this directory mqx examples msg 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 7 8 Task Queues You can use a task queue to e Schedule a task from an ISR e Do explicit task scheduling Implement custom synchronization mechanisms Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 79 Using MQX Table 3 19 Summary Using Task Queues _taskq_create Creates a task queue with the specified queuing policy FIFO or priority _taskq_destroy Destroys a task queue and puts any waiting tasks in the appropriate ready queues taskq get value Gets the size of a task queue taskq resume Restarts a task that is suspended in a task queue or restarts all tasks that are in a task que
29. 1 Destroy the log log destroy MY LOG _mgx exit 0 3 11 2 8 1 Compiling the Application and Linking It with MQX 1 Goto this directory mqx examples lwlog 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note 4 Type ten characters on the input console The program logs the characters and displays the log entry on the console 3 11 3 Kernel Log Kernel log lets an application log any combination of Function entry and exit information for all calls to MQX functions Function entry and exit information for specific function calls Context switches e Interrupts FREESCALE MQX To optimize code and data memory requirements on some target platforms the KLog component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 121 Using MQX Performance tool uses kernel log data to analyze how an application operates and how it uses resources For more information see MQX Host Tools User s Guide Table 3 31 Summary Using Kernel Log Kernel log uses certain struct
30. 1 0 Freescale MQX Real Time Operating System User Guide Rev 3 138 Freescale Semiconductor Using MQX MQX USE LWMEM ALLOCATOR 0 1 MQX_VERIFY_KERNEL_DATA 1 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 139 Using MQX Freescale MQX Real Time Operating System User Guide Rev 3 140 Freescale Semiconductor Chapter 4 Rebuilding MQX 41 Why to Rebuild MQX Rebuilding MQX is useful to enable convenient source level debugging of the MQX kernel When using factory precompiled libraries from MQX distribution the debugger may face difficulty in evaluating the path of the source files You need to rebuild MQX if you do any of the following e If you change compiler options for example optimization level e Ifyou change MQX compile time configuration options in the config board user config h file e If you develop a new BSP for example by adding a new I O driver e If you incorporate changes that you made to MQX source code CAUTION Do not modify MQX data structures If you do some MQX host tools might not perform properly Modify MQX data structures only if you are well experienced with MQX If you modify MQX data structures you must recompile MQX and rebuild it 4 2 Before You Begin Before you compile or build MQX e Read the MQX Release Notes that accompany Freescale MQX to get information that is s
31. ATTR STRUCT mutexattr char stringl Hello from Print task 1 n char string2 Print task 2 is aliveln Initialize mutex attributes if mutatr init amp mutexattr MOX OK printf Initializing mutex attributes failed Mn _mgx exit 0 Initialize the mutex if mutex init amp print mutex amp mutexattr MOX OK printf Initializing print mutex failed n _mgx exit 0 Create the print tasks task create 0 PRINT TASK uint 32 stringl task create 0 PRINT TASK uint 32 string2 JATASKi2 cociosiorpeslepetinanocaapiccicide bicapa ise sis est Task Name print task Comments This task prints a message It uses a mutex to ensure I O is not interleaved void print task uint 32 initial data while TRUE if mutex lock amp print mutex MOX OK printf Mutex lock failed Mn _mgx exit 0 _io puts char initial data mutex unlock amp print_mutex Freescale MQX Real Time Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 71 Using MQX 3 7 6 9 2 1 Goto this directory Compiling the Application and Linking It with MQX mqx examples mutex 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release notes 3 7 7 Messages Tasks can communicate with each other by exchanging messages Tasks al
32. MQX XDATE STRUCT and MQX TICK STRUCT with time ticks to xdate and time xdate to ticks typedef struct mqx xdate struct uint 16 YEAR uint 16 MONTH uint 16 MDAY uint 16 HOUR uint 16 MIN uint 16 SEC uint 16 MSEC uint 16 USEC uint 16 NSEC uint 16 PSEC Freescale MQX Real Time Operating System User Guide Rev 3 96 Freescale Semiconductor Using MQX uint 16 WDAY uint 16 YDAY MQX XDATE STRUCT PTR MQX XDATE STRUCT PTR The fields are described in MQX Reference 3 9 3 7 Timeouts A task can supply the time as a timeout parameter to several MQX components for example functions in the msgq receive and sem wait families A task can also explicitly suspend itself by calling a function from the time delay family When the time expires MQX puts the task in the task s ready queue 3 9 4 Timers Timers are an optional component that extends the core time component An application can use timers e To cause a notification function to run at a specific time when MQX creates the timer component it starts Timer task which maintains timers and their application defined notification functions When a timer expires Timer Task calls the appropriate notification function e To communicate that a time period has expired FREESCALE MQX To optimize code and data memory requirements on some target platforms the Timer component is not compiled in the MQX kernel by default To test this fea
33. Modify the program to remove priority inheritance and run the application again FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 7 6 Mutexes Mutexes are used for mutual exclusion so that only one task at a time uses a shared resource such as data or a device To access the shared resource a task locks the mutex associated with the resource The task owns the mutex until it unlocks the mutex FREESCALE MQX To optimize code and data memory requirements on some target platforms the Mutex component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details Mutexes are compatible with POSIX 4a threads extensions and provide priority inheritance and priority protection to prevent priority inversion Table 3 16 Summary Using Mutexes Mutex Description mutex create component Creates the mutex component mutex destroy Destroys a mutex mutex get priority ceiling Gets the priority of a mutex mutex get wait count Gets the number of tasks that are waiting for a mutex mutex init Initi
34. Operating System User Guide Rev 3 130 Freescale Semiconductor Using MQX 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note 3 12 4 Additional Utilities Table 3 37 Summary Additional Utilities _mqx_bsp_revision _mqx_copyright _mqx_date _mqx_fatal_error _mqx_generic_revision mqx get counter mqx get cpu type mqx get exit handler mqx get kernel data mqx get system task id mqx get tad data mqx idle task mqx io revision mqx monitor type mqx psp revision mqx set cpu type mqx set exit handler mqx set tad data mqx version mqx zero tick struct str mqx uint to hex string strnlen Revision of the BSP Pointer to the MQX copyright string Pointer to the string that indicates when MQX was built Indicates that an error has been detected that is severe enough that MQX or the application can no longer function properly Revision of the generic MQX code Gets a processor unique 32 bit number Gets the processor type Gets a pointer to the MQX exit handler which MQX calls when it exits Gets a pointer to kernel data Gets the task ID of System task descriptor Gets the TAD RESERVED field from a task descriptor Idle task I O revision for the BSP Monitor type Revision of the PSP Sets the processor type Sets the
35. Priority inversion might occur when tasks use semaphores or mutexes to gain access to a shared resource 3 7 3 3 Example Priority Inversion There are three tasks of three different priorities The mid priority task prevents the highest priority task from running Sequence Task 1 highest priority P1 Task 2 mid priority P2 Task 3 lowest priority P3 e Runs Gets semaphore 1 2 3 4 s made ready Preempties Task 3 and runs al Is made ready Preempties Task_2 and runs Tries to get semaphore that Task_3 has Blocks waiting for the semaphore Runs and keeps running 3 7 3 4 Avoiding Priority Inversion with Priority Inheritance When you create an MQX semaphore or mutex one of the properties that you can specify is priority inheritance which prevents priority inversion If you specify priority inheritance during the time that a task has locked a semaphore or mutex the task s priority is never lower than the priority of any task that waits for the semaphore or mutex If a higher priority task waits for the semaphore or mutex MQX temporarily raises the priority of the task that has the semaphore or mutex to the priority of the waiting task Table 3 11 Priority Inheritance Properties Sequence Task 1 highest priority P1 Task 2 mid priority P2 Task 3 lowest priority P3 Runs Gets semaphore Freesc
36. Project File 3 Select the build target that best suits your needs For example with the M52259EVB board you can use the Ext MRAM Debug target to simplify the code download process In this target the external MRAM memory is used by the executable code instead of internal flash while the on chip SRAM is used for data 4 Press the F7 key menu Project Make to make the project Freescale MQX Real Time Operating System User Guide Rev 3 28 Freescale Semiconductor Using MQX NOTE This procedure requires that you already have the MQX PSP and BSP libraries compiled on your host computer in the ib directory The Freescale MQX comes with pre compiled default libraries in the installation so this condition should be satisfied See the ib m52259evb cw directory in the Freescale MQX installation folder and check if there are the libraries in the mqx subdirectory If not please recompile the MQX system as described in section Section 4 5 Rebuilding Freescale MQX RTOS 5 When the build process completes open the HyperTerminal or other serial terminal on your host PC 6 In the terminal open the serial line with the following configuration 115200 bps eight data bits one stop bit no parity 7 In the CodeWarrior press the F5 key menu Project Debug to invoke the CodeWarrior debugger and to download the executable application into the MRAM memory The execution should stop at the default breakpoint
37. QUEUE BASE 9 This struct contains a data field and a message struct typedef struct MESSAGE HEADER STRUCT HEADER uchar DATA 5 SERVER MESSAGE PTR SERVER MESSAGE PTR Function prototypes extern void server task uint 32 initial data extern void client task uint 32 initial data extern pool id message pool 3 7 7 10 2 Task Templates for the Example ttl c include mgx h include lt bsp h gt include server h TASK TEMPLATE STRUCT MQX template list SERVER TASK Server task 600 5 server MOX AUTO START TASK OL 0 CLIENT TASK client task 600 5 client 0 OL 0 0 0 0 0 0 0 OL 0 3 7 7 10 3 Code for Server Task server c include lt mgx h gt include lt bsp h gt include server h Declaration of a global message pool _pool_id message pool Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 77 Using MQX TASK Task Name Server task Comments This task creates a message queue for itself allocates a message pool creates three client tasks and then waits for a message After receiving a message the task returns the message to the sender void server task uint 32 param SERVER MESSAGE PTR msg ptr uint 32 i queue id server gid Open a message queue server qid msgq open SERVER QUEUE 0
38. Time Elapsed time is the amount of time since MQX started on the processor A task can get the elapsed time in second millisecond time with time get elapsed and in tick time with time get elapsed ticks 3 9 3 4 Time Resolution When MQX starts it installs the periodic timer ISR which sets the time resolution for the hardware The resolution defines how often MQX updates time or how often a tick occurs The resolution is usually 200 ticks per second or five milliseconds A task can get the resolution in milliseconds with time get resolution and in ticks per second with time get resolution ticks A task can get elapsed time in microsecond resolution by calling time get elapsed followed by time get microseconds which gets the number of microseconds since the last periodic timer interrupt A task can get elapsed time in nanosecond resolution by calling time get elapsed followed by time get nanoseconds which gets the number of nanoseconds since the last periodic timer interrupt A task can also get the number of hardware ticks since the last interrupt by calling time get hwticks A task can get the resolution of the hardware ticks by calling time get hwticks per tick 3 9 3 5 Absolute Time So that the tasks on different processors can exchange information that is timestamped from a common reference the time component offers absolute time Freescale MQX Real Time Operating System User Guide Rev 3 Fre
39. _queue_id my_qid uint 32 test number 0 my qid msgq open MAIN QUEUE 0 qid msgq get id TEST2 ID RESPONDER QUEUE msgpool msgpool create sizeof THE MESSAGE 8 8 16 while test number 64 msg ptr THE MESSAGE PTR msg alloc msgpool msg ptr HEADER TARGET QID qid msg ptr HEADER SOURCE QID my qid msg ptr DATA test number putchar msgq send msg ptr msg ptr msgq receive MSGQ ANY QUEUE 10000 if msg ptr NULL puts Receive failed n _mgx_exit 1 else if msg ptr gt HEADER SIZE sizeof THE MESSAGE puts Message wrong size n _mgx exit 1 else if msg ptr gt DATA test number puts Message data incorrect n _mgx exit 1 msg free msg ptr puts All completen _mgx exit 0 3 8 4 5 3 Code for Processor Two ipc2 c include lt mgx h gt include lt bsp h gt include lt message h gt include lt ipc h gt include lt ipc_pcb h gt include lt io pcb h gt include lt pcb_mqxa h gt include ipc_ex h extern void responder task uint 32 TASK TEMPLATE STRUCT MQX template list IPC TTN _ipc task IPC DEFAULT STACK SIZE 6 ipc task MQX AUTO START TASK OL 0 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 89 Using MQX RESPONDER TTN responder task 2000 9 Responder MQX AUTO START TASK O 0 0 0 o 0 0 0 0 0 MOX INITIALIZA
40. a m s this is where MQX applications get the MOX from D max e rtcs usb O mfs MFS File System sources build projects and examples E O build 5 example 5 source e max MOX Operating System sources build projects and examples E 3 build E 5 examples 5 source D ES E ttes RTCS TCP IP Stack sources build projects and examples build D examples O source 3 shell Shell Support Library build El 5 source tools PC Host Tools usb a host USB Host Drivers sources build projects and examples 4 build CD examples D source E E Figure 4 1 Directory Structure of Freescale MQX RTOS Freescale MQX Real Time Operating System User Guide Rev 3 142 Freescale Semiconductor Rebuilding MQX 4 3 1 MQX RTOS Directory Structure Figure 4 2 shows the directory structure of the MQX RTOS component located in the top level mqx directory in more detail se C3 build O codewarrior D examples source El bsp a m52259demo BSP source code specific to M52259EVB board build to BSP library CO m52259evb O eds edserial MOX generic sources build to PSP library eve
41. address of the MQX exit handler which MQX calls when it exits Sets the TAD_RESERVED field in a task descriptor Pointer to the string that indicates the version of MQX A constant zero initialized tick structure that an application can use to initialize one of its tick structures to zero Converts an mqx uint value to a hexadecimal string Calculates the length of a limited length string Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 131 Using MQX 3 13 Embedded Debugging There are several ways how to debug the MQX based applications e Using plain debugger environment which is not aware about the MQX operating system This simple approach may work well when using breakpoints and single stepping through application code Using opearating system awareness in the debugger so called task aware debugger or TAD This approach helps to see the debugged code in the context of individual tasks It also helps to examine the internal MQX data strucutres in a user friendly way Using the EDS server in the target code and using the EDS client Freescale MQX Remote Debug Tool This tool connects to the target system over the serial line TCP IP or other kind of communication interface and provides information similar to the TAD FREESCALE MQX For more information about the Freescale MQX Remote Debug Tool please see the Freescale MQX Host Tools User s Guide The F
42. blocks the active task 3 10 2 Installing Application Defined ISRs With int install isr an application can replace the ISR with an application defined interrupt specific ISR which MQX calls when the interrupt occurs The application should do the replacement before it initializes the device The parameters for int install isr are interrupt number pointer to the ISR function ISR data An application defined ISR usually signals a task which can be done by Setting an event bit event set Posting a lightweight semaphore Iwsem post Posting a non strict semaphore sem post Sending a message to a message queue An ISR can also receive a message from a system message queue msgq send family Tir The most efficient way to allocate a message from an ISR is to use msg alloc dequeuing a task from a task queue which puts the task in the task s ready queue Task queues let you implement signaling methods that are customized for your application _taskq_resume 3 10 3 Restrictions on ISRs The following table contains information about ISR restrictions Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 107 Using MQX 3 10 3 1 Functions That the ISR Cannot Call MQX returns an error if the ISR calls any of the following functions Component Function Events _event_close _event_create event create auto clear ev
43. board specific pin initialization functions e processor specific header file lt board gt h e processor specific source code files e h files for device driver API 5 5 3 board h The lt board gt h file where board is the name of the target board declares board specific definitions for The board type Memory map symbols of the board such as the base addresses and size of different memory areas Flash RAM External memory etc Resolution and frequency of the periodic timer interrupt e Bus clock and system clock values e Range of interrupts for which an application can install ISRs Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 151 Developing a New BSP e Interrupt vector numbers and interrupt priorities for device drivers including the periodic timer e Default values for the MQX initialization structure All other hardware definitions that are unique to the board such as board specific registers symbolic names for buttons LEDs Analog channels etc e Default configuration options for the I O drivers 5 6 Modifying Startup Code A BSP provides default startup functions that set up the run time environment and then call mqx which starts MQX The startup code is located in a compiler specific subdirectory within the BSP Depending on the implementation it may partly reuse code from a standard startup process available in the compiler specific
44. can be timestamped in tick time or second millisecond time depending on how the MQX was configured at compile time for more information see Section 3 14 Configuring MQX at Compile Time Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 117 Using MQX FREESCALE MQX To optimize code and data memory requirements on some target platforms the LWLog component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details Table 3 30 Summary Using Lightweight Logs Lightweight logs use certain structures and constants which are defined in wlog h wlog calculate size Calculates the size needed for a lightweight log with a specified maximum number of entries lwlog create Creates a lightweight log wlog create at Creates a lightweight log at a location lwlog create component Creates the lightweight log component _Iwlog_destroy Destroys a lightweight log _Iwlog_disable Disables logging to lightweight logs _Iwlog_enable Enables logging to lightweight logs _Iwlog_read Reads from a lightweight log _Iwlog_reset Resets the contents of a lightweight log _Iwlog_test Tests the lightweight log component _Iwlog_write Writes to a lightweight log
45. d EA eoi UE AAA AENA NAAA 17 25 Memory Management 1214349999 dr da deli dqed ir OR od dO dp deed iles Rd d lg 2 5 1 Managing Memory with Variable Size Blocks 17 2 5 2 Managing Memory with Fixed Size Blocks Partitions 17 E53 BONN Cachos ads Sid da 18 2 5 4 Controlling an MMU iii WERE Ee er oU be PRES 18 2 5 5 Lightweight Memory Management sos so hh hx zas 18 26 Soie ros 18 A AG 5 182 dated elect dee eh dee eee rm 18 AOA UI ee sadu qid tee a is RU ode hdc he edie dad Ad dk ee ch han d 18 2 6 3 Lightweight Semaphores lt ncpiacdsdiwiececcucsasipiaeaaedcawees eed 18 EB E AAA 18 Ln AI eran AI E ARS EU 19 LAS MESAS 12 c4 AAA AAA ANNAN 19 ED TOR UU cr da ri ds e as e e 19 23 Inter Processor Communication 45 a me ri dea cds ddr Ra CRCR rt dis 19 E UU rss depu dca ch ecco eaae en eo edd dodi ec eio hy Hi ra ni Cade ec e o ba A 19 2 8 1 Time Component rra ane ait Te A a ai 19 28 2 Lie VINES sois sa pri ete an a ca ca 20 LRA FEN aoi E bbred eR Fb EA de EP ORE EHE RE HS de defen dere Yo dub PR 20 20A Veale PPP 20 2 9 Intemupt and Exception Handling cojos a A 20 FAR TODOS cius tebe tue da Specs dora iu oe eis A dese 20 215 1 POIS ELE 244 bo eh dd d i trad de ee eo ordo aere d leen 20 2 102 VO SUBSySEM DD SR Elan Rada bonfesiet acer d uad ades 21 ET PT acad 6 Oe n een OO Cede dE ee acd A RRA dede A ac dd 21 PA LE a IE ACT PP AAA 21 ARA RON 422 Rs pin II 21 S ILS Komel LE ohne eee
46. d b ee de ee os E Ud CR e as ES aie E 21 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 3 re AM MP 21 212 Eror Handing 5 55 31 4 ob he Sh RC EUR DR C EC OEE C ERR C eae e dca ER ed 1 2 12 1 Task Error Codes AA tiens Ee eee es CR d rDrendin 21 2 12 2 Buceo HSA us dci rm Oe HR eC sentant ren ee Ne Es 21 2 12 3 Run Time Testing caian arroces errar Eds ae 22 213 Queue SO PUN iuauas assess ed ADR d RR OR CU DIG BORA iot di 3d 33d c d 22 214 Name CONG 2 uu na cock caw ieee ado ded a RR delire Salinas 22 2 19 Embedded DepuggiNg PSP eee Od E dodo P RRSP KE OE E bip ie d 22 Chapter 3 Using MQX Z1 BOGS TOU BOG sisi sans Geet dd acc eoa edel aee CR c xo eR CA GI C ORC 23 3 2 Initializing and Starting MQX ss cine sd dd Ar d Fe GP RR aoo doe abd bm 23 3 2 1 MQX Initialization Structure oU EROR AAA ced 23 322 Task Template LISE Ji ssissssbhosessaneinssi inapentissliiastissdadss 24 3 3 Using Freescale CodeWarrior Development Studio 28 ms Die AA 30 CN TAS du del Opec YO ew doo ole ee poe cl COE JC dre dX doe RR c 31 gade CT Do AAA Ob RE ii REE 31 3 4 3 Setting a Task Environment sommet dore nee RS RIRE ee RE 31 1 NINAS Task ED S dtd eee TDI 31 445 Restarting TaskS Lualaaamaas geh deed ed dod tere pod di dee ead me 32 SENE Ud 1 10 FOCUS tk iene nee dr ri e 32 3 4 7 Example Creating ABR duse we d oa o A 4 ap GO ECC Ec ec ed 32 35 Scheduling Le PS RITTER TO TIT
47. file Freescale MQX Real Time Operating System User Guide Rev 3 132 Freescale Semiconductor Using MQX The default values are defined in the mgx source include mgqx_cnfg h file NOTE Do not change the mqx_cnfg h file directly Always use the board specific or project specific user config h file in your config directory MQX CHECK ERRORS Default is one One MQX components perform error checking on all their parameters MQX CHECK MEMORY ALLOCATION ERRORS Default is one One MQX components check all memory allocations for errors and verify that the allocations are successful MQX CHECK VALIDITY Default is one One MQX checks the VALID field of all structures when it accesses them MQX COMPONENT DESTRUCTION Default is one One MQX includes the functions that allow MQX components such as the semaphore component or event component to be destroyed MQX reclaims all the resources that the component allocated MQX DEFAULT TIME SLICE IN TICKS Default is one One Default time slice in the task template structure is in units of ticks Zero Default time slice in the task template structure is in milliseconds The value also affects the time slice field in the task template because the value is used to set a task s default time slice MQX EXIT ENABLED Default is one One MQX includes code to allow the application to return from the _mqx call MQX HAS TIME SLICE Default is one One MQ
48. in the main function Freescale CodeWarrior PEMICRO USB mi nj xj E Eile Edit View Search Project Debug Data MQX RTCS Tools Processor Expert Device Initialization Window Help 81 x Bese CEREREA RKA ES REEN dal ym x Ce E SE extmram del al xS MOX hello m52259evb mcp Helo ExtMRAM Debus v y gt B Files le Link Order Targets A Linker Files a Runtime Libraries Ga MOX Libraries Source BB hello c Asource bsp m52259evb cw2 c Comments Starts QX running int main void pi Body extern MQX INITIALIZATION STRUCT MOX init struct f Start wax mqx amp ox init struct return 8 Endbody 12 files Line 50 Col Source 8 Press F5 to continue executing the application 9 The Hello World appears on the terminal window See more details about the Freescale MQX projects created for Code Warrior Development Studio in the later sections in the Release Notes document and in Lab step by step guider available for your Freescale evaluation board Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 29 Using MQX 3 4 Managing Tasks Multiple tasks created from the same task template can coexist and each task is a unique instance MQX maintains each instance by saving its context that is its program counter registers and stack Each task has an application unique 32 bi
49. in the same priority ready queue When all the tasks in this ready queue have run the requesting task becomes active again If the mutex is still locked the spin repeats Limited spin Spins for a specified number of times or fewer if another task unlocks the mutex first If the mutex is already locked the requesting task does this Spin only protocol functions properly only if the tasks that share the mutex are either time slice tasks the same priority If non time slice tasks of different priority try to share a spin only mutex a higher priority task that wants to lock the mutex that is locked by a lower priority task will never get the lock unless the lower priority task blocks Spin only protocol mutexes are prone to deadlock and are not recommended MQX provides them for compatibility to POSIX Freescale MQX Real Time Operating System User Guide Rev 3 68 Freescale Semiconductor Using MQX 3 7 6 4 Scheduling Protocols A mutex can have special scheduling protocols that avoid priority inversion The policies might affect the priority of a task during the time that the task has the mutex locked The default is for neither protocol to be in effect Scheduling protocol Meaning Priority inheritance If the priority of the task that has locked the mutex task A is not as high as the highest priority task that is waiting to lock the mutex task_B MQX raises the priority of task_A to be
50. it uses to open the event group After opening the remote processor event group an application can set any event bit in the event group An application cannot wait for event bits in a remote event group Table 3 9 Summary Using the Event Component Event Description event clear Clears the specified event bits in an event group event close Closes a connection to an event group event create Creates a named event group event create auto clear Creates a named event group with autoclearing event bits event create component Creates the event component event create fast Creates a fast event group event create fast auto Creates a fast event group with autoclearing event bits clear event destroy Destroys a named event group event destroy fast Destroys a fast event group event get value Gets the value of an event group event get wait count Gets the number of tasks waiting for event bits in an event group event open Opens a connection to a named event group Freescale MQX Real Time Operating System User Guide Rev 3 46 Freescale Semiconductor Table 3 9 Summary Using the Event Component continued _event_open_fast Opens a connection to a fast event group _event_set Sets the specified event bits in an event group on the local processor or on a remote processor _event_test Tests the event component _event_wait_all Waits for all the
51. library files in libN amp board compiler output directory for example libvn52259evb cw e Build projects are named to reflect the board name mgx build lt compiler gt bsp_ lt board gt lt prj gt for example mgxX build cwcf72 bsp_m52259evb mcp e Post link batch files set in build projects are also specific to the board for example mgx build bat bsp_m52259evb bat The steps to clone copy an existing configuration and save it under a different name are demonstrated on the M52259EVB example used with CodeWarrior build tools e Copy existing configvn52259evb directory and assign a new board specific or configuration specific name to it for example configvn52259evb test e Create new output directory in the lib folder for example lib n52259evb_test cw e Create a copy of BSP and PSP build projects mgx build cw72 bsp_m52259evb mcp and psp m52259evb mcp and assign a new name to both of these files Freescale MQX Real Time Operating System User Guide Rev 3 146 Freescale Semiconductor Rebuilding MQX Open project settings and change include search paths referencing the old user configuration directory i e edit the config m52259evb search path to config m52259evb_test In the project settings change the output directory to the one newly created in the lib directory from lib n52259evb cw to lib n52259evb_test cw e Consider if you also want to clone the post link batch files and change the project
52. mem ptr sizeof data to duplicate 0 if result MQX NULL TASK ID result mmu create vtask VMEM TTN 0 amp data to duplicate virtual mem ptr sizeof data to duplicate 0 if result MQX NULL TASK ID 3 7 Synchronizing Tasks You can synchronize tasks by using one or more of the following mechanisms which are described in subsequent sections Events tasks can wait for a combination of event bits to become set A task can set or clear a combination of event bits Lightweight events simpler implementation of events e Semaphores tasks can wait for a semaphore to be incremented from non zero A task can post increment the semaphore MQX semaphores prevent priority inversion by providing priority inheritance For a discussion of priority inversion see page 53 Lightweight semaphores simple counting semaphores e Mutexes tasks can use a mutex to ensure that only one task at a time accesses shared data To access shared data a task locks a mutex waiting if the mutex is already locked When the task is finished accessing the shared data it unlocks the mutex Mutexes prevent priority inversion by providing priority inheritance and priority protection For details see page 67 Message passing lets tasks transfer data between themselves A task fills a message with data and sends it to a particular message queue Another task waits for messages to arrive at the message queue receives mess
53. might not be available to the ISR The ISR might run with some interrupts disabled depending on the priority of the interrupt being serviced Therefore it is important that the ISR performs a minimal number of functions The ISR usually causes a task to become ready It is the priority of this task that then determines how quickly the information gathered from the interrupting device can be processed The ISR can ready a task in a number of ways through events lightweight semaphores semaphores messages or task queues MQX provides a kernel ISR which is written in assembly language The kernel ISR runs before any other ISR and does the following It saves the context of the active task e It switches to the interrupt stack Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 105 Using MQX e It calls the appropriate ISR e After the ISR has returned it restores the context of the highest priority ready task When MQX starts it installs the default kernel ISR _int_kernel_isr for all possible interrupts When the ISR returns to the kernel ISR the kernel ISR performs a task dispatch operation if the ISR readied a task that is of higher priority than the one that was active at the time of the interrupt This means that the context of the previously active task is saved and the higher priority task becomes the active task The following diagram shows how MQX handles interrupts
54. opens its own input message queues message queue is uniquely identified by its queue ID which MQX assigns when the queue is created Only the task that opens a message queue can receive messages from the queue Any task can send to any previously opened message queue if it knows the queue ID of the opened queue Tasks allocate messages from message pools There are system message pools and private message pools Any task can allocate a message system message from system message pools Any task with the pool ID can allocate a message private message from a private message pool 2 6 7 Task Queues In addition to providing a scheduling mechanism task queues provide a simple and efficient way to synchronize tasks You can suspend tasks in the task queue and remove them from the task queue 2 7 nter Processor Communication Inter processor communication IPC is an optional component An application can run concurrently on multiple processors with one executable image of MQX on each processor The images communicate and cooperate using messages that are transferred by memory or over communication links using inter processor communication The application tasks in each image need not be the same and indeed are usually different 2 8 Timing 2 8 1 Time Component Time is an optional component that you can enable and disable at the BSP level There is elapsed time and absolute time You can change absolute time The time resolution depen
55. semaphores result lwsem create amp fifo READ SEM 0 if result MOX OK printf nCreating read sem failed 0x X result _mgx exit 0 result lwsem create amp fifo WRITE SEM 1 if result MOX OK printf nCreating write sem failed 0x X result _mgx exit 0 Create write tasks Freescale MQX Real Time Operating System User Guide Rev 3 58 Freescale Semiconductor Using MQX for i 0 i lt NUM WRITERS i task id task create 0 WRITE TASK uint 32 A i printf nwrite task created id Ox 1X task id while TRUE result _lwsem_wait amp fifo READ SEM if result MOX OK printf in _lwsem wait failed Ox X result _mgx exit 0 putchar n putchar fifo DATA lwsem post amp fifo WRITE SEM 3 7 4 4 5 Compiling the Application and Linking It with MOX 1 Goto this directory mqx examples lwsem 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note The following appears on the output device A w Paw FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 7 5 Semaphores Semaphores can be used for task
56. settings accordingly This step is not required in case your new BSP has the same set of drivers Ensure you have done the project settings change in all build targets available Debug and Release Repeat all the steps above for other MQX libraries like RTCS MFS or USB if needed Having a new configuration and build projects ready you may start modifying the build time configuration without affecting the original BSP libraries In case you want to create a completely new BSP you will need to create new BSP source files and change the content of the cloned BSP project Chapter 5 Developing a New BSP describes the new BSP development Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 147 Rebuilding MQX Freescale MQX Real Time Operating System User Guide Rev 3 148 Freescale Semiconductor Chapter 5 Developing a New BSP 5 1 What is a BSP A board support package BSP is a collection of hardware dependent files that rely on the specific features of a single board computer You may want to develop BSP that is not yet available Also if your target hardware is customization of the one that is supported it is recommended to develop a new BSP In the last section you have learnt how to clone an existing BSP and build projects for the new hardware configuration This section further describes what to keep in mind when developing a new BSP code 5 2 Overview To de
57. specified event bits in an event group for a specified number of milliseconds _event_wait_all for Waits for all the specified event bits in an event group for a specified tick time period including hardware ticks event wait all ticks Waits for all the specified event bits in an event group for a specified number of ticks event wait all until Waits for all the specified event bits in an event group until a specified tick time event wait any Waits for any of the specified event bits in an event group for a specified number of milliseconds event wait any for Waits for any of the specified event bits in an event group for a specified tick time period event wait any ticks Waits for any of the specified event bits in an event group for a specified number of ticks event wait any until Waits for any of the specified event bits in an event group until a specified tick time 1 Events use certain structures and constants which are defined in event h 3 7 1 1 Creating the Event Component Using MQX You can explicitly create the event component with event create component If you do not explicitly create it MQX creates it with default values the first time an application creates an event group Parameter Meaning Default Initial number Initial number of event groups that can be 8 created Grow number Number of additional event groups that
58. synchronization and mutual exclusion The main operations that a task performs on a semaphore are to wait for the semaphore and to post the semaphore FREESCALE MQX To optimize code and data memory requirements on some target platforms the Semaphore component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 59 Using MQX Table 3 15 Summary Using Semaphores Semaphore Description _sem_close Closes a connection to a semaphore _sem_create Creates a semaphore Sem create component Creates the semaphore component Sem create fast Creates a fast semaphore sem destroy Destroys a named semaphore sem destroy fast Destroys a fast semaphore Ssem get value Gets the current semaphore count sem get wait count Gets the number of tasks waiting for a semaphore Ssem open Opens a connection to a named semaphore sem open fast Opens a connection to a fast semaphore sem post Posts frees a semaphore Ssem test Tests the semaphore component sem wait Waits for a semaphore for a number of milliseconds sem wait for Waits for a semaphore for a tick time period se
59. task kernel log The log that can record MQX function calls context switches and interrupts and associate them with a timestamp in absolute time and sequence number See also log kernel memory Initially defined by the MQX initialization structure from START OF KERNEL MEMORY to END OF KERNEL MEMORY but an application can extend it by calling mem extend MOX allocates memory for tasks stacks and its own use from kernel memory L lightweight log Similar to logs except all entries have the same size and you can create a lightweight log at a particular location in memory lightweight memory Lightweight memory has fewer interface functions and smaller code and data sizes than the regular memory component lightweight semaphore A lightweight semaphore is faster and needs less memory than a semaphore it also has less functionality See also mutex and semaphore lightweight timer Lightweight timers provide a low overhead mechanism for calling application functions at periodic intervals Lightweight timers are installed by creating a periodic queue then adding a timer to expire at some offset from the start of the period Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 165 limited spin If a limited spin mutex is already locked when a task requests to lock it MQX reschedules the requesting task a limited number of times before the request fails See also spin only line A q
60. tasks synchronize each other with lightweight semaphores 1 Read task creates Multiple Write tasks and assigns a unique character to each One write LWSem One read LWSem 2 Each Write task waits for the Write LWSem before it writes a character into the buffer When the character is written each Write task posts the Read LWSem signaling that a character is available to the Read task 3 Read waits for the Read LWSem before it consumes the character After it consumes the character it posts the Write LWSem signaling that the buffer is ready for another character Freescale MQX Real Time Operating System User Guide Rev 3 56 Freescale Semiconductor 3 7 4 4 1 Definitions and Structures for the Example read h Number of Writer Tasks define NUM_WRITERS 3 Task IDs define WRITE TASK 5 define READ TASK 6 Global data structure accessible by read and write tasks Contains two lightweight semaphores that govern access to the data variable typedef struct sw fifo LWSEM_STRUCT READ SEM LWSEM STRUCT WRITE SEM uchar DATA SW FIFO PTR SW FIFO PTR Function prototypes extern void write task uint 32 initial data extern void read task uint 32 initial data extern SW FIFO fifo 3 7 4 4 2 Task Templates for the Example ttl c include mgx h include lt bsp h gt include read h TASK TEMPLATE STRUCT MOX template list WRITE TASK wr
61. test functions that an application can call during its normal operation There are test functions for the following components events and lightweight events kernel log and lightweight logs e memory with fixed size blocks partitions e memory with variable size memory blocks and lightweight memory message pools and message queues mutexes name component queues application defined e semaphores and lightweight semaphores task queues e timers and lightweight timers e watchdogs 2 13 Queue Manipulation There is a core component that implements a double linked list of queue elements You can initialize a queue add elements remove elements and peek at elements 2 14 Name Component The name component is optional It provides a names database that maps a string to a dynamically defined scalar such as a queue ID 2 15 Embedded Debugging EDS Server is optional It communicates with a host that is running EDS Client reading and writing MQX messages and getting various configuration information from the host Freescale MQX Real Time Operating System User Guide Rev 3 22 Freescale Semiconductor Chapter 3 Using MQX 3 1 Before You Begin This chapter describes how to use MQX It includes examples that you can compile and run For this information See Prototype for each function that is mentioned in this MQX Reference chapter Data types that are mentioned in this chapter MQX Refere
62. the MQX INITIALIZATION STRUCT If you do so the interrupt will be able to interrupt an MQX critical section For example on an ARCtangent processor MQX can be configured to never disable level 2 interrupts and to use only level 1 interrupts to disable enable in critical sections If the target hardware does not allow you to set the priority of the interrupt as described in the preceding paragraph use the event component to send a signal from the ISR to several tasks The tasks open connections to an event group and one of the tasks gives the ISR the connection Each task calls event wait any or event wait all and blocks The ISR calls _event_set to unblock the tasks When save and then restore an ISR for a specific interrupt how do I get the value of the data pointer that was associated with the original ISR Call int get isr data before you install the temporary ISR This function returns a pointer to the data of the specific vector that you pass to it 6 6 Memory How does a task transfer a memory block that it does not own Although the task that owns the memory is the one that usually transfers it a non owner can do so with mem transfer Freescale MQX Real Time Operating System User Guide Rev 3 156 Freescale Semiconductor FAQs My task allocates a 10 byte memory block but it always gets more Why When MQX allocates a memory block it aligns the block to the appropriate memory boundary and associ
63. the same as the priority of task_B while task_A has the mutex Priority protection A mutex can have a priority If the priority of a task that requests to lock the mutex task_A is not at least as high as the mutex priority MQX raises the priority of task_A to the mutex priority for as long as task_A has the mutex locked 3 7 6 5 Creating and Initializing a Mutex A task creates a mutex by first defining a variable of type MUTEX_STRUCT To initialize the mutex with the default attributes of a queuing waiting protocol and no special scheduling protocols the task calls _mutex_init with a pointer to the mutex variable and a NULL pointer However to initialize the mutex with attributes other than the default the task does the following l 2 3 It defines a mutex attributes structure of type MUTEX_ATTR_STRUCT It initializes the attributes structure with mutatr init It calls various functions to set the appropriate attributes choosing from _mutatr_set_priority_ceiling mutatr set sched protocol mutatr set spin limit mutatr set wait protocol It initializes the mutex by calling mutex init with pointers to the mutex and to the attributes structure When the mutex is initialized any task can use it It destroys the mutex attributes structure with mutatr destroy Table 3 17 Summary Using a Mutex Attributes Structure mutatr destroy Destroys a mu
64. then posted void read task uint 32 initial data pointer write sem pointer read sem pointer index sem Open connections to all semaphores if sem open write amp write sem MOX OK printf nOpening write semaphore failed _mgx exit 0 if sem open index amp index sem MOX OK printf nOpening index semaphore failed _mgx exit 0 if sem open read amp read sem MOX OK printf nOpening read semaphore failed _mgx exit 0 while TRUE Wait for the semaphores if sem wait read sem 0 MQX OK printf nWaiting for read semaphore failed _mgx exit 0 if sem wait index sem 0 MOX OK printf nWaiting for index semaphore failed _mgx exit 0 printf An 0x 1x fifo DATA fifo READ_INDEX if fifo READ INDEX gt ARRAY SIZE fifo READ INDEX 0 Post the semaphores Sem post index sem Sem post write sem 3 7 5 8 5 Code for the Write Task write c include lt mgx h gt Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 65 Using MQX include lt bsp h gt include lt sem h gt include main h TASK Task Name write task Comments This task opens a connection to all three semaphores then waits to lock a write and an index semaphore One element in the D
65. to be built or build all targets For specific information about rebuilding MQX and the examples that accompany it see the release notes that accompany the MQX 4 6 Creating Custom MQX Configurations and Build Projects 4 6 1 Why Creating a New Configuration Typical scenarios when you need to create a new set of build projects include e You want to have two or more different kernel configurations for a single board being used simultaneously in different applications This is a rather simple task of cloning the existing configuration directory and modifying the existing build projects changing name and output folder e You need to create a new BSP for custom board This is more complex task and may involve some new I O driver development or advanced configuration changes However the first step is to start with the most similar existing BSP clone it to assign a new name and further modify 4 6 2 Cloning Existing Configuration As described in the previous sections both the PSP and BSP build projects as well as projects for other MQX core components like RTCS MES or USB are bound to the target board name Using an example of M52259EVB board the following items depend on this name e User configuration is taken from config lt board gt directory for example configvn52259evb Build project include search paths are set to point to the user configuration directory e Build projects are set up to produce resulting binary
66. virtual context mmu destroy vcontext Destroys a virtual context for a task mmu get vmem attributes Gets the virtual memory attributes of an MMU page mmu get vpage size Gets the size of an MMU page mmu set vmem attributes Modifies the virtual memory attributes of an MMU page mmu vdisable Disables virtual memory mmu venable Enables virtual memory mmu vinit Initializes the MMU to use MMU page tables mmu vtop Gets the physical address that corresponds to a virtual address Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 43 Using MQX 3 6 5 1 Example Initializing the MMU with Virtual Memory Add a number of memory regions to support both instruction caching and data caching All tasks can access the regions max uint bsp enable operation void mmu vinit MPC860 MMU PAGE SIZE 4K NULL Set up and initialize the instruction cache mmu add vregion BSP FLASH BASE BSP FLASH BASE BSP FLASH SIZE PSP MMU CODE CACHE PSP MMU CACHED mmu add vregion BSP DIMM BASE BSP DIMM BASE BSP DIMM SIZE PSP MMU CODE CACHE PSP MMU CACHED mmu add vregion BSP RAM BASE BSP RAM BASE BSP RAM SIZE PSP MMU CODE CACHE PSP MMU CACHED Set up and initialize the data cache mmu add vregion BSP FLASH BASE BSP FLASH BASE BSP FLASH SIZE PSP MMU DATA CACHE PSP MMU CACHE INHIBITED
67. 12 4 Additional Utilities ca ir dr sh ga lek a a Ai oed dei dd at he 131 3 19 Embedded AAA ani iasauaecbatsasiis SA ame ee 132 3 14 Configuring MQX at Compile Time sus doetresdisssuada e see dass 132 3 14 1 MQX Compile Time Configuration Options 132 3 14 2 Recommended SEDIS si ssssssseturim diedervmen Ro io doa dre 187 Chapter 4 Rebuilding MQX 4 1 Why to Rebuild MQX air de a lt D ae ia ae asus 141 AB A auece ekvsee sd rdi E Id ad rid oe relate do dc oc 141 4 3 Freescale MQX Directory Structure 142 4 3 1 MOX RTOS Directory Structure 2 626 4660ssced een rigor ae 143 292 Por QUISO naiss isa tac as ae 143 4 3 3 BSP Subdirectories cios ddp REN Irt AAA GP ERE OS ARA 144 484 EO POURS AAA 144 4 3 5 Other Source Subdirectories isa cr es hd heeds oes see dat 144 4 4 Freescale MOX Build Projects 6c ccccewtev eG utum Rn Rara rnm m ORAS REOR 144 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 5 A a carita dude eed au diese eds lisa a dnb RR x 144 LU E dione 144 a8 Post Build PRES Lee wi ee ed d EAD Se d Re ed Rr Gil 145 BA BUIG TGS a dicke d dedi VO HERR EO e CCP EO LATUR Ol d dol C 145 4 5 Rebuilding Freescale MQX RTOS 146 4 6 Creating Custom MQX Configurations and Build Projects 146 4 6 1 Why Creating a New Configuration 146 4 6 2 Clo
68. 3 11 2 1 Creating the Lightweight Log Component You can explicitly create the lightweight log component with Iwlog create component If you do not explicitly create it MQX creates it the first time an application creates a lightweight log or kernel log 3 11 2 2 Creating a Lightweight Log A task can create a lightweight log at a particular location Iwlog create at or let MQX choose the location _lwlog_create With either function the task specifies e Log number in the range of one through 15 zero is reserved for kernel log Maximum number of entries in the log What happens when the log is full The default behavior is that no additional data is written Another behavior is that new entries overwrite the oldest ones In the case of Iwlog create at the task also specifies the address of the log Freescale MQX Real Time Operating System User Guide Rev 3 118 Freescale Semiconductor Using MQX 3 11 2 3 Format of a Lightweight Log Entry Each lightweight log entry has the following structure typedef struct lwlog entry struct _mgx_uint SEQUENCE NUMBER dif MOX LWLOG TIME STAMP IN TICKS 0 Time at which the entry was written uint 32 SECONDS uint 32 MILLISECONDS uint 32 MICROSECONDS else Time in ticks at which the entry was written MQX TICK STRUCT TIMESTAMP Hendif _mgx max type DATA LWLOG MAXIMUM DATA ENETRIES Struct lwlog entry struct PTR NEXT PTR LWL
69. ATA array is written to The index and read semaphores are then posted void write task uint 32 initial data pointer write sem pointer read sem pointer index sem Open connections to all semaphores if sem open write amp write sem MOX OK printf nOpening write semaphore failed mgx exit 0 if sem open index amp index sem MOX OK printf nOpening index semaphore failed mgx exit 0 if sem open read amp read sem MOX OK printf nOpening read semaphore failed mgx exit 0 while TRUE Wait for the semaphores if sem wait write sem 0 MOX OK printf nWaiting for write semaphore failed _mgx exit 0 if sem wait index sem 0 MOX OK printf nWaiting for index semaphore failed _mgx exit 0 fifo DATA fifO WRITE INDEX task get id if fifo WRITE INDEX gt ARRAY SIZE fifo WRITE INDEX 0 Post the semaphores Sem post index sem Sem post read sem 3 7 5 8 6 Compiling the Application and Linking It with MOX 1 Goto this directory mqx examples sem Freescale MQX Real Time Operating System User Guide Rev 3 66 Freescale Semiconductor Using MQX 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release notes Read task prints the data that is written to the FIFO
70. AUTO START TASK 0 0 0 0 0 0 D 0 Main 0 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 123 Using MQX TASK 222 O Task Name main task Comments This task logs timer interrupts to the kernel log then prints out the log void main task uint 32 initial data mgx uint result mgx uint i Create kernel log result klog create 4096 0 if result MOX OK printf Main task klog create failed mgx exit 0 Enable kernel log _klog control KLOG ENABLED KLOG CONTEXT ENABLED KLOG INTERRUPTS ENABLED KLOG SYSTEM CLOCK INT ENABLED KLOG FUNCTIONS ENABLED KLOG TIME FUNCTIONS KLOG INTERRUPT FUNCTIONS TRUE Write data into kernel log for i 0 i 10 i _time delay ticks 5 i Disable kernel log _klog control OxFFFFFFFF FALSE Read data from kernel log printf NnKernel log contains Mn while klog display O _mgx exit 0 3 11 3 3 1 Compiling the Application and Linking It with MQX 1 Goto this directory mqx examples klog 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note After about three seconds Main task displays the contents of kernel log Freescale MQX Real Time Operating S
71. C Routing Table The IPC routing table defines the routes for inter processor messages There is one routing table per processor and it is called ipc routing table In the previous example on processor two messages for Freescale MQX Real Time Operating System User Guide Rev 3 84 Freescale Semiconductor Using MQX processor one are directed to queue number 20 messages for processors three and four are directed to queue number 21 The routing table 1s an array of routing structures and ends with a zero filled entry typedef struct ipc routing struct _processor number MIN PROC NUMBER _processor number MAX PROC NUMBER _queue number QUEUE IPC ROUTING STRUCT PTR IPC ROUTING STRUCT PTR The fields are described in MQX Reference 3 8 4 1 1 Routing Table for Processor One IPC ROUTING STRUCT _ipc routing table 2 3 10 4 4 11 o 0 O 3 8 4 1 2 Routing Table for Processor Two IPC ROUTING STRUCT _ipc routing table Lo EL a 2X 3 4 20 0 0 0 3 8 4 1 3 Routing Table for Processor Three IPC ROUTING STRUCT _ipc routing table 15 2 31 4 4 30 o 0 O 3 8 4 1 4 Routing Table for Processor Four IPC ROUTING STRUCT _ipc routing table E uL 405 2 3 41 0 0 O 3 8 4 2 Building an IPC Protocol Initialization Table The IPC protocol initialization table defines and initializes the protocols that implement the IPC Each IPC output queue in the rou
72. CTOR isr ptr OLD ISR int get isr BSP TIMER INTERRUPT VECTOR int install isr BSP TIMER INTERRUPT VECTOR new tick isr isr ptr time delay ticks 200 printf nTick count d n isr ptr gt TICK COUNT mgx exit 0 3 10 8 1 Compiling the Application and Linking It with MQX 1 Goto this directory mqx examples isr 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note Main task displays the number of times the application ISR was called FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 11 Instrumentation Instrumentation includes the following components logs lightweight logs e kernel log e stack usage utilities Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 113 Using MQX 3 11 1 Logs Many real time applications need to record information about significant conditions such as events state transitions or function entry and exit information If the application records the information as it occurs you can analyze the sequence to determine whether the application processed conditions correctly If each piece of information has a timestamp in a
73. FAULT IO OPEN MODE y IPC ROUTING STRUCT _ipc routing table TEST2 ID TEST2 ID QUEUE TO TEST2 0 0 0 IO PCB MOXA INIT STRUCT pcb mqxa init IO PORT NAME ittyb BAUD RATE 19200 IS POLLED FALSE INPUT MAX LENGTH sizeof THE MESSAGE INPUT TASK PRIORITY T4 OUPUT TASK PRIORITY 4 IPC PCB INIT STRUCT pcb init IO PORT NAME pcb mgxa ittyb DEVICE INSTALL _io pcb mqxa install DEVICE INSTALL PARAMETER pointer amp pcb mqxa init IN MESSAGES MAX SIZE sizeof THE MESSAGE IN MESSAGES TO ALLOCATE 8 IN MESSAGES TO GROW 8 IN MESSAGES MAX ALLOCATE 16 OUT PCBS INITIAL 8 OUT PCBS TO GROW 8 OUT PCBS MAX 16 3 IPC PROTOCOL INIT STRUCT ipc init table ipc pcb init amp pcb init Pcb to test2 QUEUE TO TEST2 NULL NULL NULL 0 TASK Task Name main task Comments This task creates a message pool and a message queue then Sends a message to a queue on the second CPU It waits for a return message validating the message before Sending a new message Freescale MQX Real Time Operating System User Guide Rev 3 88 Freescale Semiconductor Using MQX void main task uint_32 dummy _pool_id msgpool THE_MESSAGE_PTR msg_ptr _queue_id qid
74. Freescale MQX Real Time Operating System User s Guide Document Number MQXUG Rev 3 04 2011 VO P bd freescale semicon ductor How to Reach Us Home Page www freescale com E mail support freescale com USA Europe or Locations Not Listed Freescale Semiconductor Technical Information Center CH370 1300 N Alma School Road Chandler Arizona 85224 1 800 521 6274 or 1 480 768 2130 support freescale com Europe Middle East and Africa Freescale Halbleiter Deutschland GmbH Technical Information Center Schatzbogen 7 81829 Muenchen Germany 44 1296 380 456 English 46 8 52200080 English 49 89 92103 559 German 33 1 69 35 48 48 French support freescale com Japan Freescale Semiconductor Japan Lid Headquarters ARCO Tower 15F 1 8 1 Shimo Meguro Meguro ku Tokyo 153 0064 Japan 0120 191014 or 81 3 5437 9125 support japan freescale com Asia Pacific Freescale Semiconductor China Ltd Exchange Building 23F No 118 Jianguo Road Chaoyang District Beijing 100022 China 86 10 5879 8000 support asia freescale com For Literature Requests Only Freescale Semiconductor Literature Distribution Center P O Box 5405 Denver Colorado 80217 1 800 441 2447 or 303 675 2140 Fax 303 675 2150 LDCForFreescaleSemiconductor hibbertgroup com LDCForFreescaleSemiconductor hibbertgroup com Information in this document is provided solely to enable system and software imple
75. M WRITERS write tasks and creates one read task void main task uint 32 initial data task id task id _mgx uint i fifo READ INDEX 0 fifo WRITE INDEX O0 Create semaphores if sem create component 3 1 6 MOX OK printf nCreating semaphore component failed _mgx exit 0 if sem create write ARRAY SIZE 0 MOX OK printf nCreating write semaphore failed _mgx exit 0 if sem create read 0 0 MOX OK printf nCreating read semaphore failed _mgx exit 0 if sem create index 1 0 MOX OK printf nCreating index semaphore failed _mgx exit 0 Create tasks for i 0 i NUM WRITERS i task id task create 0 WRITE TASK i printf nwrite task created id 0x 1x task id task id task create 0 READ TASK 0 printf nread task created id 0x 1x task id 3 7 5 8 4 Code for the Read Task read c include lt mgx h gt Freescale MQX Real Time Operating System User Guide Rev 3 64 Freescale Semiconductor A Using MQX include lt bsp h gt include lt sem h gt include main h TASK Task Name read_task Comments This task opens a connection to all three semaphores then waits to lock a read semaphore and an index semaphore One element in the DATA array is displayed The index and write semaphores are
76. Most from the sem family Freescale MQX Real Time Operating System User Guide Rev 3 122 Freescale Semiconductor Table 3 32 continued Specific tasks only task qualified Interrupts Context switches Tasking The sched task taskq and time families Timing The timer family certain ones from the time family Watchdogs The watchdog family For each task to log call one of klog disable logging task klog enable logging task Periodic timer interrupts system clock 3 11 3 2 Disabling Kernel Logging Using MQX Kernel logging can make your application use more resources and run slower After you have tested and verified the application you might want to create a version that does not include the ability to log to kernel log To remove kernel logging for any part of MQX you must recompile MQX with the MQX KERNEL LOGGING option set to zero For more information see Section 3 14 1 MQX Compile Time Configuration Options The complete procedure for recompiling MQX is described in Section 4 5 Rebuilding Freescale MQX RTOS 3 11 3 3 Example Using Kernel Log Log all calls to the timer component and all periodic timer interrupts klog c include mgx h include lt bsp h gt include lt log h gt include lt klog h gt extern void main_task uint_32 initial data TASK TEMPLATE STRUCT MOX template list 10 main task 2000 8 MQX
77. OG ENTRY STRUCT PTR LWLOG ENTRY STRUCT PTR The fields are described in MQX Reference 3 11 2 4 Writing to a Lightweight Log Tasks write to a lightweight log with _Iwlog_write 3 11 2 5 Reading From a Lightweight Log Tasks read from a lightweight log by calling Iwlog read and specifying how to read the log Possible ways to read the log are e To read the newest entry e To read the oldest entry To read the next entry from the previous one read used with read oldest e To read the oldest entry and delete it 3 11 2 Disabling and Enabling Writing to a Lightweight Log Any task can disable logging to a specific lightweight log with _Iwlog_disable Any task can subsequently enable logging to the lightweight log with _Iwlog_enable 3 11 2 7 Resetting a Lightweight Log A task can reset the contents of a lightweight log to its initial state of no data with _Iwlog_reset 3 11 2 8 Example Using Lightweight Logs lwlog c include mgx h include lt bsp h gt Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 119 Using MQX include lt lwlog h gt define MAIN TASK 10 define MY LOG 1 extern void main task uint 32 initial data TASK TEMPLATE STRUCT MQX template list MAIN TASK main task 2000 8 Main MOX AUTO START TASK 0 0 0 0 0 0 0 0 0 0 3 TASK
78. PU family See processor family CPU type A processor family includes CPU types For example the PowerPC family includes in part PowerPC 403 PowerPC 603 and PowerPC 750 creator The task that created a task See also child Freescale MQX Real Time Operating System User Guide Rev 3 162 Freescale Semiconductor D data cache See cache default memory pool Area within kernel memory from which MQX allocates memory when an application calls mem alloc mem alloc zero mem alloc system or mem alloc system zero An application can extend the area by calling mem extend dispatch verb When MQX dispatches a task it is in the process of examining the ready queues to determine which task it will make active MQX makes active the highest priority task that has been the longest in the ready queue See also block and schedule dynamic partition A partition that is in the default memory pool created with partition create The partition is dynamic because it can have a grow factor whereby MQX increases the partition size if all the partition blocks have been allocated See also static partition E endian format One of big endian or little endian format event group An event group lets tasks synchronize and communicate Event bits are grouped into 32 bit event groups Tasks can wait for event bits to be set they can also set and clear event bits There are fast event groups and named event groups
79. RRER RR RERO CE e dex es 84 3 8 5 Endian Conversion of Message Headers 92 ms TNI ct eb eRe doct EA FER e CU WAGE C AA 92 3 9 1 Rollover of MOX Time ssissssssssiiestonsasessestosesmssisa ies 92 192 PONE o MOX TIE na sa did prid di D RR CORR B2 di d ae 92 S90 TRS Cee 16 55 duas deb E35 dra sai adieu RO decia eda resto 92 oif HE 0 rior EEE A EEE T E A 97 ess Lue TINE ususadacefiiipixriekeddaadeqed dbeex pE R axi r 101 o d SR Rd RER DE A RDA IT ER DR ER qd TT DANS 102 23 10 Handling Interrupts and Exceptions cocos xERREER x ma rata nw RR Rx dat 105 3 10 1 Initializing Interrupt Handling cr eee ks esent aca 106 3 10 2 Installing Application Defined ISRS 107 210 2 PIQUE ON AS ids dor IX ox cdi d EORR RON o aen dede ad 107 3 10 4 Changing Default ISRS sisi eee REY REX A 110 2105 Handing ESCAPE 155075 CR eq ode ER OP CR ERR de Eee ARA Rest 111 310 6 HARINA EXOODIUPM Leurs cbse cs Cheba Ress dei 111 3 10 7 Handling Task EXOODUDEIE e icu qoede nd ee ds aa pw t di 111 3 10 8 Example Installing an ISR i i ooooeeeeoeces sh RR RR RRRERS 112 SA1 NSFUMEMA ON 42 245 ha ee os os i hs UD RR es Ap qol a Pax 113 GA A 114 LOMME LAOS rea ykp epXoth pit kb Padapiesia dnd ed 3xpRYUP poe aes 117 RES A 121 311 4 Stack Usage VIES ca tedden ab 125 Oe UNIES 22 D Re dau ed dua E dod a 125 EA A PP 125 3 12 2 Name ON 5 as ridad Ap 126 9 123 Rum Time Testi os cod GO ee doo Eco Ee RRR tint pied 127 3
80. Studio is the preferred environment for MQX development and build See the next section for steps needed to run the Hello application Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 27 Using MQX 3 3 Using Freescale CodeWarrior Development Studio This section describes the steps to use the CodeWarrior Development Studio to build run or debug your MOX application The Hello demo application for the ColdFire M52259EVB board is used for the purpose of this demonstration See also the section Section 4 5 Rebuilding Freescale MQX RTOS for more information about using CodeWarrior to rebuild the MQX operating system and other core components Use the Windows Start menu to run the CodeWarrior Development Studio 2 Using the File Open menu in CodeWarrior IDE open the Hello application project created for M52259EVB board By default you should find the project file as C Program Files Freescale Freescale MOX mqx examples hello codewarrior hello m52259evb mcp Freescale CodeWarrior File Edit View Search Project Debug MQX RTCS Tools Processor Expert Device Initialization Window Help BESSON ARANESV i BEE hello m52259evb mcp e Hell Ext MRAM Debug vD x 4 E Files Link Order Targets A Linker Files C3 Runtime Libraries MQX Libraries EX Source M hello c 12 files Figure 3 1 Locating
81. TETTE 34 20 PFO Sched iud dde sa ded dick edd xdi dob deor eode do dor dn 35 252 Mound Robin Scheduling esos guards ranira cece da dE ER 35 36 POO MEMON sar dX addu d Ro dod atte deae up lue dd dri qi dad ide od A auc ee 36 3 6 1 Managing Memory with Variable Size Blocks 36 3 6 2 Managing Lightweight Memory with Variable Size Blocks 38 3 6 3 Managing Memory with Fixed Size Blocks Partitions 39 3 6 4 Controlling Caches ox a ed citerne do di e ORE OR Rr DRE RR ERI 41 3 6 5 Controlling the MMU Virtual Memory 42 Er PIONEER AA 45 Bn GUN asa Ga cie E deed Nub AROS x btc dd 46 els Libet ESS 1 rot desee ERR RC CR Odea SEES RR A 51 3 7 3 About Semaphore Type Objects 52 3 7 4 Lightweight Semaphores secc AAA AAA 55 3 7 5 Semaphgres uiua tee die diede duh ok n dede oC RR Rods do edd e diode 59 E 7 o Pv 67 a A da 2054 Ra 3 Ere erate eee de dida dod a Sale 72 og M lt sc T TETTE 79 4H Communication Between Processors 2 di ah de dans dk oe o dd 82 3 8 1 Sending Messages to Remote Processors 83 3 8 2 Creating and Destroying Tasks on Remote Processors 84 Freescale MQX Real Time Operating System User Guide Rev 3 4 Freescale Semiconductor 3 8 3 Accessing Event Groups on Remote Processors 84 4584 Creating and MIAMI IPO ss se d co CO
82. TION STRUCT MQX init struct TEST2 ID BSP DEFAULT START OF KERNEL MEMORY BSP DEFAULT END OF KERNEL MEMORY BSP DEFAULT INTERRUPT STACK SIZE pointer MQX template list BSP DEFAULT MOX HARDWARE INTERRUPT LEVEL MAX BSP DEFAULT MAX MSGPOOLS BSP DEFAULT MAX MSGQS BSP DEFAULT IO CHANNEL BSP DEFAULT IO OPEN MODE IPC ROUTING STRUCT _ipc routing table TEST_ID TEST_ID QUEUE_TO TEST E O 505 0 7 Y IO PCB MQXA INIT STRUCT pcb mqxa init IO_PORT_NAME UVrttybi BAUD RATE 19200 IS POLLED FALSE INPUT MAX LENGTH sizeof THE MESSAGE INPUT TASK PRIORITY T OUTPUT TASK PRIORITY 7 IPC PCB INIT STRUCT pcb init IO PORT NAME pcb mqxa ittyb DEVICE INSTALL io pcb mqxa install DEVICE INSTALL PARAMETER amp pcb mqxa init IN MESSAGES MAX SIZE sizeof THE MESSAGE IN MESSAGES TO ALLOCATE 8 IN MESSAGES TO GROW 8 IN MESSAGES MAX ALLOCATE 16 OUT PCBS INITIAL 8 OUT PCBS TO GROW 8 OUT PCBS MAX 16 s IPC PROTOCOL INIT STRUCT _ipc init table ipc pcb init amp pcb init Pcb to test QUEUE TO TEST NULL NULL NULL 0 Mea NS E ae hes setae nel teed ba Re reer is e e eu ees em Freescale MQX Real Time Operating System User Guide Rev 3 90 Freescale Semiconductor Task Name responder task Comments This task creates a message queue the
83. UCT 84 debugging embedded 12 default kernel ISR 93 deinitializing mutex attributes 57 mutexes 55 57 delaying a task 81 destroying event groups 36 kernel log 100 lightweight event groups 40 lightweight logs 104 lightweight semaphores 43 logs 100 message pools private 60 mutex attributes 57 mutexes 57 semaphores 49 task queues 67 tasks 21 remotely 71 destroying partitions 28 directory structure for MQX 124 dispatch 25 DSP tasks 15 E elapsed time 82 in microseconds 83 in nanoseconds 83 resolution 83 versus absolute time 83 embedded debugging 12 endian formats converting between in memory variable size blocks 26 message data 59 80 message headers 59 79 event bits 34 clearing 36 example 36 setting 36 using 34 waiting for 36 event component 8 33 creating 35 using 34 event groups 34 accessing remotely 71 connections closing 36 opening 36 creating 35 destroying 36 example 36 setting event bits 36 using 34 waiting for event bits 36 exception handling 97 exception ISR 97 exceptions task exceptions 98 exit handler MQX getting 117 setting 117 exit handler task getting and setting 19 expiry function for watchdogs 90 extended date format 84 extending memory with variable size blocks 26 partitions static partitions 29 F floating point I O 119 floating point tasks 15 disabling and enabling 19 flushing data cache d
84. Using MQX Table 3 2 Summary Scheduling Tasks _sched_yield Moves the active task to the end of its ready queue which yields the processor to the next ready task of equal priority _task_block Blocks the task _task_get_priority Gets a task s priority _task_ready Makes a task ready _task_set_priority Sets a task s priority _task_start_preemption Re enables preemption for the task _task_stop_preemption Disables preemption for the task Each task is in one of the following logical states e Blocked task is not ready to become active because it is waiting for a condition to occur when the condition occurs the task becomes ready e Ready task is ready to become active but it is not active because it is of the same priority as or lower priority than the active task e Active task is running If the active task becomes blocked or is preemptied MQX performs a dispatch operation in which it examines the ready queues to determine which task should become active MQX makes the highest priority ready task the active task If more than one task of the same priority is ready the task at the start of that ready queue becomes the active task That is each ready queue is in FIFO order 3 5 2 1 Preemption The active task can be preemptied Preemption occurs when a higher priority task becomes ready and thus becomes the active task The previously active task is still ready but is
85. X includes code to allow time slice scheduling of tasks at the same priority MQX HAS DYNAMIC PRIORITIES Default is one One MQX includes code to change task priorities dynamically by task set priority call or by priority inheritance or priority boosting MQX HAS EXCEPTION HANDLER Default is one One MQX includes code to handle exceptions see psp lt psp gt int_xcpt c and to set get task exception handler Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 133 Using MQX routine by using the task set exception handler and task get exception handler calls MQX HAS EXIT HANDLER Default is one One MQX includes code to execute task exit handler before the task exits Also the task set exit handler and task get exit handler calls are included MQX HAS HW TICKS Default is one One MQX includes support for hardware ticks and associated calls time get hwticks time get hwticks per tick and psp usecs to ticks Note that hardware ticks also need to be supported by the BSP MQX HAS TASK ENVIRONMENT Default is one One MQX includes code to set and get task environment data pointer task set environment and task get environment MQX HAS TICK Default is one It is recommended to leave this option enabled One MQX includes support for tick time and all related functionality of delaying tasks waiting for synchronization objects with timeout etc MQX KD HAS COUNTER Default is o
86. ages Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 45 Using MQX e Task queues let an application suspend and resume tasks 3 7 1 Events Events can be used to synchronize a task with another task or with an ISR The event component consists of event groups which are groupings of event bits The number of event bits in an event group is the number of bits in mqx uint Any task can wait for event bits in an event group If the event bits are not set the task blocks Any other task or ISR can set the event bits When the event bits are set MQX puts all waiting tasks whose waiting condition is met into the task s ready queue If the event group has autoclearing event bits MQX clears the event bits as soon as they are set and makes one task ready FREESCALE MQX To optimize code and data memory requirements on some target platforms the event component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details There can be named event groups which are identified by a unique string name and fast event groups which are identified by a unique number An application can open an event group on a remote processor by specifying the processor number in the string that
87. ale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 53 Using MQX Table 3 11 Priority Inheritance Properties continued s made ready Preempties Task 3 and runs Is made ready Preempties Task 2 and runs Tries to get semaphore that Task 3 has Raises priority of Task 3 to P1 and blocks 10 11 Preempts Task 1 and runs Finishes work and posts semaphore Priority is lowered to P3 12 13 Preempts Task 3 and Task 2 and runs Gets semaphore 3 7 3 5 When you create an MQX mutex you can specify the mutex attributes of priority protection and a mutex priority These attributes prevent priority inversion If the priority of a task that requests to lock the mutex is not at least as high as the mutex priority MOX temporarily raises the task s priority to the mutex priority for as long as the task has the mutex locked Table 3 12 Mutex Attributes Avoiding Priority Inversion with Priority Protection Sequence Task 1 highest priority P1 Task 2 mid priority P2 Task 3 lowest priority P3 Runs Locks mutex with priority P1 priority is boosted to P1 s made ready Does not preempt Task 3 Freescale MQX Real Time Operating System User Guide Rev 3 54 Freescale Semiconductor Table 3 12 Mutex Attributes continued 5 s made ready 6 Does n
88. alizes a mutex mutex lock Locks a mutex mutex set priority ceiling Sets the priority of a mutex mutex test Tests the mutex component mutex try lock Tries to lock a mutex mutex unlock Unlocks a mutex Mutexes use certain structures and constants which are defined in mutex h Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 67 Using MQX 3 7 6 1 Creating the Mutex Component You can explicitly create the mutex component with mutex create component If you do not explicitly create it MQX creates it the first time an application initializes a mutex There are no parameters 3 7 6 2 Mutex Attributes A mutex can have attributes with respect to its waiting and scheduling protocols 3 7 6 3 Waiting Protocols A mutex can have one of several waiting protocols which affect tasks that request to lock an already locked mutex Waiting protocol Description Queuing Blocks until another task unlocks the mutex When the mutex is default unlocked the first task regardless of priority that requested the lock locks the mutex Priority queuing Blocks until another task unlocks the mutex When the mutex is unlocked the highest priority task that requested the lock locks the mutex Spin only Spins is timesliced indefinitely until another task unlocks the mutex This means that MQX saves the requesting task s context and dispatches the next task
89. alizes global memory Can terminate it without affecting the child tasks Yes When MQX terminates the creator it frees the creator s resources memory partitions queues and so on and stack space The resources of the child tasks are independent of the creator and are not affected Does the creator task own its child task No The only relationship between the two is that the child can get the task ID of its creator The child has its own stack space and automatic variables What are tasks and how are they created Tasks share the same code space if they execute the same root function A task always starts executing at the entry point of the root function even if the function is its creator s root function This is not the same behavior as fork in UNIX Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 159 FAQs Can move a created task to another processor No 6 13 Time Slices How does MQX measure a time slice Is the time slice absolute or relative That is if a task has a 10 ms time slice and starts at time 0 ms does it give up the processor at time 10 ms or does it give up the processor after 10 ms of execution With a 10 ms time slice MQX counts the number of periodic timer interrupts that have occurred while the task is active If the equivalent of ten or more milliseconds have expired MQX effectively runs _sched_yield for the task As a result a task doe
90. ample if the tick rate was once per nanosecond the MQX time rolls over when 584 years have passed 3 9 2 Accuracy of MQX Time MQX keeps the time internally as a 64 bit count of the number of tick interrupts but when an application requests the tick time the time also includes a 32 bit number that represents the number of hardware ticks that have occurred since the last tick interrupt Typically MQX reads this value from the hardware counter that is used to program the timer As a result the application receives the time as accurately as it can possibly be determined 3 9 3 Time Component Time is a core component that offers time as elapsed time and absolute time expressed as seconds and milliseconds second millisecond time as ticks tick time or as a date date time and extended date time Freescale MQX Real Time Operating System User Guide Rev 3 92 Freescale Semiconductor Table 3 21 Summary Using the Time Component ticks to time time add day to ticks time add hour to ticks time add min to ticks time add msec to ticks time add nsec to ticks time add psec to ticks time add sec to ticks time add usec to ticks time delay time delay for time delay ticks time delay until time dequeue time dequeue td time diff _time diff days time diff hours time diff microseconds time diff milliseconds time diff minutes time diff nanoseconds
91. an IPC_PROTOCL_INIT_STRUCT that is set up to use the standard MQX IPC over PCB device drivers ipc pcb init amp pcb init Pcb to test2 QUEUE TO TEST2 NULL NULL NULL 0 3 8 4 4 Starting IPC Task IPC task examines the IPC protocol initialization table and starts the IPC server which initializes each IPC driver The IPC server accepts messages from other processors to perform remote procedure calls The application must define IPC task as an autostart task in the MQX initialization structure for each processor The task template for IPC task is IPC TTN _ipc task IPC DEFAULT STACK SIZE 6 ipe task 0 OL 0 3 8 4 5 Example IPC Initialization Information In this example two processors set up IPC communication over an asynchronous serial port using the PCB device drivers that accompany MQX Each processor is connected by interrupt driven asynchronous character device drivers ittyb The IPC uses the PCB MQXA driver which sends and receives packets that have an MQX defined format Freescale MQX Real Time Operating System User Guide Rev 3 86 Freescale Semiconductor Using MQX The ipc_init_table uses the MQX IPC over PCB I O driver initialization function ipe pcb init and the data structure needed for its initialization pcb init which defines e The PCB I O driver name to use when opening the driver e The installation function to call in this case io pcb mqxa install needs not to be specif
92. appropriate endian format The IPC component communicates over packet control block PCB device drivers When MQX with the IPC component initializes it initializes IPC message drivers and builds message routing tables which define the paths that messages take to go from one processor to another For information that might be specific to your hardware refer to the release notes that accompany your MQX release Freescale MQX Real Time Operating System User Guide Rev 3 82 Freescale Semiconductor Using MQX Table 3 20 Summary Setting Up Inter Processor Communication ipc add ipc handler Adds an IPC handler for an MQX component ipc add io ipc handler Adds an IPC handler for an I O component ipc msg route add Adds a route to the message routing table ipc msg route remove Removes a route from the message routing table ipc pcb init Initializes an IPC for a PCB driver ipc task Task that initializes IPCs and processes remote service requests 3 8 1 Sending Messages to Remote Processors As well as having a message routing table each processor has one or more IPCs each of which consists of input function e output function output queue When a task sends a message to a message queue MQX examines the destination processor number which is part of the queue ID If the destination processor is not local MQX checks the routing table If there is a route the table indicates the outp
93. are fast An application can specify a FIFO or round robin scheduling policy when it creates the task queue 2 5 Memory Management 2 5 1 Managing Memory with Variable Size Blocks To allocate and free variable size pieces called memory blocks of memory MQX provides core services that are similar to malloc and free which most C run time libraries provide You can allocate memory blocks from memory pools that are inside and outside the default memory pool You can allocate memory blocks to a task or to the system Memory allocated to a task is a resource of the task and MQX frees the memory if the allocating task terminates 2 5 2 Managing Memory with Fixed Size Blocks Partitions Partitions are an optional component You can allocate and manage fixed size pieces called partition blocks of memory The partition component supports fast deterministic memory allocation which reduces memory fragmentation and conserves memory resources Partitions can be in the default memory pool dynamic partitions and outside it static partitions You can allocate partition blocks to a task or to the system Partition blocks allocated to a task are a resource of the task and MQX frees them if the allocating task terminates Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 17 MQX at a Glance 2 5 3 Controlling Caches MQX functions let you control the instruction cache and data cache that some CPUs have
94. area of memory that an application can optionally create and from which it can allocate memory blocks memory region Defined by a start address and an end address or by a start address and a size memory region has attributes that are defined by the hardware memory region might consist of multiple memory spaces and can be in physical memory or virtual memory memory space A part of a memory region to which MQX gives logical attributes A memory space can be in physical memory or virtual memory Examples include code space and data space MMU Memory management unit a hardware device MMU page number A part of a virtual address that is an index into an MMU page table MMU page offset The part of a virtual address that is an offset into an MMU page MMU page table Contains the base addresses of each page in physical memory The base address is combined with the MMU page offset to determine the physical address that is sent to the MMU MMU translation registers Examples include BAT TLB and TTR MQX MQX An RTOS for single processor multi processor and distributed processor embedded real time applications MQX initialization structure Defines parameters of the application and target hardware for each image MQX uses the information when it starts MQX task A task that MQX creates for its internal use MQX tasks include Idle task System task and depending on the application IPC task and Timer task In multi pro
95. ask_id Create a task queue my task queue taskq create MOX TASK QUEUE FIFO if my task queue NULL _mgx exit 0 Freescale MQX Real Time Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 81 Using MQX Create the task second task id task create 0 ISR TASK 0 if second task id MOX NULL TASK ID printf n Could not create simulated ISR taskWMn _mgx exit 0 while TRUE printf Tick n taskq suspend my task queue 3 7 8 4 2 Compiling the Application and Linking It with MOX 1 Goto this directory mqx examples taskq 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 8 Communication Between Processors With the inter processor communication IPC component tasks can do the following on remote processors exchange messages create tasks blocked or not blocked destroy tasks open and close named event groups e set event bits in named event groups All the processors need not be directly connected or be of the same type The IPC component routes messages through intermediate processors and converts them to the
96. ates an internal header with the block It also enforces a minimum size Can a task allocate a memory block for another task No Tasks allocate their own memory However a task can subsequently transfer the memory to another task If _partition_test detects a problem does it try to repair the problem No This indicates that memory is corrupted Debug the application to determine the cause When extend the default memory pool must the additional memory be contiguous with the existing end of the pool No The additional memory can be anywhere What does _mem_get_highwater return if extend the default memory pool with non contiguous memory The highwater mark is the highest memory location from which MQX has allocated a memory block have tasks on several processors that need to share memory How can provide mutual exclusion to the memory Depending on your hardware you might be able to use a spin mutex to protect the shared memory Spin mutexes call _mem_test_and_set which is multi processor safe when the hardware supports locking shared memory 6 7 Message Passing How can guarantee that target message queue IDs are associated with the correct task Create one task that uses the names database to associate each message queue number with a name Each task then gets the queue number by specifying the name Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 157
97. ble and disable an MMU and add a memory region to it MMU functions are not supported on all architectures You can control an MMU by using MMU page tables The virtual memory component lets an application control the MMU page tables The following diagram shows the relationship between virtual address MMU page tables MMU pages physical page and physical address Freescale MQX Real Time Operating System User Guide Rev 3 42 Freescale Semiconductor virtual address pi p2 d MMU page table L1 attributes addr MMU page table L2 p2 attributes physical b physical page addr physical addr Figure 3 3 Using MQX With the virtual memory component an application can manage virtual memory which maps to physical addresses An application can use the virtual memory component to create a virtual context for a task Virtual context provides memory that is private to a task and is visible only while the task is the active task The functions are called when the BSP is initialized Table 3 8 Summary Managing Virtual Memory mmu add vcontext Adds a memory region to a virtual context mmu add vregion Adds a memory region to the MMU page tables that all tasks and MQX can use mmu create vcontext Creates a virtual context for a task mmu create vtask Creates a task with an initialized
98. bsolute time you can determine where the application spends processing time and therefore which code should be optimized FREESCALE MQX To optimize code and data memory requirements on some target platforms the Log component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details With the log component you can store data into and retrieve it from a maximum of 16 logs Each log has a predetermined number of entries Each entry contains a timestamp in absolute time a sequence number and application defined data Table 3 29 Summary Using Logs Logs use certain structures and constants which are defined in og h log create Creates a log log create component Creates the log component log destroy Destroys a log log disable Disables logging log enable Enables logging log read Reads from a log log reset Resets the contents of a log log test Tests the log component log write Writes to a log 3 11 1 1 Creating the Log Component You can explicitly create the log component with log create component If you do not explicitly create it MQX creates it the first time an application creates a log or kernel log 3 11 1 2 Creating a Log To create a log a task calls log create and spe
99. can be 8 created if all the event groups are created until the maximum number is reached Maximum number If grow number is not 0 maximum number of 0 event groups that can be created unlimited 3 7 1 2 Creating an Event Group Before a task can use the event component it must create an event group Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 47 Using MQX To create this type of Call With event group Fast event create fast Index must be within the limits with autoclearing event event create fast specified when the event bits auto clear component was created Named _event_create String name with autoclearing event event create auto bits clear If an event group is created with autoclearing event bits MQX clears the bits as soon as they are set This action makes ready any tasks that are waiting for the bits without the tasks having to clear the bits 3 7 1 3 Opening a Connection to an Event Group Before a task can use the event component it must open a connection to a created event group To open a connection to this type of event Call With group Fast _event_open_fast Index which must be within the limits that were specified when the event component was created Named _event_open String name Both functions return a unique handle to the event group 3 7 1 4 Waiting for Event Bit
100. cept that they are simpler e Autoclearing event bits if an application creates an event group with the autoclearing attribute MQX automatically clears an event bit immediately after the event bit is set This behavior makes ready any tasks that are waiting for event bits but the tasks need not clear the bits Lightweight semaphores can be waited for with a timeout and polled e Task can be restarted an application can restart a task from the beginning of the task s function while keeping the same task descriptor task ID and task stack e Partitions are enhanced partitions are a fully registered MQX component An application can create and destroy them in the same manner as it can do it with other MOX components EDS Server for embedded debugging is enhanced and included in MQX as well IPC supports EDS Server so that you can debug across a multi processor MQX network e Multiprocessor events an application can set events bits from another processor in a multi processor MQX network e 32 bit queue IDs an application can represent queue IDs as 32 bit quantities in addition to 16 bit quantities As a result applications can now use queue numbers and processor numbers higher than 255 You enable the option when you compile the PSP e Faster and more compact MQX an application can use additional compile time configuration options to build a smaller MQX and use new types of components lightweight components
101. cessor applications the application includes IPC task as an autostart task in the task template list for each processor mutex A mutex provides mutually exclusive access to a shared resource Before a task accesses the resource it requests to lock the mutex that is associated with the resource If the mutex is not already locked the task locks it and continues to run If the mutex is already locked depending on the attributes of the mutex the task might wait until another task unlocks the mutex See also lightweight semaphore and semaphore N named event group An event group that is identified by a name See also fast event group named semaphore A semaphore that is identified by a name See also fast semaphore Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 167 name component Let tasks map a string name to a number non strict If a semaphore type object is non strict a task can release the object without waiting for and getting the object Lightweight semaphores are non strict mutexes are strict and semaphores can be strict or non strict normalized date Date that is defined by MQX XDATE STRUCT where each field is within its maximum limit normalized time Time that is defined by TIME STRUCT where the MILLISECONDS field is less than 1000 notification function An application provided function that MQX calls when a particular condition occurs O object Examples include m
102. cifies Log number in range of zero through 15 Maximum number of mqx uint quantities to be stored in the log this includes headers What happens when the log is full The default behavior is that no additional data is written Another behavior is that new entries overwrite the oldest ones Freescale MQX Real Time Operating System User Guide Rev 3 114 Freescale Semiconductor Using MQX 3 11 1 3 Format of a Log Entry Each log entry consists of a log header LOG_ENTRY_STRUCT followed by application defined data typedef struct mgx uint SIZE _mgx uint SEQUENCE NUMBER uint 32 SECONDS uint 16 MILLISECONDS uint 16 MICROSECONDS LOG ENTRY STRUCT _PTR_ LOG ENTRY STRUCT PTR The fields are described in MQX Reference 3 11 1 4 Writing to a Log Tasks write to a log with log write 3 11 1 5 Reading From a Log Tasks read from a log by calling log read and specifying how to read the log Possible ways to read the log are To read the newest entry e To read the oldest entry To read the next entry from the previous one read used with read oldest e To read the oldest entry and delete it 3 11 1 6 Disabling and Enabling Writing to a Log Any task can disable logging to a specific log with log disable Any task can subsequently enable logging to the log with log enable 3 11 1 7 Resetting a Log A task can reset the contents of a log to its initial state of no data with log res
103. cks Normalizes an extended date structure Called by the BSP when a periodic timer interrupt OCCUIS Sets the absolute time in second millisecond time Sets the number of hardware ticks per tick Sets the absolute time in tick time Sets the frequency of the periodic timer interrupt Sets the periodic timer interrupt vector that MQX uses Sets the frequency in ticks per second of the clock interrupt Converts ticks to an extended date since 0 00 00 000 Jan 1 1970 Converts second millisecond time to date time Converts second millisecond time to tick time Converts an extended date to ticks since 0 00 00 000 Jan 1 1970 Freescale MQX Real Time Operating System User Guide Rev 3 94 Freescale Semiconductor Using MQX 3 9 3 1 Second Millisecond Time Time is available in seconds and milliseconds To process second millisecond time is more complex and CPU intensive than processing tick time typedef struct time struct uint 32 SECONDS uint 32 MILLISECONDS TIME STRUCT PTR TIME STRUCT PTR The fields are described in MQX Reference 3 9 3 2 Tick Time Time is available in tick time To process tick time is simpler and less CPU intensive than processing second millisecond time typedef struct mqx tick struct _mqx uint TICKS MQX NUM TICK FIELDS uint 32 HW TICKS MQX TICK STRUCT _PTR_ MQX TICK STRUCT PTR The fields are described in MQX Reference 3 9 3 3 Elapsed
104. ctory For example the CodeWarrior libraries for the M52259EV B board are built into the ibvn52259evb cw directory Both BSP and PSP build projects are also set up to execute post build batch file which copies all the public header files to the destination ib directory This makes the output lib folder the only place accessed by the MQX application code The MQX application build projects do not need to make any reference to the MQX RTOS source tree at all 4 4 4 Build Targets CodeWarrior development environment enables you to have multiple build configurations called build targets All projects in the Freescale MQX RTOS contain at least two build targets e Debug target Compiler optimizations are set low to enable easy debugging Libraries built using this target are named with d postfix for example libvn52259evb cwNnqxNnqx d a Release target Compiler optimizations are set to maximum to achieve the smallest code size and fast execution The resulting code is very hard to debug Generated library name does not get any postfix for example ibvn52259evb cwNnqxNnqx a Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 145 Rebuilding MQX 4 5 Rebuilding Freescale MQX RTOS Rebuilding the MQX RTOS libraries is a simple task that involves opening the proper build projects for PSP and BSP in the development environment and building them Do not forget to select the proper build target
105. ddress When a logical address is different from its physical address it is called a virtual address virtual context A virtual context for a task is created by calling mmu create vcontext and added to by calling mmu add vcontext A task with a virtual context virtual context task is created by calling mmu create vtask A virtual context exists only while the task is the active task and can be used only by that task virtual context task A task that is created by calling mmu create vtask virtual memory component MQX functions that let an application manage virtual memory The names of the functions start with mmu and contain v Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 173 W wait When a task waits for and gets a semaphore or lightweight semaphore object it owns the object When it is finished it posts releases the object See also lock and unlock Freescale MQX Real Time Operating System User Guide Rev 3 174 Freescale Semiconductor A aborting tasks 21 absolute time 83 getting 83 setting 83 versus elapsed time 83 accuracy of MQX time 80 allocating lightweight memory blocks variable size 27 memory blocks variable size 25 messages 25 61 mutex attributes 56 mutexes 56 partition blocks 28 application queues 11 structure 112 using 111 112 autostart tasks 13 15 example 16 boot comp 131 broadcasting messages sending 60
106. deWarrior Development Studio for more details 3 7 2 Lightweight Events Lightweight events are a simpler low overhead implementation of events The lightweight event component consists of lightweight event groups which are groupings of event bits The number of event bits in a lightweight event group is the number of bits in mqx uint Any task can wait for event bits in a lightweight event group If the event bits are not set the task blocks Any other task or ISR can set the event bits When the event bits are set MQX puts all waiting tasks whose waiting condition is met into the task s ready queue If the lightweight event group has autoclearing event bits MQX clears the event bits as soon as they are set and makes one task ready Lightweight event groups are created from static data structures and are not multi processor Table 3 10 Summary Using the Lightweight Event Component Event Description _Iwevent_clear Clears the specified event bits in a lightweight event group _lwevent_create Creates a lightweight event group indicating whether it has autoclearing event bits _lwevent_destroy Destroys a lightweight event group _Iwevent_set Sets the specified event bits in a lightweight event group _lwevent_test Tests the lightweight event component _lwevent_wait_for Waits for all or any of the specified event bits in a lightweight event group for a specified tick time period _lwevent_
107. ds 82 ticks 82 time component 80 accuracy 80 rollover 80 time slice tasks 15 time slices 24 TIME STRUCT 82 timeouts 84 timer component 9 creating 85 lightweight 9 Timer Task 84 85 89 timers 9 cancelling 86 example 86 lightweight notification function 9 notification function 9 84 85 86 89 starting 86 timer component creating 85 using 84 86 U unexpected ISR 97 unified cache 29 unique numbers getting 117 unlocking mutexes 57 urgent messages sending 60 V vector table 94 virtual memory controlling 30 W wait count for event groups 34 mutexes 55 semaphores 47 waiting for event bits 36 lightweight events 39 lightweight semaphores 43 semaphores 49 waiting in message queues getting count 63 task queues 67 waiting protocols mutexes 55 watchdog component creating 90 watchdogs 10 example 91 expiry function 90 resetting 90 restarting 90 starting 90 stopping 90 using 89 watchdog component creating 90 writing lightweight logs 105 106 logs 101 102 kernel log 108 lightweight 105 106 Y yielding the processor 24 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 181 Z zero filling memory variable size blocks 26 Freescale MQX Real Time Operating System User Guide Rev 3 182 Freescale Semiconductor
108. ds on the application defined resolution that is set for the target hardware when MQX starts Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 19 MQX at a Glance 2 8 2 Lightweight Timers Lightweight timers are an optional component and provide a low overhead mechanism for calling application functions at periodic intervals Lightweight timers are installed by creating a periodic queue then adding a timer to expire at some offset from the start of the period When you add a lightweight timer to the queue you specify a notification function that will be called by the MQX tick ISR when the timer expires Since the timer runs from an ISR not all MQX functions can be called from the timer 2 8 3 Timers Timers are an optional component They provide periodic execution of an application function MOX supports one shot timers they expire once and periodic timers they expire repeatedly at a given interval You can set timers to start at a specified time or after a specified duration When you set a timer you specify the notification function that timer task calls when the timer expires The notification function can be used to synchronize tasks by sending messages setting events or using one of the other MQX synchronization mechanisms 2 8 4 Watchdogs Watchdogs are option components that let the user detect task starvation and deadlock conditions at the task level 2 9 Interrupt and Except
109. e associated with the task s context Some MQX functions update the task error code when they detect an error If an MQX function detects an error and the application ignores the error additional errors might still occur Usually the first error best indicates the problem subsequent errors might be misleading To provide a reliable opportunity to diagnose problems after MQX sets the task error code to a value other than MQX OK MQX does not further change the task error code until the task explicitly resets it to MQX OK A task can get its task error code from Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 31 Using MQX e task get error e task errno A task resets its task error code by calling task set error with MQX OK The function returns the previous task error code and sets the task error code to MQX OK Using task set error a task can attempt to set its task error code to a value other than MQX OK However only if the current task error code is MQX OK does MQX change the task error code to the new value 3 4 5 Restarting Tasks An application can restart a task by calling task restart which restarts the task at the beginning of its function with the same task descriptor task ID and task stack 3 4 6 Terminating Tasks A task can terminate itself or any other task whose task ID it knows When a task is terminated its children are not terminated When a task is
110. e cache and have not been written to memory are lost A subsequent access reloads the cache with data or instructions from physical memory Invalidating Data or Instruction Cache Table 3 6 Summary Controlling Data Caches DCACHE DISABLE Disables the data cache DCACHE ENABLE Enables the data cache _DCACHE_FLUSH Flushes the entire data cache _DCACHE_FLUSH_LINE Flushes the data cache line containing the specified address _DCACHE_FLUSH_ MLINES Flushes the data cache lines containing the specified memory region _DCACHE_INVALIDATE Invalidates the data cache _DCACHE_INVALIDATE_ Invalidates the data cache line containing the LINE specified address DCACHE INVALIDATE Invalidates the data cache lines containing the MLINES specified memory region Table 3 7 Summary Controlling Instruction Caches ICACHE DISABLE Disables the instruction cache ICACHE ENABLE Enables the instruction cache _ICACHE_INVALIDATE Invalidates the instruction cache _ICACHE_INVALIDATE_ Invalidates the instruction cache line containing the LINE specified address _ICACHE_INVALIDATE _ Invalidates the instruction cache lines containing the MLINES specified memory region 3 6 5 Controlling the MMU Virtual Memory For some CPUs you must initialize the memory management unit MMU before you enable caches MQX functions let you initialize ena
111. e find Looks up a name in the names database and gets its number name find by number Looks up a number in the names database and gets its name name test Tests the name component 3 12 2 1 Creating the Name Component An application can explicitly create the name component with name create component If you do not explicitly create it MQX creates it with default values the first time an application uses the names database The parameters and their default values are the same as for the event component which is described on page 47 3 12 3 Run Time Testing MQX provides core run time testing that tests the integrity of most MOX components A test determines whether the data that is associated with the component is valid and not corrupted MQX considers the data in a structure valid if the structure s VALID field is a known value MQX considers data in a structure corrupted if its CHECKSUM field is incorrect or pointers are incorrect An application can use run time testing during its normal operation Table 3 36 Summary Run Time Testing event test Events log test Logs lIwevent test Lightweight events _Iwlog_test Lightweight logs _lwmem_test Lightweight memory with variable size blocks _Iwsem_test Lightweight semaphores Iwtimer test Lightweight timers mem test Memory with variable size blocks msgpool test Message pools Freescale MQX Real Time Operating System User Guide Rev
112. e for a specified tick time period _lwsem_wait_ticks Waits for a lightweight semaphore for a specified number of ticks _Iwsem_wait_until Waits for a lightweight semaphore until a specified number of ticks have elapsed 3 7 4 1 Creating a Lightweight Semaphore To create a lightweight semaphore you declare a variable of type LWSEM STRUCT and initialize it by calling Iwsem create with a pointer to the variable and an initial semaphore count The semaphore count which indicates the number of requests that can be concurrently granted the lightweight semaphore is set to the initial count 3 7 4 2 Waiting for and Posting a Lightweight Semaphore A task waits for a lightweight semaphore with Iwsem wait If the semaphore count is greater than zero MQX decrements it and the task continues to run If the count is zero MQX blocks the task until some other task posts the lightweight semaphore To release a lightweight semaphore a task posts it with Iwsem post If no tasks are waiting for the lightweight semaphore MQX increments the semaphore count Since lightweight semaphores are non strict tasks can post without waiting first therefore the semaphore count is not bounded and can increase beyond the initial count 3 7 4 3 Destroying a Lightweight Semaphore When a task no longer needs a lightweight semaphore it can destroy it with Iwsem destroy 3 7 4 4 Example Producers and Consumer Producer and consumer
113. e is 0x2000 single addressable units Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 25 Using MQX hello task The hello task task is a time slice task with a time slice of 100 in milliseconds if the default compile time configuration options are used For information about these options see page 132 Freescale MQX Real Time Operating System User Guide Rev 3 26 Freescale Semiconductor Float_task The Float task task is both a floating point task and an autostart task 3 2 2 5 Example Creating an Autostart Task A single task prints Hello World and terminates hello c include lt mgx h gt include lt fio h gt Task IDs define HELLO TASK 5 extern void hello task uint 32 TASK TEMPLATE STRUCT MOX template list HELLO TASK hello task 500 5 hello MOX AUTO START TASK OL 0 1 30 9 0 0 0 0 OL 0 0 y void hello task uint 32 initial data printf in Hello World An _mgx exit 0 3 2 2 5 1 Compiling the Application and Linking it with MOX 1 Goto this directory mqx examples hello Using MQX 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note The following appears on the output device Hello World FREESCALE MQX With Freescale MQX the CodeWarrior Development
114. e size of the compiled image and MQX runs slower You can use profiling only if the toolset that you are using supports profiling MQX RUN TIME ERR CHECK ENABLE Default is zero One Code to support an external run time error checking tool is compiled into MQX This adds to the size of the compiled image and MQX runs slower You can use run time error checking only if the toolset that you are using supports it MQX ROM VECTORS Default is zero One The interrupt vector table is not copied into RAM The ROM based table is set up correctly to handle all interrupts by the default MQX interrupt dispatcher The application will still be able to install interrupt service routine by using the int install isr call However the int install kernel isr call can not be used to install the low level interrupt service routines directly in the vector table MQX SPARSE ISR TABLE Default is zero One The MQX interrupt service routine table is allocated as an array of linked lists instead of linear array This option is independent on the MOX ROM VECTORS as it deals with the logical table managed by the interrupt dispatcher in MQX With the sparse ISR table only the ISRs installed by the int install isr call consume RAM memory Interrupt latency increases as the MQX needs to walk the list to find user ISR to be invoked MQX SPARSE ISR SHIFT Default is 3 When MQX SPARSE ISR TABLE is defined as 1 this MOX SPARSE ISR SHIFT option determines
115. efinition of 29 formatted I O 10 freeing messages 61 partition blocks fixed size 28 G get nsec c 131 132 get usec c 131 132 H handling exceptions 97 hardware interrupts disabling and enabling 94 highwater mark in memory with fixed size blocks 29 variable size blocks 26 I O 10 I O subsystem 10 Idle Task 13 117 135 init bsp c 131 135 initdev c 133 initializing Freescale MQX Real Time Operating System User Guide Rev 3 176 Freescale Semiconductor application queues 112 ISR table 94 MQX 6 13 mutex attributes 57 mutexes 56 installing application ISR default 94 ISR default 97 ISRs application 94 execption 97 kernel ISR default 94 periodic timer ISR 83 unexpected ISR default 94 interrupt stack usage getting 111 interrupts and exceptions 10 11 93 application ISRs installing 94 changing default ISRs 97 exception handling 97 ISR exception handling 97 ISR table initializing 94 kernel ISR 93 default 93 invalidating data or instruction cache definition of 30 IPC component 9 creating 72 endian conversion message data 80 message headers 79 event groups accessing remoting 71 example 4 processors 71 messages between processors exchanging 70 protocol initialization table 72 building 73 structure 73 routing table 70 72 building 72 structure 72 tasks creating remotely 71 tasks destroying remotely 71 IPC routing table structure
116. ement to the end of a queue by calling _queue_enqueue with pointers to the queue and to queue element object which is the header structure of the object that the task wants to queue 3 12 1 4 Removing Elements From a Queue A task gets and removes an element from the start of a queue by calling _queue_dequeue with a pointer to the queue 3 12 2 Name Component With the name component tasks can associate a 32 bit number with a string or symbolic name MQX stores the association in a names database that all tasks on the processor can use The database avoids global variables FREESCALE MQX To optimize code and data memory requirements on some target platforms the Name component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details Freescale MQX Real Time Operating System User Guide Rev 3 126 Freescale Semiconductor Using MQX Table 3 35 Summary Using the Name Component The name component uses certain structures and constants which are defined in name h name add Adds a name to the names database a name is a NULL terminated string max length 32 characters including NULL name create component Creates the name component name delete Deletes a name from the names database nam
117. en switching to the task with the defined priority considering the value of the MOX HARDWARE INTERRUPT LEVEL MAX This table is valid for ColdFire platforms only As an example when Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 109 Using MQX MQX HARDWARE INTERRUPT LEVEL MAX is set to 7 switching to the task with the priority of 4 causes the SR register is loaded by the value of 2 It means that this task can not be interrupted by the interrupts with the priority lower that 3 MQX HARDWARE INTERRUPT LEVEL MAX Table 3 26 SR Register Values for Different Task Priorities and Different Values of MQX HARDWARE INTERRUPT TaskiEriority LEVEL_MAX A 3 E F E a NOT ALLOWED EFFECTIVELLY CHANGES TO MQX HARDWARE INTERRUPT LEVEL MAX 1 1 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 3 2 1 0 0 0 0 0 4 3 2 1 0 0 0 0 5 4 3 2 1 0 0 0 6 5 4 3 2 1 0 0 7 6 5 4 3 2 1 0 A NOT ALLOWED EFFECTIVELLY CHANGES TO MQX_HARDWARE_INTERRUPT_LEVEL_MAX 7 3 10 4 Changing Default ISRs When MQX handles an interrupt it calls _int_kernel_isr which calls a default ISR with the interrupt number if either of these conditions is true The application has not installed an application defined ISR for the interrupt number e The interrupt number is outside the range of the ISR table The application can get a pointer to the default ISR with i
118. ent and waits After all bits have been set Tick is printed and the event is cleared void service task uint 32 initial data pointer event ptr task id second task id setup event if event create global MOX OK printf nMake event failed _mgx exit 0 if event open global amp event ptr MOX OK printf nOpen event failed _mgx exit 0 create task second task id task create 0 ISR TASK 0 if second task id MOX NULL TASK ID printf Could not create simulated ISR task In _mgx exit 0 while TRUE if event wait all event ptr 0x01 0 MOX OK printf NnEvent Wait failed _mgx exit 0 if event clear event ptr 0x01 MOX OK printf nEvent Clear Failed _mgx exit 0 printf Tick An Freescale MQX Real Time Operating System User Guide Rev 3 50 Freescale Semiconductor Using MQX 3 7 1 9 2 Compiling the Application and Linking it with MOX 1 Goto this directory mqx examples event 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note Event task prints a message each time an event bit is set FREESCALE MQX_ With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale Co
119. ent create component event create fast event create fast auto clear event destroy event destroy fast event wait all family event wait any family Lightweight events _Iwevent_destroy _Iwevent_test _lwevent_wait family Lightweight logs _Iwlog_create_component Lightweight semaphores _Iwsem_test _Iwsem_wait Logs _log_create_component Messages msg create component msgq receive family Mutexes mutex create component mutex lock Names name add name create component name delete Partitions partition create component Semaphores sem close _sem_create _sem_create_component _sem_create_fast _sem_destroy _sem_destroy_fast sem post for strict semaphores only sem wait family Task queues taskq create taskq destroy taskq suspend taskq suspend task taskq test Timers timer create component Watchdogs watchdog create component Freescale MQX Real Time Operating System User Guide Rev 3 108 Freescale Semiconductor Using MQX 3 10 3 2 Functions That ISRs Should Not Call ISRs should not call MQX functions that might block or take a long time to run These include e most functions from the io family e event wait family e jnt default isr e int unexpected isr e klog display klog show stack usage e l wevent wait family e wsem wait family e msgq receive family e mutatr set wait protoco
120. ere are named semaphores and fast semaphores See also lightweight semaphore and mutex semaphore type objects Include lightweight semaphores semaphores and mutexes single addressable unit The smallest quantity in bits that a CPU can address Traditionally it has been eight bits or one byte however some CPUs and DSPs define it to be up to 32 bits space See memory space spin only If a spin only mutex is already locked when a task requests to lock it MQX effectively timeslices the task until the mutex is unlocked See also limited spin static partition A partition that is outside the default memory pool created with partition create at The partition is static because it cannot have a grow factor which means that MQX does not increase the partition size if all the partition blocks have been allocated The application must explicitly extend the partition See also dynamic partition strict If a semaphore type object is strict a task must first wait for and get the object before it can release the object Lightweight semaphores are non strict mutexes are strict and semaphores can be strict or non strict system Usually used to include the application and all its target hardware System resource A resource that an application task allocates but does not own MQX does not free the resource when the task is terminated Examples of system resources include system memory blocks system message pools system message que
121. es code to support multi processor MQX applications MQX KERNEL LOGGING Default is one One Certain functions in each component write to kernel log when they are entered and as they exit The setting reduces performance only if you enable logging for the component You can control which component is logged with _klog_control MQX LWLOG TIME STAMP IN TICKS Default is one One Timestamp in lightweight logs is in ticks Zero Timestamp is in seconds milliseconds and microseconds MQX MEMORY FREE LIST SORTED Default is one One MQX sorts the freelist of memory blocks by address This reduces memory fragmentation but increases the time MQX takes to free memory MQX MONITOR STACK Default is one One MQX initializes all task and interrupt stacks to a known value so that MQX components and debuggers can calculate how much stack is used The setting reduces performance only when MQX creates a task You must set the option to one in order to make use of _klog_get interrupt stack usage klog get task stack usage klog show stack usage MQX MUTEX HAS POLLING Default is one One MQX includes code to support the mutex options MUTEX SPIN ONLY and MUTEX LIMITED SPIN Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 135 Using MQX MQX_PROFILING ENABLE Default is zero One Code to support an external profiling tool is compiled into MQX Profiling adds to th
122. es tasks that are waiting for the semaphore and destroys the semaphore after all the tasks that have the semaphore post the semaphore If destruction is not forced MQX destroys the semaphore after the last waiting task gets and posts the semaphore This is always the action if the semaphore is strict 3 7 5 8 Example Task Synchronization and Mutual Exclusion This example builds on the lightweight semaphore example on page 56 It shows how semaphores can be used for task synchronization and mutual exclusion The example manages a FIFO that multiple tasks can write to and read from Mutual exclusion is required for access to the FIFO data structure Task synchronization is required to block the writing tasks when the FIFO is full and to block the reading tasks when the FIFO is empty Three semaphores are used e Index semaphore for mutual exclusion on the FIFO Read semaphore to synchronize the readers Write semaphore to synchronize the writers The example consists of three tasks Main Read and Write Main initializes the semaphores and creates Read and Write 3 7 5 8 1 Definitions and Structures for the Example main h This file contains definitions for the semaphore example define MAIN TASK 5 define WRITE TASK 6 Freescale MQX Real Time Operating System User Guide Rev 3 62 Freescale Semiconductor define READ TASK 7 define ARRAY SIZE 5 define NUM WRITERS 2 Global data structure acces
123. escale Semiconductor 95 Using MQX Initially absolute time is the time since the reference date of 0 00 00 000 January 1 1970 An application can change the absolute time by changing the reference date in second millisecond time with time set or in tick time with time set ticks A task gets the absolute time in second millisecond time with time get or in tick time with time get ticks Unless an application changes the absolute time the following pairs of functions return the same values e time get and time get elapsed time get ticks and time get elapsed ticks CAUTION A task should use elapsed time to measure an interval or implement a timer This prevents the measurement from being affected by other tasks that might call time set or time set ticks and thereby change the absolute time 3 9 3 6 Time in Date Formats To help you set and interpret absolute time that is expressed in second millisecond time or tick time the time component offers time expressed in a date format and an extended date format 3 9 3 6 1 DATE STRUCT typedef struct date struct uint 16 YEAR uint 16 MONTH uint 16 DAY uint 16 HOUR uint 16 MINUTE uint 16 SECOND uint 16 MILLISEC DATE STRUCT PTR DATE STRUCT PTR The fields are described in MQX Reference 3 9 3 6 2 MQX XDATE STRUCT This structure represents a date in a format that is more detailed than DATE STRUCT You can convert between
124. escale Semiconductor 99 p E Using MQX _timer_id id pointer data_ptr MOX TICK STRUCT PTR tick ptr printf OFF n JETRGKES See es cinco cd x rtc rene et dae cuu end Rie teens e Task Name main_task Comments This task creates two timers each of a period of 2 seconds the second timer offset by 1 second from the first XK AX xo void main task uint 32 initial data MOX TICK STRUCT ticks MOX TICK STRUCT dticks timer id on timer timer id off timer Create the timer component with more stack than the default in order to handle printf requirements _timer create component TIMER DEFAULT TASK PRIORITY 1024 time init ticks amp dticks 0 time add sec to ticks amp dticks 2 time get ticks amp ticks time add sec to ticks amp ticks 1 on timer timer start periodic at ticks LED on O0 TIMER ELAPSED TIME MODE amp ticks amp dticks time add sec to ticks amp ticks 1 off timer timer start periodic at ticks LED off 0 TIMER ELAPSED TIME MODE amp ticks amp dticks _time delay ticks 600 printf NnThe task is finished timer cancel on timer timer cancel off timer _mgx exit 0 Freescale MQX Real Time Operating System User Guide Rev 3 100 Freescale Semiconductor Using MQX 3 9 4 4 2 Compiling the Application and Linking It with MOX 1 Goto this directory mqx examples timer 2 Refer to your MQX Release Notes document for
125. esolution delays timeouts and measurements MQX measures time in ticks instead of in seconds and milliseconds Delays for a specified time or until a specified time are possible The change applies to all components that use a timeout The internal changes are transparent In addition MQX adds an extended date structure that represents a calendar date well beyond the 94 century and to an accuracy of a picosecond MMU support is included in PSPs MMU support allows memory protection between tasks Each task can establish its own protected data areas Multiple memory pools applications can allocate memory blocks from an application defined global memory space as well as they could before from the default memory pool The pools are similar to MQX version 2 40 partitions but let the user allocate variable sized blocks Freescale MQX Real Time Operating System User Guide Rev 3 12 Freescale Semiconductor Before You Begin Lightweight memory similar to the memory component except that MQX does fewer checks when it allocates blocks and the code and data sizes are smaller Lightweight memory is faster to allocate and free memory but slower to release memory when a task is destroyed e Blocked tasks can be created applications can create tasks that are in the blocked state MOX creates the task as in MQX version 2 40 but does not add it to the ready queue Lightweight event groups similar to event groups ex
126. essor two using queue ten and then from processor two to processor three using queue 20 When the IPC on processor three receives the message MQX directs the message to the destination target message queue 3 8 2 Creating and Destroying Tasks on Remote Processors With IPC component a task can create and destroy tasks on a remote processor by sending service requests to IPC task on that processor IPC task runs the request and responds to the requesting processor 3 8 3 Accessing Event Groups on Remote Processors With the IPC component a task can open and close a named event group on a remote processor and set event bits in the event group However a task cannot wait for event bits on a remote processor Event groups are opened on remote processors by specifying the processor number followed by a colon in the name of the event The following example would open the event Fred on processor number four event open 4 fred amp handle 3 8 4 Creating and Initializing IPC For tasks to communicate across processors the application must create and initialize the IPC component on each processor as summarized in the following steps Each step is described in subsequent sections using information from the routing table previous example 1 Build the IPC routing table 2 Build the IPC protocol initialization table 3 Provide IPC protocol initialization functions and data 4 Create IPC task ipe task 3 8 4 1 Building an IP
127. et 3 11 1 8 Example Using Logs log c include mgx h include lt bsp h gt include lt log h gt define MAIN TASK 10 define MY LOG 1 extern void main task uint 32 initial data TASK TEMPLATE STRUCT MOX template list MAIN TASK main task 2000 8 Main MQX AUTO START TASK 0 0 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 115 Using MQX 0 0 0 0 0 0 0 0 3 typedef struct entry struct LOG ENTRY STRUCT HEADER _mgx uint C _mgx uint I ENTRY STRUCT PTR ENTRY STRUCT PTR TASK 00 Sie siii less eee ee See Ee seh be sos eee ki ieee Task Name main_task Comments This task logs 10 keystroke entries then prints out the log void main_task uint_32 initial_data ENTRY_STRUCT entry _mgx uint result _mgx uint 3 uchar Gu Create the log component result log create component if result MOX OK printf Main task log create component failed _mqx exit 0 Create a log result log create MY LOG 10 sizeof ENTRY STRUCT sizeof mgx uint 0 if result MOX OK printf Main task log create failed _mgx exit 0 Write data into the log printf Please type in 10 characters Mn for i 0 i lt 10 i c getchar result log write MY LOG 2 mqx uint c i if result MOX OK printf Main task log write failed
128. ffort needed to modify BSP source files for a new board Table 5 1 Effort in Modifying BSP Source Files Effort if porting to the Effort if porting to a Effort if porting to a File dame microprocessor similar processor within different processor p the same sub family same code and PSP bsp h medium medium high init hw c bsp init c medium medium high bsp prv h medium medium high bsp rev h low low low enet ini c low medium high Freescale MQX Real Time Operating System User Guide Rev 3 150 Freescale Semiconductor Developing a New BSP get_usec c low low low gpio_init c medium high high init_bsp c medium high high init_ lt driver_name gt c low low low board name h low medium high max init c low low low vectors c low medium medium Compiler specific code low low low cw c Linker configuration low medium high cw Icf Debugger configuration low medium high cw dbg mem cfg PSP processor files low high high 5 5 1 bsp_prv h The file contains e Prototypes for private functions that the BSP uses e Prototypes for device initialization structures for devices in the BSP in source io 5 5 2 bsp h The file includes include statements for files the applications can use to access board resources and device driver API It also declares prototypes of public BSP functions exported to be used by applications or by IO drivers e g
129. g _Iwtimer_create_periodic_queue with a pointer to a variable of type LWTIMER PERIOD STRUCT which specifies the queue s period in ticks It then adds a timer to the queue by calling Iwtimer add timer to queue with the address of the periodic queue variable and a pointer to a variable of type LWTIMER STRUCT which specifies the function that is called when the timer expires Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 101 Using MQX When the timer expires the notification function specified by the timer runs CAUTION Because the notification function runs in the context of the kernel timer ISR it is subject to the same restrictions as the ISR see page 107 The MQX interrupt stack size should include the stack space that the notification function needs 3 9 5 2 Cancelling Outstanding Lightweight Timer Requests A task can cancel an outstanding lightweight timer request by calling Iwtimer cancel timer with the address of the L WTIMER STRUCT A task can cancel all the timers on a lightweight timer queue by calling Iwtimer cancel period with the address of the L WTIMER PERIOD STRUCT 3 9 6 Watchdogs Most embedded systems have a hardware watchdog timer If the application does not reset the timer within a certain time perhaps because of deadlock or some other error condition the hardware generates a reset operation As such a hardware watchdog timer monitor
130. g Source Code This section describes key BSP files which needs to be modified when supporting a different board or processor 5 7 1 init_bsp c The file contains e Initialization function that is specific to the board bsp enable card e Periodic timer ISR bsp timer isr e MQX exit handler bsp exit handler e Support for hardware tick time if available bsp get hwticks e Initialize hardware watchdog if available bsp setup watchdog 5 7 1 1 bsp enable card Part way through initialization MQX calls the function to do the following Initialize processor support facilities A PSP can provide facilities for managing CPU resources such as CPU based memory or baud rate generators Initialize interrupt support The function psp int init creates and installs the MQX interrupt table Initialize cache and MMU and optionally enable them The PSP provides support functions for CPUs that have caches and MMUs e Install and initialize the periodic timer ISR e Install I O device drivers and initialize the I O subsystem This code uses conditional compilation to install selected I O drivers only See lt board gt h for drivers enabled by default The settings can be changed in the user config h or directly in the lt board gt h file 5 7 1 2 bsp timer isr This function is the interrupt service routine for the periodic timer interrupt It clears the interrupt and if required restarts the timer It ca
131. gement Dynamic task management Core Scheduling Round robin and FIFO Core Explicit using task queues Optional Task synchronization and Lightweight semaphores Core eee Semaphores Optional Lightweight events Optional Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor MQX at a Glance Table 2 1 Core and Optional Components continued Events Optional Mutexes Optional Messages Optional Task queues Optional Interprocessor Optional communication Timing Time component Optional BSP Lightweight timers Optional Timers Optional Watchdogs Optional Memory management Memory with variable size blocks Core Memory with fixed size blocks Optional partitions MMU cache and virtual memory Optional Lightweight memory Optional Interrupt handling Optional BSP I O drivers I O subsystem Optional BSP Formatted 1 0 Optional BSP Instrumentation Stack usage Core Kernel log Optional Logs Optional Lightweight logs Optional Error handling Task error codes exception handling Core runtime testing Queue manipulation Core Name component Optional Embedded debugging EDS Server Optional 2 2 Initialization is a core component The application starts when _max runs The function initializes the hardware and starts MQX When MQX starts it creates tasks that the application defines as auto
132. gnificant byte contains the queue number bit position 15 8 7 0 queue ID processor number queue number 3 7 7 5 2 32 Bit Queue IDs The most significant word of a 32 bit queue ID contains the processor number and the least significant word contains the queue number bit position 31 16 15 0 queue ID processor number queue number 3 7 7 6 Using Private Message Queues to Receive Messages A task can send a message to any private message queue but only the task that opened a private message queue can receive messages from it Only one task at a time can have the private message queue open A task opens a private message queue msgq open by specifying its queue number which is a value between eight and the maximum queue number that is specified in the MQX initialization structure Queue numbers of one through seven are reserved If a task calls msgq open with queue number zero MQX opens any of the task s unopened private message queues Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 75 Using MQX The task that opened a private message queue can close it with msgq close which removes all messages from the message queue and frees the messages A task receives a message from one of its private message queues with a function from the msgq receive family which removes the first message in the specified queue and returns a pointer to the
133. h different characteristics The function msgpool create returns a pool ID which any task can use to access the private message pool System message pool Private message pool Create a message pool msgpool create system msgpool create Allocate a message msg alloc system msg alloc MQX searches all MQX searches only the system message pools specified private message pool Free a message msg free msg free message owner only Destroy a message pool A system message pool cannot msgpool destroy be destroyed By any task with the pool ID after all messages in the pool are freed 3 7 7 3 Allocating and Freeing Messages Before a task sends a message it allocates a message msg alloc system or msg alloc of the appropriate size from a system or private message pool System message pools are not the resource of any task and any task can allocate a message from them Any task with the pool ID can allocate a message from a private message pool When a task allocates a message from either type of pool the message becomes the resource of the task until the task frees the message msg free or puts it in a message queue msgq send family of functions When a task gets a message from a message queue msgq poll or msgq receive family the message becomes the resource of the task Only the task that has the message as its resource can free the message Message
134. he default values and overrides others CAUTION For MQX host tools to work properly the MQX initialization structure variable must be called MQX init struct 5 8 Creating Default Initialization for I O Drivers A number of initialization files might be needed to provide default information when I O drivers are installed with _bsp_enable_card 5 8 1 init dev c The init dev c files where dev is the name of a device driver which provides default initialization structure and other information needed to install specific I O drivers Freescale MQX Real Time Operating System User Guide Rev 3 154 Freescale Semiconductor Chapter 6 FAQs 6 1 General My application stopped How do tell if MQX is still running If the time is being updated MQX is processing the periodic timer interrupt If Idle task is running MOX is running 6 2 Events Two tasks use an event group The connection works for one task but not for the other Why The tasks are probably sharing the same global connection rather than having their own local individual connection Each task should call event open or event open fast to get its own connection 6 3 Global Constructors need to initialize some global constructors which use the new operator before I call main that is before start MQX The new operator calls malloc which redefine to call the MQX function mem alloc How do do t
135. he include search paths to the new configuration directory redirect the output library path to the new output directory optionally change the name of the output library file being built clone the batch files in the buila bat directory and select them in the project settings as a new post linker action 7 In the all files change all occurrences uppercase and lowercase of the name of the old BSP or processor to the name of the new BSP processor 5 4 Editing the Debugger Configuration Files The board specific configuration files are stored with the BSP sources in the dbg subdirectory and they are copied into the output lib folder by the post linker batch The BSP project itself makes no other use of the debugger configuration files It is the application project built with a particular BSP which refers to the debugger files in its project You might need to modify debugger initialization files such as cfg or mem to support the new board Typical changes needed in the debugger initialization file include external memory setup external bus signals timing memory area location etc TIP Use the debugger configuration files for evaluation boards based on the same processor device coming with the debugger tool as an example 5 5 Modifying BSP Specific Include Files BSP specific include files are in mqx source bsp lt board gt where lt board gt is the BSP name The following table shows the e
136. hin the limits that were specified when the semaphore component was created Named _sem_create String name When the task creates the semaphore it also specifies Initial count the initial value for the semaphore count represents the number of locks that the semaphore has A task can get multiple locks Priority queuing if priority queuing is specified the queue of tasks waiting for the semaphore is in priority order and MQX puts the semaphore to the highest priority waiting task If priority queuing is not specified the queue is in FIFO order and MQX puts the semaphore to the longest waiting task Priority inheritance if priority inheritance is specified and a higher priority task is waiting for the semaphore MQX raises the priority of the tasks that have the semaphore to the priority of the waiting task For more information see the discussion on priority inheritance on page 53 To use priority inheritance the semaphore must be strict Strictness if strictness is specified a task must wait for the semaphore before it can post the semaphore If a semaphore is strict the initial count is the maximum value of the semaphore count If the semaphore is non strict the count is unbounded 3 7 5 4 Opening a Connection to a Semaphore Before a task can use a semaphore it must open a connection to the semaphore Semaphore Type Call With Fast _sem_open_fast Index which must be within the
137. his Initialize the constructors from bsp enable card in init bsp c which MQX calls after it initializes the memory management component 6 4 Idle Task What happens if Idle task blocks because of an exception If Idle task blocks System task which is really a system task descriptor that has no code becomes the active task System task descriptor sets up the interrupt stack then re enables interrupts As a result the application can continue to run Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 155 FAQs 6 5 Interrupts An interrupt comes at periodic intervals that my application must respond to very quickly quicker than MQX allows What can do Call int install kernel isr to replace the kernel ISR int kernel isr Your replacement ISR must e Save all registers on entry and restore them on exit t must not call any MQX functions e Pass information to other tasks if required by an application implemented mechanism usually ring buffers with head and tail pointers and total size fields My application consists of several tasks that should run only when a certain signal comes in by an interrupt How can my ISR that handles the interrupt communicate to the appropriate tasks If the target hardware allows it set the priority of the interrupt to be higher than what MQX uses when it disables interrupts see the MOX HARDWARE INTERRUPT LEVEL MAX field in
138. ications The main features are its scalable size component oriented architecture and ease of use MQX supports multi processor applications and can be used with flexible embedded I O products for networking data communications and file management Throughout this book we use MQX as the abbreviation for MQX 1 2 About This Book Use this book in conjunction with e MQX Reference contains MQX simple and complex data types and alphabetically ordered listings of MQX function prototypes FREESCALE MQX Freescale MQX release includes also other software products based on MQX operating system See also user guides and reference manuals for RTCS TCP IP stack USB Host Development Kit USB Device Development Kit MFS File System and others Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 11 Before You Begin 1 3 What s New in Versions 3 0 and 2 50 FREESCALE MQX To continue version numbering of the original MQX releases the first Freescale MQX version is released as 3 0 Despite of the major version number change there are no major features added to MQX so it is compatible with the version 2 50 See also the Release Notes document for the most up to date information about new features available in the Freescale MQX RTOS MQX version 3 0 released as Freescale MQX RTOS brings the following enahancements over version 2 50 Other key MQX componen
139. ied if the PCB I O driver was previously installed e The PCB I O driver specific initialization pcb mqxa init 3 8 4 5 1 IPC Initialization Information ipc ex h define TEST_ID 1 define IPC TTN 9 define MAIN TTN 10 define QUEUE TO TEST2 63 Hdefine MAIN QUEUE 64 define TEST2 ID 2 define RESPONDER TTN 11 define QUEUE TO TEST 67 define RESPONDER QUEUE 65 typedef struct the message MESSAGE HEADER STRUCT HEADER uint 32 DATA THE MESSAGE PTR THE MESSAGE PTR 3 8 4 5 2 Code for Processor One ipci c include mgx h include lt bsp h gt include lt message h gt include lt ipc h gt include lt ipc_pcb h gt include io pcb h gt include pcb mqxa h gt include ipc ex h extern void main task uint 32 TASK TEMPLATE STRUCT MOX template list IPC TTN _ipc task IPC DEFAULT STACK SIZE 6 ipc task MOX AUTO START TASK 0 0 MAIN TTN main task 2000 8 Main MOX AUTO START TASK 0 0 0 0 0 0 0 0 0 0 MOX INITIALIZATION STRUCT MOX init struct TEST_ID Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 87 Using MQX BSP DEFAULT START OF KERNEL MEMORY BSP DEFAULT END OF KERNEL MEMORY BSP DEFAULT INTERRUPT STACK SIZE pointer MQX template list BSP DEFAULT MOX HARDWARE INTERRUPT LEVEL MAX BSP DEFAULT MAX MSGPOOLS BSP DEFAULT MAX MSGOS BSP DEFAULT IO CHANNEL BSP DE
140. ime Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 129 Using MQX d if Create the message component Verify the integrity of message pools and message queues msg create component MOX OK printf nError creating the message component _mgx exit 9 msgpool test amp error ptr amp error2 ptr MOX OK printf nFailed msgpool test _mgx exit 10 msgq test amp error ptr amp error2 ptr MOX OK printf nFailed msgq test _mgx exit 11 mutex test amp error ptr MOX OK printf nFailed mutex test _mgx exit 12 name test amp error ptr amp error2 ptr MOX OK printf nFailed name test _mgx exit 13 partition test amp partition amp error ptr amp error2 ptr MQX OK printf nFailed partition test _mgx exit 14 sem test amp error ptr MOX OK printf nFailed sem test _mgx exit 15 taskq test amp error ptr amp error2 ptr MOX OK printf nFailed takq test mgx exit 16 timer test amp error ptr MOX OK printf nFailed timer test _mgx exit 17 watchdog test amp error ptr amp error2 ptr MOX OK printf nFailed watchlog test _mgx exit 18 printf All tests passed mgx exit 0 3 12 3 1 1 Compiling the Application and Linking It with MQX 1 Go to this directory mqx examples test Freescale MQX Real Time
141. instructions on how to build and run the application 3 Run the application according to the instructions in the release note A message is printed each time the timer notification function runs FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 9 5 Lightweight Timers Lightweight timers are an optional component that extends the core time component Lightweight timers provide periodic notification to the application A task can create a periodic queue and add timers to it The timers expire at the same rate as the queue s period but offset from the period s expiry time Table 3 23 Summary Using Lightweight Timers Lightweight timers use certain structures and constants which are defined in wtimer h Iwtimer add timer to Adds a lightweight timer to a periodic queue queue Iwtimer cancel period Removes all the timers from a periodic queue Iwtimer cancel timer Removes a timer from a periodic queue Iwtimer create periodic Creates a periodic queue with a period of a specified queue number of ticks to which lightweight timers can be added _Iwtimer_test Tests all the periodic queues and their timers 3 9 5 1 Starting Lightweight Timers A task starts a lightweight timer by first creating a periodic queue by callin
142. ints World RENDA void world task uint 32 initial data task id hello task id hello task id task create 0 HELLO TASK 0 if hello task id MQX NULL TASK ID printf An Could not create hello taskWMn Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 33 Using MQX else printf World n _mgx exit 0 XTASKK Task Name hello task Comments This task prints Hello RENA void hello task uint 32 initial data printf Hello n _task block 3 4 7 2 Compiling the Application and Linking it with MQX 1 Goto this directory mqx examples hello2 2 Refer to your MQX Release Notes document for instructions on how to build and run the application 3 Run the application according to the instructions in the release note The following appears on the output device Hello World FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see the Section 3 3 Using Freescale CodeWarrior Development Studio for more details 3 5 Scheduling Tasks MQX provides these task scheduling policies e FIFO e Round robin Explicit using task queues described in a subsequent section on page 79 You can set the scheduling policy to FIFO or round robin for the processor and separately for each task As ares
143. ion Handling Interrupt and exception handling is optional at the PSP level MQX services all hardware interrupts within arange that the BSP defines and saves a minimum context for the active task MQX supports fully nested interrupts 1f the CPU supports nested interrupts Once inside an interrupt service routine ISR an application can re enable any interrupt level To further reduce interrupt latencies MQX defers task rescheduling until after all ISRs have run In addition MQX reschedules only if a new task has been made ready by an ISR To reduce stack size MQX supports a separate interrupt stack An ISR is not a task it is a small high speed routine that reacts quickly to hardware interrupts An ISR is usually written in C language Its duties include resetting the device getting its data and signaling the appropriate task An ISR can be used to signal a task with any of the non blocking MQX functions 2 10 I O Drivers I O drivers are an optional component at the BSP level They consist of formatted I O and the I O subsystem I O drivers are not described in this book 2 10 1 Formatted I O MQX provides a library of formatted I O functions that is the API to the I O subsystem Freescale MQX Real Time Operating System User Guide Rev 3 20 Freescale Semiconductor MQX at a Glance 2 10 2 1 0 Subsystem You can dynamically install I O device drivers after which any task can open them 2 11 Instrumentation 2 11 1 Logs
144. ite task 600 5 write 0 OL O READ TASK read task 500 5 read MOX AUTO START TASK OL 0 fo 0 0 0 O 0 OL 0 3 7 4 4 3 Code for a Write Task write c include lt mgx h gt include lt bsp h gt include read h TASK Task Name write task Comments This task waits for the write semaphore Freescale MQX Real Time Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 57 Using MQX then writes a character to data and posts a read semaphore END void write task uint 32 initial data printf nWrite task created 0x 1X initial data while TRUE if lwsem wait amp fifo WRITE SEM MOX OK printf n lwsem wait failed _mgx exit 0 fifo DATA uchar initial data lwsem post amp fifo READ SEM 3 7 4 4 4 Code for Read Task read c include lt mgx h gt include lt bsp h gt include read h SW_FIFO fifo TASK Task Name read task Comments This task creates two semaphores and NUM WRITER write tasks Then it waits on the read sem and finally outputs the data variable void read task uint 32 initial data _task_id task id _mgx uint result _mgx uint i Create the lightweight
145. itialization MQX creates one instance of each task whose template defines it as an autostart task In addition while an application is running it can create other tasks using a task template that either the task template list defines or the application defines dynamically The end of the task template list is a zero filled task template typedef struct task template struct _mgx_uint TASK TEMPLATE INDEX void CODE PTR_ TASK ADDRESS uint 32 mem size TASK STACKSIZE _mgx_uint TASK PRIORITY char _PTR_ TASK NAME _mgx_uint TASK ATTRIBUTES uint 32 CREATION PARAMETER _mgx_uint DEFAULT TIME SLICE TASK TEMPLATE STRUCT _PTR_ TASK TEMPLATE STRUCT PTR For a description of each field see MOX Reference Freescale MQX Real Time Operating System User Guide Rev 3 24 Freescale Semiconductor Using MQX 3 2 2 1 Assigning Task Priorities CAUTION If you assign priority zero to a task the task runs with interrupts disabled On some target processor platforms e g ColdFire certain task priority levels are reserved and are mapped to processor interrupt priority levels Tasks running at such a special priority may prevent lower priority interrupts to be serviced See more details about interrupt handling in section 3 10 Handling Interrupts and Exceptions When you assign task priorities in the task template list note that e MQX creates one ready queue for each priority up to the lowest prior
146. ity highest number While an application is running it cannot create a task that has a lower priority a higher number than the lowest priority task in the task template list 3 2 2 2 Assigning Task Attributes You can assign any combination of the following attributes to a task e Autostart when MQX starts it creates one instance of the task e DSP MQX saves the DSP co processor registers as part of the task s context e Floating point MQX saves floating point registers as part of the task s context Time slice MQX uses round robin scheduling for the task the default is FIFO scheduling 3 2 2 3 Default Task Template List You can initialize your own task template list or use the default which is called MQX template list 3 2 2 4 Example A Task Template List TASK TEMPLATE STRUCT MOX template list MAIN TASK world task 0x2000 5 world task MQX AUTO START TASK OL 0 HELLO hello task 0x2000 5 hello task MOX TIME SLICE TASK OL 100 FLOAT float task 0x2000 5 Float task MQX AUTO START TASK MQX FLOATING POINT TASK OL O 0 0 0 0 0 0 OL 0 world_task The world_task is an autostart task So at initialization MQX creates one instance of the task with a creation parameter of zero The application defines the task template index MAIN_ TASK The task is of priority five The function world_task is the code entry point for the task The stack siz
147. ize various I O drivers in a way suitable for a given board This code compiles together with the I O drivers code into the BSP library 4 3 4 l O Subdirectories Subdirectories in the mgx source io contain source code for MQX I O drivers Typically source files in each I O driver directory are further split to device specific and device independent The I O drivers suitable for given board are part of the BSP build project and are compiled into the BSP library 4 3 5 Other Source Subdirectories All other directories in the source contain generic parts of the MQX RTOS Together with the platform dependent PSP code the generic sources are compiled into the PSP library 4 4 Freescale MQX Build Projects All necessary build projects are located in the mgx build lt compiler gt directory For each board there are two build projects available PSP and BSP The BSP project contains board specific code while PSP is platform specific for example ColdFire only The PSP project does not contain any board specific code Despite this both projects refer to the board name in their file names and both also generate the binary output file into the same board specific directory lib lt board gt lt compiler gt The board independent PSP library is also compiled to board specific output directory because the compile time configuration file is taken from board specific directory config lt board gt In other words even if the PSP source code it
148. l e mutex lock e partition create component e task block e fask create and task create blocked e task destroy e time delay family e timer start family 3 10 3 3 Non Maskable Interrupts Non Maskable Interrupts NMI are defined as interrupts that cannot be disabled masked by software It is possible to use such interrupts in MQX applications but NMI service routines must be installed directly to vector table as kernel ISRs use _int_install_kernel_isr instead of _int_install_isr The NMI service routines are not allowed to call any MQX API function Note that _int_install_kernel_isr call is only enabled if the vector table is located in RAM memory see MQX ROM VECTORS configuration option in section 3 14 Configuring MQX at Compile Time 3 10 3 4 MQX HARDWARE INTERRUPT LEVEL MAX Configuration Parameter On some processor platforms an internal concept of disabling all interrupt levels may be re configured in a way that only interrupt levels up to the MOX HARDWARE INTERRUPT LEVEL MAX field in the MOX INITIALIZATION STRUCT are disabled This effectively enables critical interrupt requests above that maximum level to be serviced asynchronously to MQX kernel execution and with minimum possible latency From the MQX perspective such an interrupt is considerred a non maskable interrupt and the same restrictions as for NMI apply The following Table 3 26 summarizes values written into the SR register wh
149. l execute when no other tasks are ready otherwise the processor will stop when there are no tasks to run MQX USE INLINE MACROS Default is one One Some internal functions that MQX calls are changed from function calls to in line code The setting optimizes MQX for speed Zero MQX is optimized for code size MQXKX USE IO Default is one One the MQX implements the I O subsystem calls needed by I O drivers Without the I O subsystem no driver can be installed or used and tasks are not able to use stdin stdout stderr handles MQX USE LWMEM ALLOCATOR Default is zero One Calls to the mem family of functions are replaced with calls to the corresponding function in the _lwmem family 3 14 2 Recommended Settings The settings you choose for compile time configuration options depend on the requirements of your application FREESCALE MQX The MQX build process and its compile time configuration is specific for given target board set in config lt board gt user_config h directory You may want to create your own configurations specific to the custom board or even the application Please see more details about this process in Section 4 6 Creating Custom MQX Configurations and Build Projects The following table shows common settings you can use as you develop your application Table 3 38 Compile time Configuration Setting Option Default Debug Speed Size MQX_ALLOW_TYPED_MEMORY 1 1 0 0 1
150. limits that were specified when the semaphore component was created Named _sem_open String name Both functions return a unique handle to the semaphore 3 7 5 5 Waiting for a Semaphore and Posting a Semaphore A task waits for a semaphore using one of the functions from the _sem_wait_ family of functions If the semaphore count is zero MQX blocks the task until another task posts _sem_post the semaphore or the task specified timeout expires If the count is not zero MQX decrements the count and the task continues to run Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 61 Using MQX When a task posts a semaphore and there are tasks waiting for the semaphore MQX puts them in their ready queues If there are no tasks waiting MQX increments the semaphore count In either case the posting task remains ready 3 7 5 6 Closing a Connection to a Semaphore When a task no longer needs to use a semaphore it can close its connection with the semaphore with sem close 3 7 5 7 Destroying a Semaphore When the semaphore is no longer needed a task can destroy it Semaphore Type Call With Fast sem destroy fast Index which must be within the limits that were specified when the semaphore component was created Named sem destroy String name As well the task can specify whether to force destruction If destruction is forced MQX readi
151. ll the tasks that are waiting for the semaphore Two tasks use a semaphore The connection works for one task but not for the other Why The tasks are probably sharing the same global connection rather than having their own local individual connection Each task should call sem open or sem open fast to get its own connection Freescale MQX Real Time Operating System User Guide Rev 3 158 Freescale Semiconductor FAQs 6 10 Task Exit Handler Versus Task Exception Handler What is the difference between the two MQX calls the task exit handler when a task calls _task_abort or when a task returns from its task body If MQX exception handling is installed MQX calls the task exception handler if the task causes an exception that is not supported 6 11 Task Queues My application puts several tasks of the same priority in a priority task queue How are they ordered Tasks are in FIFO order within a priority 6 12 Tasks Do always need at least one autostart task Yes In an application at least one autostart application task is required in order to start the application In a multi processor application the application can create tasks remotely each image need not have an autostart application task however each image must include IPC task as an autostart task in the task template list If no application task is created on a processor Idle task runs One autostart task creates all my other tasks and initi
152. lls time notify kernel so that MQX knows that the interrupt occurred The bsp timer isr handler services also the hardware watchdog counter if this is available 5 7 1 3 bsp exit handler This function is called when an application calls mqx exit It shuts down the devices that are no longer used Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 153 Developing a New BSP 5 7 2 get_usec c 5 7 2 1 time get microseconds This function returns the number of microseconds since the last periodic timer interrupt If itis not possible to determine the time since the last periodic timer interrupt the function should return zero Modify the function only if you are using a different timer in which case call its timer get usec function 5 7 3 get nsec c 5 7 3 1 time get nanoseconds The function returns the time in nanoseconds since the last periodic timer interrupt If it is not possible to determine the time since the last periodic timer interrupt the function returns zero Modify the function only if you are using a different timer In this case callits timer get nsec function 5 7 4 mqx init c This file contains the board s default MQX initialization structure so that simple applications or applications that use default values defined in farget h need not define an initialization structure An application can create a new MQX initialization structure that uses some of t
153. lo_task template to create an instance of hello_task If task create is successful it returns the task ID of the new child task otherwise it returns MQX NULL TASK ID The new hello task task is put in the ready queue for the task s priority Since it has a higher priority than world task it becomes active The active task prints Hello The world task task then becomes active and checks to see whether hello task was created successfully If it was world task prints World otherwise world task prints an error message Finally MQX exits If you change the priority of world task to be of the same priority as hello task the output is World only The world task runs before hello task because world task has the same priority and does not relinquish control with a blocking function Since world task calls mqx exit after printing World nothing else can be printed because hello task does not have the opportunity to run again 3 4 7 1 Code for the Example hello2 c include lt mgx h gt include fio h Task IDs define HELLO TASK 5 define WORLD TASK 6 extern void hello task uint 32 extern void world task uint 32 TASK TEMPLATE STRUCT MQX template list WORLD TASK world task 500 5 world MQX AUTO START TASK OL O HELLO TASK hello task 500 4 hello 0 OL 0 o o 0 0 0 0 OL 0 XTASKK Task Name world task Comments Ed This task creates hello task and then pr
154. locate messages from message pools Tasks send messages to message queues and receive messages from message queues Messages can be assigned a priority or marked urgent Tasks can send broadcast messages FREESCALE MQX To optimize code and data memory requirements on some target platforms the Message component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details Table 3 18 Summary Using Messages Messages use certain structure definitions and constants which are defined in message h msg alloc Allocates a message from a private message pool msg alloc system Allocates a message from a system message pool msg available Gets the number of free messages in a message pool msg create component Creates the message component msg free Frees a message msg swap endian data Converts the application defined data in a message to the other endian format msg swap endian header Converts the message header to the other endian format msgpool create Creates a private message pool msgpool create system Creates a system message pool msgpool destroy Destroys a private message pool msgpool test Tests all message pools
155. locked the task locks it and continues to run If the task is already locked the task does not get the mutex but continues to run 3 7 6 7 Unlocking a Mutex Only the task that has locked a mutex can unlock it mutex unlock 3 7 6 8 Destroying a Mutex If a mutex is no longer needed a task can destroy it with mutex destroy If any tasks are waiting for the mutex MQX puts them in their ready queues 3 7 6 9 Example Using a Mutex A mutex is used for mutual exclusion There are two time slice tasks both of which print to the same device A mutex prevents the output from being interleaved 3 7 6 9 1 Code for the Example main c include mgx h include lt bsp h gt include lt mutex h gt Task IDs define MAIN TASK 5 define PRINT TASK 6 extern void main_task uint_32 initial data extern void print task uint 32 initial data TASK TEMPLATE STRUCT MOX template list Freescale MQX Real Time Operating System User Guide Rev 3 70 Freescale Semiconductor MAIN TASK main_task 600 5 main MOX AUTO START TASK OL 0 PRINT TASK print task 600 6 print MOX TIME SLICE TASK OL 3 o 0 O 05 0 0 OL 0 MUTEX STRUCT print mutex J TASK L222cclsscllilsucene jubcnidgeecades03 ececoBl 5 exe Task Name main task Comments This task creates a mutex and then two instances of the print task void main task uint 32 initial data MUTEX
156. lopers write compile and link with MQX If the application runs on only one processor it consists of one image If it runs on multiple processors it consists of multiple images application queue A queue that an application initializes and uses through the queue component See also message queue ready queue task queue and timeout queue application task A task that an application developer writes and at the application s instruction that MQX creates and starts See also autostart task and MOX task autoclearing event bits If a task creates an event group with autoclearing event bits MQX clears the bits as soon as they have been set If the event group does not have autoclearing event bits it is the responsibility of the application to clear the bits autostart task If the task template in the task template list defines a task as an autostart task MQX creates an instance of the task when MQX starts B BAT Block address translation an MMU translation register big endian The most significant byte is the first byte in the word See also little endian block verb When the active task blocks MQX removes it from the ready queue and makes another task active See also dispatch board Also called a single board computer A board can have multiple processors Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 161 BSP Board support package A group of files that are specific to a
157. m wait ticks Waits for a semaphore for a number of ticks sem wait until Waits for a semaphore until a time in tick time 1 Semaphores use certain structures and constants which are defined in sem h 3 7 5 1 Using a Semaphore To use a semaphore a task executes the following steps each of which is described in subsequent sections 1 Optionally creates the semaphore component Creates the semaphore Opens a connection to the semaphore If the semaphore is strict it waits for the semaphore When finished using the semaphore for the time being it posts the semaphore If it no longer needs the semaphore it closes its connection to the semaphore LIO ROI If the semaphore is protecting a shared resource that ceases to exist or is no longer accessible the task can destroy the semaphore 3 7 5 2 Creating the Semaphore Component You can explicitly create the semaphore component with sem create component If you do not explicitly create it MQX creates it with default values the first time an application creates a semaphore The parameters and their default values are the same as for the event component which is described on page 47 Freescale MQX Real Time Operating System User Guide Rev 3 60 Freescale Semiconductor Using MQX 3 7 5 3 Creating a Semaphore Before a task can use a semaphore it must create the semaphore Semaphore Type Call With Fast sem create fast Index which must be wit
158. me slice for the processor is usually 50 milliseconds You can change the default time slice for the processor with sched set rr interval or sched set rr interval ticks passing the task ID parameter as MQX DEFAULT TASK ID When the time slice expires for an active round robin task MQX saves the task s context MQX then performs a dispatch operation in which it examines the ready queues to determine which task should become active MQX moves the expired task to the end of the task s ready queue an action that causes control to pass to the next task in the ready queue If there are no other tasks in the ready queue the expired task continues to run With round robin scheduling tasks of the same priority can share the processor in a time equitable manner Table 3 1 Summary Getting and Setting Scheduling Info sched get max priority Gets the highest priority allowed for any task always returns zero sched get min priority Gets the lowest priority for any task Ssched get policy Gets the scheduling policy sched get rr interval Gets the time slice in milliseconds Sched get rr interval ticks Gets the time slice in tick time sched set policy Sets the scheduling policy Sched set rr interval Sets the time slice in milliseconds sched set rr interval ticks Sets the time slice in tick time Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 35
159. menters to use Freescale Semiconductor products There are no express or implied copyright licenses granted hereunder to design or fabricate any integrated circuits or integrated circuits based on the information in this document Freescale Semiconductor reserves the right to make changes without further notice to any products herein Freescale Semiconductor makes no warranty representation or guarantee regarding the suitability of its products for any particular purpose nor does Freescale Semiconductor assume any liability arising out of the application or use of any product or circuit and specifically disclaims any and all liability including without limitation consequential or incidental damages Typical parameters that may be provided in Freescale Semiconductor data sheets and or specifications can and do vary in different applications and actual performance may vary over time All operating parameters including Typicals must be validated for each customer application by customer s technical experts Freescale Semiconductor does not convey any license under its patent rights nor the rights of others Freescale Semiconductor products are not designed intended or authorized for use as components in systems intended for surgical implant into the body or other applications intended to support or sustain life or for any other application in which the failure of the Freescale Semiconductor product could create a situation where pers
160. message If the task specifies queue ID zero it receives a message from any of its open message queues Receiving a message from a private message queue is a blocking action unless the task specifies a timeout which is the maximum time the task will wait for a message 3 7 7 7 Using System Message Queues to Receive Messages System message queues are not owned by a task and a task does not block waiting to receive a message from one Since it is not possible to block waiting for a message in a system message queue ISRs can use system message queues A task or ISR opens a system message queue with msgq open system A task or ISR receives messages from a system message queue with msgq poll If there are no messages in the system message queue the function returns NULL 3 7 7 8 Determining the Number of Pending Messages A task can determine how many messages are in a system message queue or in one of its private message queues with msgq get count 3 7 7 9 Notification Functions With both system and private message queues a task can specify a notification function that runs when a message is sent to the queue For system message queues the task specifies the notification function when it opens the queue For private message queues the task sets the notification function with msgq set notification function after it opens the queue Applications can use notification functions to couple another synchronization service such as an eve
161. mmu add vregion BSP PCI MEMORY BASE BSP PCI MEMORY BASE BSP PCI MEMORY SIZE PSP MMU DATA CACHE PSP MMU CACHE INHIBITED mmu add vregion BSP PCI IO BASE BSP PCI IO BASE BSP PCI IO SIZE PSP MMU DATA CACHE PSP MMU CACHE INHIBITED mmu add vregion BSP DIMM BASE BSP DIMM BASE BSP DIMM SIZE PSP MMU DATA CACHE PSP MMU CACHE INHIBITED mmu add vregion BSP RAM BASE BSP RAM BASE BSP COMMON RAM SIZE PSP MMU DATA CACHE PSP MMU CACHE INHIBITED mmu venable _ICACHE_ENABLE 0 _DCACHE ENABLE 0 3 6 5 2 Example Setting Up a Virtual Context Set the active task to access 64 KB of private memory at 0xA0000000 pointer virtual mem ptr uint 32 size virtual mem ptr pointer 0xA0000000 size 0x10000L result mmu create vcontext MOX NULL TASK ID if result MOX OK result mmu add vcontext MOX NULL TASK ID Freescale MQX Real Time Operating System User Guide Rev 3 44 Freescale Semiconductor Using MQX virtual mem ptr size 0 if result MQX OK 3 6 5 3 Example Creating Tasks with a Virtual Context Create tasks with a virtual context and a copy of common data Task template number for the virtual context task define VMEM_TTN 10 Global variable uchar ptr data to duplicate 0x10000 0x1 0x2 0x3 pointer virtual_mem ptr virtual_mem_ptr pointer 0xA0000000 result mmu create vtask VMEM TTN 0 amp data to duplicate virtual
162. mplate index of zero In this case MQX interprets the task creation parameter as a pointer to a task template The functions initialize the child s stack The function task create puts the child in the ready queue for the task s priority If the child is of higher priority than the creator the child becomes the active task because it is the highest priority ready task If the creator is of higher or equal priority it remains the active task The function task create blocked creates a task that is blocked The task is not ready to run until another task calls task ready 3 4 2 Getting Task IDs A task can directly get its task ID with task get id If a function takes a task ID as a parameter you can specify MQX NULL TASK ID to refer to the task ID of the active task A task can directly get the task ID of its creator with task get creator The function task create returns the child s task ID to the creator A task ID can also be determined from the task name in the task template from which the task was created This is done with task get id from name which returns the task ID of the first task that matches the name in the task template list 3 4 3 Setting a Task Environment A task can save an application specific environment pointer with task set environment Other tasks can access the environment pointer with task get environment 3 4 4 Managing Task Errors Each task has an error code the task error cod
163. mutex locked See also priority inheritance priority queuing MQx grants the semaphore or mutex to the highest priority task that is waiting for the semaphore or mutex Within a priority tasks are queued in FIFO order private resource A resource that an application task owns because either the task allocated the resource as a non system resource or because another task transferred or effectively transferred ownership of the resource MQX frees the resource when the task is terminated Private resources include memory blocks messages message pools message queues and partition blocks See also system resource processor The physical CPU device on which the image runs It is identified by its processor number See also board CPU type processor family PSP and SBC Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 169 processor family Examples of processor families are ARCtangent MC68060 and PowerPC Within a family are CPU types Also called CPU family See also PSP processor number Application unique number that the application assigns in the MQX initialization structure for each image processor type See CPU type program See application PSP Processor Support Package A group of files that are specific to a CPU type See also BSP Q queue ID Application unique MQX generated number that identifies a message queue It is a combination of the queue number and processor n
164. n 158 6 10 Task Exit Handler Versus Task Exception Handler 158 AL 1755 50 POTETE N AAA 159 AE M PTT 159 EIS ICD EDS A deque Equus dad ade abu Beebe esa oa es 160 Freescale MQX Real Time Operating System User Guide Rev 3 6 Freescale Semiconductor ir ERES uus abandonnant ot oon an d near aba SCR cec ide dant ananas de 160 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 7 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor Revision History To provide the most up to date information the revision of our documents on the World Wide Web will be the most current Your printed copy may be an earlier revision To verify you have the latest information available refer to http www freescale com mqx The following revision history table summarizes changes contained in this document Revision Revision e Numb zt Boe Description of Changes Rev 0 01 2009 Initial Release coming with MQX 3 0 Rev 0B 04 2009 Text edited and formatting changed for MQX 3 1 release New MQX compile time configuration options described in Section 3 14 BSP Rev 1 01 2010 S L porting instructions updated in Chapters 4 and 5 Section 3 6 5 updated AS Tol due Section 3 10 3 3 added Interrupt level taks priorities described in section 3 2 2 1 Rev 2 09 2010 NMI handling text edited in section 3 10 3 3 Section 3 14 upda
165. n waits for a message Upon receiving the message the data is incremented before the message is returned to the sender void responder task uint 32 dummy 3 8 4 5 4 THE MESSAGE PTR msg ptr queue id qid queue id my qid puts Receiver running n my gid msgq open RESPONDER QUEUE 0 while TRUE msg ptr msgq receive MSGQ ANY QUEUE 0 if msg ptr NULL qid msg_ptr gt HEADER SOURCE_QID msg ptr gt HEADER SOURCE QID my qid msg_ptr gt HEADER TARGET_QID qid msg_ptr gt DATA putchar msgq send msg ptr else puts RESPONDER RECEIVE ERROR n mgx exit 1 Compiling the Application and Linking It with MQX Using MQX 1 Refer to your MQX Release Notes document for instructions on how to build and run the application 2 Goto this directory to compile for processor one mqx examples ipc cpul 3 Build the project 4 Goto this directory to compile for processor two mqx examples ipc cpu2 5 Build the project 6 Connect ttyb of processor one to ttyb of processor two 7 Run the applications according to the instructions in the release notes Start processor two before processor one FREESCALE MQX With Freescale MQX the CodeWarrior Development Studio is the preferred environment for MQX development and build Please see Section 3 3 Using Freescale CodeWarrior Development Studio for more details Freescale MQX Real Time Operating Sys
166. nce 3 2 Initializing and Starting MQX MQX is started with mqx which takes the MQX initialization structure as its argument Based on the values in the structure MQX does the following e It sets up and initializes the data that MQX uses internally including the default memory pool ready queues the interrupt stack and task stacks e It initializes the hardware for example chip selects e It enables timers e It sets the default time slice value e It creates the Idle task which will be active if no other task is ready e It creates tasks that the task template list defines as autostart tasks e It starts scheduling the tasks 3 2 1 MQX Initialization Structure The MQX initialization structure defines parameters of the application and target hardware typedef struct mgx initialization struct _mqx uint PROCESSOR_NUMBER pointer START OF KERNEL MEMORY pointer END OF KERNEL MEMORY _mgx uint INTERRUPT STACK SIZE TASK TEMPLATE STRUCT PTR TASK TEMPLATE LIST _mgx uint MQX HARDWARE INTERRUPT LEVEL MAX _mgx uint MAX MSGPOOLS mgx uint MAX MSGQS char PTR_ IO CHANNEL char _PTR_ IO OPEN MODE _mqx uint RESERVED 2 MQX INITIALIZATION STRUCT _PTR_ MQX INITIALIZATION STRUCT PTR Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 23 Using MQX For a description of each field see MQX Reference 3 2 1 1 Default MQX Initialization Structure
167. ne One The MQX kernel maintains the counter value which is automatically increamented any time the value is queried by the mqx get counter call MQX TD HAS PARENT Default is one One The MQX task descriptors maintain the task s creator ID which is available through task get creator call MQX TD HAS TEMPLATE INDEX Default is one One The MQX task descriptors maintain the original index value coming from the TASK TEMPLATE STRUCT array This value is maintained for backward compatiblity only and is not used by MQX kernel MQX TD HAS TASK TEMPLATE PTR Default is one One The MQX task descriptors maintain the pointer to original TASK TEMPLATE STRUCT structure used for task creation This pointer is used by task restart call task restart and by several lookup functions like task get id from name MQX TD HAS ERROR CODE Default is one One The MQX task descriptors maintain the error code which is accessible with task set error and Freescale MQX Real Time Operating System User Guide Rev 3 134 Freescale Semiconductor Using MQX _task_get_error calls MQX TD HAS STACK LIMIT Default is one One The MQX task descriptors maintain the task limit value which is needed by various stack overflow checking calls like task check stack MQX INCLUDE FLOATING POINT IO Default is zero One io printf and io scanf include floating point I O code MQX IS MULTI PROCESSOR Default is one One MQX includ
168. ning Existing Configuration uu sssaeekeerr kae ERR YR RR ER 146 Chapter 5 Developing a New BSP Bd MIE MEN riberas added bit etudes 149 SE AI Sona Aa ke RAO ROR Per 149 53 Selecting A Baselne BSP ciar EO o OR Po nd CIRCE ER OR E 149 5 4 Editing the Debugger Configuration Files 150 55 Modifying BSP Specific Include Files c lt cinozisosiariass sopa ese 150 Sal PPPT PRI 151 A Ecc cer 151 DOM DONA Li bia dich dott dur lacs dabo ed ede lt le paced ge dad id 151 5 6 Modifying Startup Code oa 6 A ra de RR AERE ELD ERE GEN E AOI CU DR dE dor por RA 152 561 SOUL and MDI ss me d hx Ek ane Oe e idee EAS d 152 5 7 Modifying Source Code oc ccc esae RR ERR RUE RR RE ROEA EORR Rec RR Rea 153 Sol A AAA be Ree REAM ETS AER a Woe 153 Oe DEL UBOGO ii AIR ttr E Y OO OR de 9 AR AAA AA Rh edo 154 nra UI ts bh Ree OE AG SC PACA EAE ol deir cea 154 2 ADEM uu Hs Len de Re CRE ardid iia dd 154 5 8 Creating Default Initialization for I O Drivers 154 BAI MUN o od twee RUN dE UNES Ec ae ddud adidceg ded Pu Sra aped 154 Chapter 6 FAQs RC AAA 155 O2 EONS au de AER A A ak 155 63 Global so oa cod adco e qoo d edd Oe dedi A et de id 155 Eu CE SE he Ro A dee US del MI E dep d ode Ri OS 155 ES MEND tartar iic cupio d dHER Rodeo beaded E 156 OO ROMO tis cies eo eee ee ee ee ee hee Baas 156 67 Message PO iddaduacg ced a oti eh dent de ds desde and dc t EA 157 A CMT 158 ED ABIDE a oh Gai Kol D EORR RERO I
169. no longer the active task Preemption occurs when an interrupt handler causes a higher priority task to become ready or the active task makes a higher priority task ready 3 6 Managing Memory 3 6 1 Managing Memory with Variable Size Blocks By default MQX allocates memory blocks from its default memory pool Tasks can also create memory pools outside the default memory pool and allocate memory blocks from them Both allocation processes are similar to using malloc and free which are in most C run time libraries NOTE You cannot use a memory block as a message You must allocate messages from message pools see page 72 A memory block can be a private memory block a resource owned by the task that allocates it or a system memory block not owned by any task When a task is terminated MQX returns the task s private memory blocks to memory Freescale MQX Real Time Operating System User Guide Rev 3 36 Freescale Semiconductor Using MQX When MQX allocates a memory block it allocates a block of at least the requested size the block might be larger A task can transfer ownership of a memory block to another task _mem_transfer Table 3 3 Summary Managing Memory with Variable Size Blocks mem alloc Allocates a private memory block from the default memory pool mem alloc from Allocates a private memory block from the specified memory pool mem alloc zero Allocates a ze
170. nt C3 fio C2 include E a jo VO Drivers source code build to BSP library C3 kernel CQ Hog Rest of the MOX generic sources build to PSP library O log O lwevent O lwlog C3 lwmem O lwmsa O lwtimer CD message a mutex O name Co part O profile Ce psp PSP sources the platform specific part of PSP library O coldfire CD queue O sem Rest of the MOX generic sources build to PSP library DB string B timer C3 watchdog CodeWarrior project files to build PSP and BSP libraries Figure 4 2 MQX RTOS Directory Structure 4 3 2 PSP Subdirectories The mgx source psp directory contains the platform dependent code of the PSP library For example the ColdFire subdirectory contains the MQX kernel parts specific to the Freescale ColdFire architecture for example core initialization register save restore code for interrupt handling stack handling cache Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 143 Rebuilding MQX control functions and so on In addition this directory also contains processor definition files for each supported processor derivative 4 3 3 BSP Subdirectories The subdirectories in mgx source bsp typically follow the name of the board and contain low level startup code processor and board initialization code The BSP also contains data structures used to initial
171. nt get default isr The application can change the default ISR as described in the following table Default ISR Description Modify or install with int default isr int exception isr int unexpected isr MQX installs it as the default To modify ISR when MQX starts Itblocks int install default the task isr To install int install exception isr Implements MQX exception handling Similar to int default isr To install but also prints a message tothe int install unexpected _ default console identifying the isr unhandled interrupt Freescale MQX Real Time Operating System User Guide Rev 3 110 Freescale Semiconductor Using MQX 3 10 5 Handling Exceptions To implement MQX exception handling an application should call int install exception isr which installs int exception isr as the default ISR Thus int exception isr is called when an exception or unhandled interrupt occurs The function int exception isr does the following when an exception occurs e If the exception occurs when a task is running and a task exception ISR exists MQX runs the ISR if a task exception ISR does not exist MQX aborts the task by calling _task_abort e If the exception occurs when an ISR is running and an ISR exception ISR exists MQX aborts the running ISR and runs the ISR s exception ISR The function walks the interrupt stack looking for information abo
172. nt or semaphore to a message queue 3 7 7 10 Example Client Server Model This client server model shows communication and task synchronization using message passing Server task blocks waiting for a request message from Client task When Server receives the request it executes the request and returns the message to Client Two way message exchange is used in order to block Client while Server runs Server opens an input message queue that it will use to receive requests from Client tasks and creates a message pool from which it allocates request messages Server then creates a number of Client tasks In a real application the Client tasks most likely would not be created by Server When Server has opened its message queue and created its message pool it enters a loop receiving messages from the message queue acting on them in this case printing the data and returning the message to Client Client also opens a message queue It allocates a message from the message pool fills in the message field sends the message to Server and waits for a response from Server Freescale MQX Real Time Operating System User Guide Rev 3 76 Freescale Semiconductor Using MQX 3 7 7 10 1 Message Definition server h include mgx h include lt message h gt Number of clients define NUM CLIENTS 3 Task IDs define SERVER TASK 5 define CLIENT TASK 6 Queue IDs define SERVER QUEUE 8 define CLIENT
173. on blocks in a partition this is a highwater mark that indicates the maximum number that have been allocated simultaneously not necessarily the number that are currently allocated partition get total blocks Gets the number of partition blocks in a partition partition get total size Gets the size of a partition including extensions partition test Tests the partition component partition transfer Transfers ownership of a partition block to another task including the system only the new owner can free the partition block 3 6 4 Controlling Caches MQX functions let you control the instruction cache and data cache that some CPUs have Using MQX So that you can write an application that applies to both cached and non cached systems MQX wraps the functions in macros For CPUs that do not have the cache the macros do not map to a function Some CPUs implement a unified cache one cache is used for both data and code in which case the _DCACHE_ and ICACHE macros map to the same function 3 6 4 1 Flushing Data Cache MQX uses the term flush to mean flushing the entire data cache Unwritten data that is in the cache is written to physical memory Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 41 Using MQX 3 6 4 2 MQX uses the term invalidate to mean invalidating all the cache entries Data or instructions that are left in th
174. onal injury or death may occur Should Buyer purchase or use Freescale Semiconductor products for any such unintended or unauthorized application Buyer shall indemnify and hold Freescale Semiconductor and its officers employees subsidiaries affiliates and distributors harmless against all claims costs damages and expenses and reasonable attorney fees arising out of directly or indirectly any claim of personal injury or death associated with such unintended or unauthorized use even if such claim alleges that Freescale Semiconductor was negligent regarding the design or manufacture of the part e 2 freescale semiconductor Freescale and the Freescale logo are trademarks of Freescale Semiconductor Inc All other product or service names are the property of their respective owners 1994 2008 ARC International All rights reserved Freescale Semiconductor Inc 2009 All rights reserved Document Number MQXUG Rev 3 04 2011 Chapter 1 Before You Begin 13 SOIR aer ze ua Jtoen ps ded dectediadesa dau dt lb audd credits 11 T2 ABM TNS BOOK ARA ST 11 1 3 Whale New in Versions S D and 2 50 aussi cide kx 3 1d 9a do OCA RO de dod 12 UE COMON spa ons hehe T1213 RAS 14 FA a ea ed tee tn ER LS CN Fe REET ed tes 14 TAZ NOIRS ania acd ae sede deeded deb ded aed beet E Cen dd do dde cir dei E 14 JE SONS unm 14 Chapter 2 MQX at a Glance ME co e AAA 15 ze AAA IN 16 23 Task MOBIC criar rar ARANA A 17 ns ened
175. ot preempt Task 3 7 Finishes with mutex and unlocks it 8 Priority is lowered to P3 9 Preempts Task 3 and runs 10 Locks mutex Table 3 13 Comparison of Lightweight Semaphores Semaphores and Mutexes Feature LWSem Semaphore Mutex Timeout Yes Yes No Queuing FIFO FIFO FIFO Priority Priority Spin only Limited spin Strict No No or yes Yes Priority No Yes Yes inheritance Priority No No Yes protection Size Smallest Largest Between lightweight semaphores and semaphores Speed Fastest Slowest Between lightweight semaphores and semaphores Lightweight Semaphores Lightweight semaphores are a simpler low overhead implementation of semaphores Lightweight semaphores are created from static data structures and are not multi processor Table 3 14 Summary Using Lightweight Semaphores Iwsem create Creates a lightweight semaphore Iwsem destroy Destroys a lightweight semaphore Iwsem poll Polls for a lightweight semaphore non blocking I wsem post Posts a lightweight semaphore Iwsem test Tests the lightweight semaphore component Iwsem wait Waits for a lightweight semaphore Freescale MQX Real Time Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 55 Using MQX Table 3 14 Summary Using Lightweight Semaphores continued _lwsem_wait_for Waits for a lightweight semaphor
176. particular type of processor on a particular type of board It includes drivers See also PSP bus snooping The cache monitors bus activity If the application performs a write operation to an address that is a cache entry the cache updates its cache If the application performs a read operation for an address that is a cache entry the cache supplies the data byte See single addressable unit C cache A region of fast memory that holds copies of data data cache or instructions instruction cache sometimes called code cache Access to the cached copy is usually more efficient than access to the original Some CPUs have a unified cache which they use for both data and code callback function See notification function checksum CHECKSUM Many MQX data structures include a CHECKSUM field If the field is incorrect MQX considers the data within the structure corrupted See also valid child A task that this task created See also creator code cache See cache component A group of MQX functions that offers a service such as the mutex component or the watchdog component Components can be core or optional context MQX maintains context for each instance of each task and for the current ISR Context includes the program counter registers stack task state and task resources corrupted MQX considers data within a structure corrupted if its checksum is incorrect or pointers are incorrect See also invalid C
177. pecific to your target environment e Ensure you have the required tools for your target environment compiler assembler linker librarian e Be familiar with the MQX directory structure and re build instructions as they are described in the release notes document and also the instructions provided later in this section FREESCALE MQX Freescale MQX can be conveniently built by using one of the supported development environments for example Freescale CodeWarrior Development Studio Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 141 D Rebuilding MQX 4 3 Freescale MQX Directory Structure FREESCALE MQX With a few exceptions the Freescale MQX directory structure is the same as it was in the previous MQX releases The major difference is that multiple components MQX MFS RTCS USB are installed together in one top level directory and they share the common config and ib directories Figure 4 1 shows the directory structure of the whole Freescale MQX RTOS distribution e Freescale MOX 3 a config MOX Configuration header files for different boards 3 common may reuse common files in directory common O ms2259demo CO m52259evb doc Documentation 3 lib CD ms2259demo cw a mS2259evb cw MOX libraries compiled in CodeWarrior for particular board
178. periodic interrupt and prints a message every time the interrupt occurs The task first creates a task queue then suspends itself in the queue The simulated ISR task task simulates a periodic interrupt with time delay and when the timeout expires it schedules service task Freescale MQX Real Time Operating System User Guide Rev 3 80 Freescale Semiconductor 3 7 8 4 1 Code for the Example taskq c include lt mgx h gt include lt fio h gt Task IDs define SERVICE TASK 5 define ISR_TASK 6 extern void simulated ISR task uint 32 extern void service task uint 32 TASK TEMPLATE STRUCT MOX template list SERVICE TASK service task 600 5 service MOX AUTO START TASK OL 0 ISR TASK simulated ISR task 600 5 simulated ISR 0 OL 0 0 0 0 0 0 0 OL 0 pointer my task queue TASK Task Name simulated_ISR_task Comments This task pauses and then resumes the task queue void simulated ISR task uint 32 initial data while TRUE time delay 200 _taskq resume my task queue FALSE J TAGRAS SRE MES e ene oe Baie dee ne canal Nae nt en de Task Name service task Comments This task creates a task queue and the simulated ISR task task Then it enters an infinite loop printing Tick and suspending the task queue AX A void service task uint 32 initial data _task_id second_t
179. reescale MQX does not support the IPC component required for native EDS communication Use the EDSerial or TCP IP servers 3 14 Configuring MQX at Compile Time MQX is built with certain features that you can include or exclude by changing the value of compile time configuration options If you change any configuration value you must recompile the MQX and relink it with your target application As the Board Support Package BSP library may also depend on some MQX configuration options it must be typically recompiled as well Like BSP there are also other code components that use the MQX OS services for example RTCS MES USB These components need to be re compiled after the MQX and BSP FREESCALE MQX Comparing with original ARC versions Freescale MQX introduces a different method of compile time configuration of the MQX OS and other components Original method used the compiler command line D options or source psp platform psp_cnfg asm file In Freescale MQX there is a central user configuration file user config h in the config lt board gt directory which can be used to override default configuration options The same configuration file is used by other system components like RTCS MFS or USB 3 14 4 MQX Compile Time Configuration Options This section provides a list of MQX configuration options The default value of any of these options can be overridden in the config lt board gt user_config h
180. rnel timer interrupt Chain the ISR to the previous ISR which is the BSP provided periodic timer ISR isr c Hinclude lt mgx h gt include lt bsp h gt define MAIN TASK 10 extern void main task uint 32 extern void new tick isr pointer TASK TEMPLATE STRUCT MOX template list MAIN TASK main task 2000 8 Main MOX AUTO START TASK OL O 0 0 0 0 0 0 OL 0 typedef struct pointer OLD ISR DATA void CODE PTR OLD ISR pointer _mgx uint TICK COUNT MY ISR STRUCT _PTR MY ISR STRUCT PTR ISR Name new tick isr Comments This ISR replaces the existing timer ISR old timer ISR void new tick isr pointer user isr ptr MY ISR STRUCT PTR isr ptr isr ptr MY ISR STRUCT PTR user isr ptr isr ptr TICK COUNT Chain to previous notifier isr ptr OLD ISR isr ptr gt OLD ISR DATA then calls the ETASK 2 2 O Task Name main task Comments This task installs a new ISR to replace the timer ISR It then waits for some time finally printing out the Freescale MQX Real Time Operating System User Guide Rev 3 112 Freescale Semiconductor Using MQX number of times the ISR ran void main task uint 32 initial data MY ISR STRUCT PTR isr ptr isr ptr mem alloc zero sizeof MY ISR STRUCT isr ptr TICK COUNT 0 isr ptr gt OLD ISR DATA int get isr data BSP TIMER INTERRUPT VE
181. ro filled private memory block from the default memory pool mem alloc zero from Allocates a zero filled private memory block from the specified memory pool mem alloc system Allocates a system memory block from the default memory mem alloc system from Allocates a system memory block from the specified memory pool mem alloc system zero Allocates a zero filled system memory block from the default memory pool mem alloc system zero from Allocates a zero filled system memory block from the specified memory pool mem copy Copies data from one memory location to another mem create pool Creates a memory pool outside the default memory pool mem extend Adds additional memory to the default memory pool the additional memory must by outside the current default memory pool but need not be contiguous with it mem extend pool Adds additional memory to a memory pool that is outside the default memory pool the additional memory must be outside the memory pool but it needs notto be contiguous with the pool mem free Frees a memory block that is inside or outside the default memory pool mem free part Frees part of a memory block used if the memory block is larger than requested or if it is larger than needed mem get error Gets a pointer to the memory block that caused mem test to indicate an error mem get error pool
182. roup See fast event group indexed semaphore See fast semaphore instance MQX creates an instance of an application task if the task is an autostart task or if an application calls task create The instance is uniquely identified by its task ID and task descriptor Unless it would create confusion the instance of the task is simply called the task The POSIX term is thread instruction cache See cache invalid MQX considers data invalid if the VALID field in its structure is not the same as what MQX set it to See also checksum corrupted and valid 1 0 Generally refers to the transfer of commands or data across a device interface Freescale MQX Real Time Operating System User Guide Rev 3 164 Freescale Semiconductor IPC Inter processor communication The mechanism by which multiple processors communicate IPC task The MQX task that is required on each processor of a multi processor application ISR Interrupt service routine small high speed routine that reacts quickly to hardware interrupts K KB kilobyte kernel data Data structure where MQX stores all internal information that it needs The information is stored either directly or as pointers to other data structures kernel ISR The assembly language routine that saves the current context switches from the task s stack to the interrupt stack runs the appropriate ISR and after that ISR completes makes ready the highest priority ready
183. runtime library 5 6 1 boot and lt compiler gt c The boot file either coded in C or Assembler and the lt compiler gt c file where lt compiler gt is an abbreviated name of the compiler tool implement the compiler dependent code required for starting up the processor and for run time board setup These files are typically located in a subdirectory with other compiler dependent source and configuration files The code in the boot file handles the reset condition e It disables interrupts e It sets up a initial stack for the rest of the boot up process e It initializes the hardware registers such as vector base address peripheral register base address internal memory base address etc e It sets up key processor resources such as clock source PLL external bus etc e It passes the control to the standard compiler specific startup function which takes care about C variable initialization and invoking the main function The main function is implemented in the BSP source code in the mgx_main c file Body of the main function passes control to the MQX kernel by calling the _mgx function int main void Body extern const MQX INITIALIZATION STRUCT MQX init struct Start MQX mqx MOX INITIALIZATION STRUCT PTR amp MOX init struct return 0 Endbody Freescale MQX Real Time Operating System User Guide Rev 3 152 Freescale Semiconductor Developing a New BSP 5 7 Modifyin
184. s A task waits for a pattern of event bits a mask in an event group with event wait all or event wait any When a bit is set MQX makes ready the tasks that are waiting for the bit If the event group is created with autoclearing event bits _event_create_auto_clear or _event_create fast_auto_clear MQX clears the bit so that the waiting tasks need not clear it 3 7 1 5 Setting Event Bits A task can set a pattern of event bits a mask in an event group with _event_set The event group can be local or on a remote processor When an event bit is set tasks waiting for the bit are made ready If the event group is created with autoclearing event bits MQX clears the bits as soon as they are set 3 7 1 6 Clearing Event Bits A task can clear a pattern of event bits a mask in an event group with _event_clear However if the event group is created with autoclearing event bits MQX clears the bits as soon as they are set Freescale MQX Real Time Operating System User Guide Rev 3 48 Freescale Semiconductor Using MQX 3 7 1 7 Closing a Connection to an Event Group When a task no longer needs to use an event group it can close its connection to the group with event close 3 7 1 8 Destroying an Event Group If tasks are blocked waiting for an event bit in the to be destroyed event group MQX moves them to their ready queues 3 7 1 9 Example Using Events Simulated tick ISR sets an event bit each time i
185. s begin with a message header MESSAGE HEADER STRUCT that defines the information that MQX needs to route the message Application defined data follows the message header typedef struct message header struct _msg size SIZE if MOX USE 32BIT MESSAGE QIDS uint 16 PAD endif queue id TARGET QID queue id SOURCE QID uchar CONTROL Freescale MQX Real Time Operating System User Guide Rev 3 74 Freescale Semiconductor Using MQX if MOX USE 32BIT MESSAGE QIDS uchar RESERVED 3 else uchar RESERVED Hendif MESSAGE HEADER STRUCT _PTR_ MESSAGE HEADER STRUCT PTR For a description of each field see MQX Reference 3 7 7 4 Sending Messages After a task allocates a message and fills in the message header fields and any data fields it sends the message with msgq send which sends the message to the target message queue that is specified in the message header Sending a message is not a blocking action 3 7 7 5 Message Queues Tasks use message queues to exchange messages There can be private message queues and system message queues When a task opens a message queue specified by a message queue number MOX returns an application unique queue ID which tasks subsequently use to access the message queue A task can convert a queue number to a queue ID with msgq get id 3 7 7 5 1 16 Bit Queue IDs The most significant byte of a 16 bit queue ID contains the processor number and the least si
186. s not get 10 ms of linear time since higher priority tasks will preempt it Also if the task calls a scheduling function for example task block or _sched_yield MQX sets the task s time slice counter back to zero As with timeouts the time that MQX allocates is plus or minus BSP ALARM FREQUENCY ticks per second 6 14 Timers My application is on more than one processor have a master processor that sends a synchronization message to the other processors that causes them to reset their time How can make sure that the reset messages don t interfere with the timers that the application uses So that timers are not affected by changes to absolute time time set start timers with relative time TIMER ELAPSED TIME rather than absolute time TIMER KERNEL TIME MODE What happens if timer start oneshot at is given an expiry time that is in the past MQX puts the element in the timer queue When the next periodic timer interrupt occurs MQX determines that the current time is greater than or equal to the expiry time so the timer triggers and MQX calls the notification function Freescale MQX Real Time Operating System User Guide Rev 3 160 Freescale Semiconductor Glossary A active task The task that is currently running on the processor that is the highest priority ready task address See logical address physical address and virtual address application The application consists of code that deve
187. s the entire application on a processor it does not monitor individual tasks FREESCALE MQX To optimize code and data memory requirements on some target platforms the Watchdog component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details The MQX watchdog component provides a software watchdog for each task If a single task starves or runs beyond certain timing constraints the watchdog provides a way to detect the problem Initially the task starts its watchdog with a specific time value and if the task fails to stop or restart the watchdog before that time expires MQX calls a processor unique application supplied expiry function that can initiate error recovery Table 3 24 Summary Using Watchdogs Watchdogs use certain structures and constants which are defined in watchdog h watchdog create component Creates the watchdog component watchdog start Starts or restarts the watchdog time is specified in milliseconds watchdog start ticks Starts or restarts the watchdog time is specified in ticks watchdog stop Stops the watchdog watchdog test Tests the watchdog component Freescale MQX Real Time Operating System User Guide Rev 3 102 Freescale Semiconductor Using MQX
188. sage to a message queue msgq send queue Sends a message directly to a message queue circumvents inter processor routing msgq send urgent Sends an urgent message to a message queue msgq set notification function Sets the notification function for a message queue msgq test Tests message queues 3 7 7 1 You can explicitly create the message component with msg create component If you do not explicitly create it MQX creates it the first time that an application creates a message pool or opens a message queue Creating the Message Component 3 7 7 2 Tasks allocate messages from message pools which a task must first create A task can create a private message pool msgpool create or a system message pool msgpool create system Using Message Pools A task specifies the following info when it creates a message pool Size of the messages in the pool Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 73 Using MQX e Initial number of messages in the pool Grow factor the number of additional messages that MQX adds to the pool if tasks have allocated all the messages Maximum number of messages in the pool if the grow factor is not zero zero means here that the pool can contain an unlimited number of messages The function msgpool create system can be called multiple times to create multiple system message pools each wit
189. self does not depend on the board features the user may want to build a different PSP for different boards 4 4 1 PSP Build Project The PSP project is used to build the PSP library which contains the platform dependent parts from max source psp and also contains generic MOX RTOS code 4 4 2 BSP Build Project The BSP project is used to build the BSP library which contains the board specific code from mgqx source bsp lt board gt and also the selected I O drivers from mqxNsourceNo directory Freescale MQX Real Time Operating System User Guide Rev 3 144 Freescale Semiconductor up Rebuilding MOX MQX RTOS BSP library board a PSP library compiled as mqx a 5 e g mqxbuild psp m52259evb mcp gt lib m52259evb cw mqx mqx a OG USES ENS Aisa mqx source io config lt board gt IO Drivers User Configuration each driver is typically split to device independent code and code specific to device or family of devices Included by all MQX files Linked library files and related public header files mqx source bsp board BSP Device and lib board mqx Board specific code lib lt board gt startup vector table device memory d board initialization starting _1 3 aa 10 drivers oia Binary Libraries linked by apps 4 4 3 Post Build Processing All build projects are configured to generate the resulting binary library file in the top level lib lt board gt lt compiler gt dire
190. set event bits in an event group that is on a remote processor 2 6 3 Lightweight Semaphores Lightweight semaphores LWSems are a core component They are a low overhead way for tasks to synchronize their access to shared resources LWSems require a minimal amount of memory and run quickly LWSems are counting FIFO semaphores without priority inheritance 2 6 4 Semaphores Semaphores are an optional component They are counting semaphores You can use semaphores to synchronize tasks You can use a semaphore to guard access to a shared resource or to implement Freescale MQX Real Time Operating System User Guide Rev 3 18 Freescale Semiconductor MQX at a Glance a producer consumer signalling mechanism Semaphores provide FIFO queuing priority queuing and priority inheritance Semaphores can be strict or non strict There are named and fast semaphores 2 6 5 Mutexes Mutexes are an optional component They comply with POSIX 4a threads extensions A mutex provides mutual exclusion among tasks when they access a shared resource Mutexes provide polling FIFO queuing priority queuing spin only and limited spin queuing priority inheritance and priority protection Mutexes are strict that is a task cannot unlock a mutex unless it had first locked the mutex 2 6 6 Messages Messages are an optional component Tasks can communicate with each other by sending messages to message queues that are opened by other tasks Each task
191. sible by read and write tasks Contains a DATA array that simulates a FIFO READ INDEX and WRITE INDEX mark the location in the array that the read and write tasks are accessing All data is protected by semaphores typedef struct task id DATA ARRAY SIZE uint 32 READ INDEX uint 32 WRITE INDEX SW FIFO PTR SW FIFO PTR Function prototypes extern void main task uint 32 initial data extern void write task uint 32 initial data extern void read task uint 32 initial data extern SW FIFO fifo 3 7 5 8 2 Task Templates for the Example ttl c include lt mgx h gt include main h TASK TEMPLATE STRUCT MOX template list MAIN TASK main task 1000 5 main MQX AUTO START TASK OL 0 WRITE TASK write task 600 5 write 0 OL O READ TASK read task 1000 5 read 0 OL O o0 0 0 0 0 0 OL 0 3 7 5 8 3 Code for Main Task The Main task creates The semaphore component The Index Read and Write semaphores e Read and Write tasks Freescale MQX Real Time Operating System User Guide Rev 3 Using MQX Freescale Semiconductor 63 p Using MQX main c include lt mgx h gt include lt bsp h gt include lt sem h gt include main h SW FIFO fifo TASK Task Name main task Comments This task initializes three semaphores creates NU
192. start tasks Initialization Freescale MQX Real Time Operating System User Guide Rev 3 16 Freescale Semiconductor MQX at a Glance 2 3 Task Management Task management is a core component As well as it automatically creates tasks when MQX starts an application can also create manage and terminate tasks as the application runs It can create multiple instances of the same task and there is no limit to the total number of tasks in an application The application can dynamically change the attributes of any task MQX frees task resources when it terminates a task As well for each task you can specify e An exit function which MQX calls when it terminates the task e An exception handler which MQX calls if an exception occurs while the task is active 2 4 Scheduling Scheduling complies with POSIX 4 real time extensions and supports these policies e FIFO also called priority based preemptive scheduling is a core component the active task is the highest priority task that has been ready the longest e Round robin also called time slice scheduling is a core component the active task is the highest priority task that has been ready the longest without consuming its time slice e Explicit scheduling using task queues is an optional component you can use task queues to explicitly schedule tasks or to create more complex synchronization mechanisms Because task queues provide minimal functionality they
193. t creating 55 priority inheritance 56 priority protection 56 scheduling protocols 56 unlocking 57 using 54 waiting protocols 55 mutual exclusion 8 40 47 54 example 50 57 N name component 11 creating 113 using 112 nesting of ISRs getting 94 notification functions message queues 63 timers 9 84 85 86 lightweight 9 89 O opening event group connections 36 message queues private 63 system 63 semaphore connections 49 P partition blocks 7 27 allocating 28 freeing 28 partitions 7 27 creating 28 destroying 28 example 28 peeking at first message in message queue 60 pending message count getting 63 Performance Tool 10 108 periodic queues 89 periodic timer interrupt notify kernel 82 resolution getting and setting 81 vector number setting 82 periodic timer ISR installing 83 polling for messages 63 posting lightweight semaphores 43 semaphores 47 49 preemption 25 preemption enabling and disabling 24 priority mutex attributes getting and setting 57 mutexes geting and setting 55 tasks assigning 14 priority inheritance 41 mutexes 56 semaphores 48 priority inversion 40 avoiding 41 42 example 40 priority messages sending 60 priority protection 42 priority protection mutexes 56 processor number task getting for 19 producer consumer example 44 Q queue IDs 62 Freescale MQX Real Time Operating Sys
194. t runs Service task performs a certain action each time a tick occurs and therefore waits for the event bit that Simulated tick sets 3 7 1 9 1 Code for the Example event c include mgx h include lt fio h gt include lt event h gt Task IDs define SERVICE TASK 5 define ISR_TASK 6 Function Prototypes extern void simulated ISR task uint 32 extern void service task uint 32 TASK TEMPLATE STRUCT MOX template list SERVICE TASK service task 500 5 service MQX AUTO START TASK OL 0 ISR TASK simulated ISR task 500 5 simulated ISR 0 OL O o 0 0 0 0 0 OL 0 E TASK Task Name simulated ISR task Comments This task opens a connection to the event After delaying the event bits are set END 225452 2820 so6 ont ce Lecker e ae void simulated ISR task uint 32 initial data pointer event ptr open event connection if event open global amp event ptr MQX OK printf nOpen Event failed mgx exit 0 Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 49 Using MQX while TRUE _time delay 1000 if event set event ptr 0x01 MOX OK printf nSet Event failed _mgx exit 0 JPTASKE Sooo aiii ones ons sn nee tutos Task Name Service task Comments This task creates an event and the simulated ISR task task It opens a connection to the ev
195. t task ID which MQX and other tasks use to identify the task The section on initialization page 23 shows how a task can be started automatically when MOX initializes You can also create manage and terminate tasks while the application runs task abort Terminates the task after running its task exit handler and releasing its resources task check stack Determines whether the task s stack is out of bounds task create Allocates and starts makes ready a new task task create blocked Allocates a new task in the blocked state task destroy Terminates the task after freeing its resources task disable fp Disable floating point context switching for the task if the task is a floating point task task enable fp Enables floating point context switching for the task task errno Gets the task error code for the active task task get creator Gets the task ID of the task that created the task task get environment Gets a pointer to the environment data for a task task get error Gets the task error code task get error ptr Gets a pointer to the task error code task get exit handler Gets a task s task exit handler task get id Gets the task ID task get id from name Gets the task ID of the first task with this name in the task template task get index from id Gets the task template index for the task ID
196. task get parameter Gets the task creation parameter task get parameter for Gets the task creation parameter for a task task get processor Gets the processor number on which a task resides task get td Converts a task ID to a pointer to a task descriptor task get template index Gets the task template index of a task name task get template ptr Gets a pointer to the task template for the task ID task restart Restarts a task at the beginning of the task s function keeps the same task descriptor task ID and task stack task set environment Sets a pointer to the environment data for a task task set error Sets the task error code task set exit handler Sets the task s exit handler Freescale MQX Real Time Operating System User Guide Rev 3 30 Freescale Semiconductor Using MQX task set parameter Sets the task creation parameter task set parameter for Sets the task creation parameter for a task 3 4 1 Creating Tasks Any task creator can create another task child by calling task create or task create blocked and passing the processor number a task template index and a task creation parameter The application defines one creation parameter which is normally used to provide initialization information to the child A task can also create a task that is not defined in the task template list by specifying a te
197. te list The list of task templates that is defined in the MQX initialization structure for the processor Abbreviated as TTL thread POSIX term for an instance of a task tick A tick is considered to have occurred each time a periodic timer interrupts timeout queue Queue of tasks that are waiting for a specific length of time after which MQX returns them to their ready queues Timer task The MQX task that MQX creates if the application uses the timer component time slice Maximum time that a round robin task is active before MQX preempts it and attempts to reschedule another task of the same priority Freescale MQX Real Time Operating System User Guide Rev 3 172 Freescale Semiconductor time slice scheduling See round robin scheduling time slice task See round robin task TLB Translation lookaside buffer an MMU translation register TRUE Not FALSE that is any value that is not zero TTL Task template list TTR Transparent translation register an MMU translation register U unified cache Some CPUs have a unified cache which they use for both data and code unlock When a task unlocks a mutex it releases the mutex See also lock post and wait user log See log and lightweight log V valid VALID Many MQX data structures include a VALID field MQX considers the data in the structure valid if the field is set to a known value See also checksum corrupted and invalid virtual a
198. ted lightweight semaphores were removed from the list of freed resources in sec tion 3 4 6 Res 04 2011 Description of the MQX HARDWARE INTERRUPT LEVEL MAX Configura tion Parameter added Freescale and the Freescale logo are trademarks of Freescale Semiconductor Inc Freescale Semiconductor Inc 2010 All rights reserved Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor Freescale MQX Real Time Operating System User Guide Rev 3 10 Freescale Semiconductor Chapter 1 Before You Begin 1 1 About MQX The MQX Real Time Operating System from MQX Embedded has been designed for uni processor multi processor and distributed processor embedded real time systems To leverage the success of the MQX operating system Freescale Semiconductor adopted this software platform for its ColdFire and PowerPCTM familes of microprocessors Comapring to the original MQX distributions the Freescale MQX distribution was made simpler to configure and use One single release now contains the MQX operating system plus all the other software components supported for a given microprocessor part In this document the sections specific to Freescale MQX release are marked as below FREESCALE MQX This is how notes specific to Freescale MQX release are marked in this document MQX is a run time library of functions that programs use to become real time multi tasking appl
199. ted with autoclearing event bits MQX clears the bits as soon as they are set 3 7 2 5 Destroying a Lightweight Event Group When a task no longer needs a lightweight event group it can destroy the event group with Iwevent destroy 3 7 3 About Semaphore Type Objects MQX provides lightweight semaphores LWSems semaphores and mutexes You can use both types of semaphores for task synchronization and mutual exclusion A task waits for a semaphore If the semaphore count is zero MQX blocks the task otherwise MQX decrements the semaphore count gives the task the semaphore and the task continues to run When the task is finished with the semaphore it posts the semaphore the task remains ready If a task is waiting for the semaphore MQX puts the task in the task ready queue otherwise MQX increments the semaphore count You can use mutexes for mutual exclusion A mutex is sometimes called a binary semaphore because its counter can be only zero or one 3 7 3 1 Strictness If a semaphore type object is strict a task must first wait for and get the object before it can release the object If the object is non strict a task does not need to get the object before it releases the object Freescale MQX Real Time Operating System User Guide Rev 3 52 Freescale Semiconductor 3 7 3 2 Priority Inversion Using MQX Task priority inversion is a classic condition where the relative priorities of tasks appear to be reversed
200. tem User Guide Rev 3 Freescale Semiconductor 179 queues periodic 89 R random numbers getting 117 reading kernel log 108 lightweight logs 105 logs 101 ready queues creation 13 number 15 receiving messages message queues from 63 remotely 70 restarting tasks 21 resuming tasks task queues 67 rollover of MQX time 80 RR interval getting and setting 24 S scheduling policy getting and setting 24 scheduling protocols mutexes 56 scheduling tasks FIFO 23 policy getting and setting 24 round robin 24 RR interval getting and setting 24 yielding the processor 24 second millisecond time format 82 semaphore component creating 48 semaphores 8 33 connections closing 49 opening 49 creating 48 semaphore component 48 destroying 49 FIFO queuing 48 initial count 48 posting 49 priority inheritance 48 priority queuing 48 queuing protocols 48 strictness 49 using 47 waiting for 49 semaphore type objects 40 comparison 42 sending messages broadcast 60 priority 60 remotely 70 urgent 60 spin 42 55 spin limit mutex attributes getting and setting 57 spin only 42 55 stack usage 11 stack usage getting 111 stacks task out of bounds 19 starting MQX 6 13 states 25 strictness 40 lightweight semaphores 43 mutexes 55 semaphores 49 suspending tasks on task queues 67 synchronizing tasks 7 8 9 33 40 example 50 68 System Task Descriptor 117 T
201. tem User Guide Rev 3 Freescale Semiconductor 91 Using MQX 3 8 5 Endian Conversion of Message Headers When a processor receives a message from a remote processor the IPC input function examines the CONTROL field in the message header to determine whether the message is from a processor that uses the other endian format If the message is the input function converts the message header to the local processor s own endian format and sets the CONTROL field to specify its endian format MESSAGE HEADER STRUCT msg ptr if MSG MUST CONVERT HDR ENDIAN msg ptr CONTROL msg swap endian header msg ptr CAUTION The IPC cannot convert the data portion of the message to the other endian format because it does not know the format of the data Itis the responsibility of the application to convert the data portion of received messages to the other endian format To check whether conversion is necessary use the macro MSG MUST CONVERT DATA ENDIAN To convert the message data use msg swap endian data Both functions are defined in message h For more information see MQX Reference 3 9 Timing MQX provides the core time component which can be extended with optional timer and watchdog components 3 9 1 Rollover of MQX Time MQX keeps the time internally as a 64 bit count of the number of tick interrupts since the application started to run This provides a very long time before MQX time rolls over For ex
202. terminated MQX frees the task s MQX managed resources These resources include e dynamically allocated memory blocks and partition blocks message queues messages e mutexes e non strict semaphores Strict semaphores after posting them e queued connections are dequeued e task descriptor An application can terminate a task immediately after MQX frees the task s resources with _task_destroy or gracefully with task abort When a task is terminated gracefully MQX puts the task in the appropriate ready queue if the task is blocked When the to be terminated task becomes active an application defined task exit handler runs The exit handler could clean up resources that MQX does not manage The task exit handler is set with _task_set_exit_handler and obtained with _task_get_exit_handler MQX also calls the task exit handler if the task returns from its task body 3 4 7 Example Creating Tasks This example adds a second task world_task to the example on page 27 We modify that example s task template list to include information about world_task and to change hello_task so that it is not an autostart task The world_task task is an autostart task Freescale MQX Real Time Operating System User Guide Rev 3 32 Freescale Semiconductor Using MQX When MQX starts it creates world_task The world_task then creates hello_task by calling _task_create with hello_task as a parameter MQX uses the hel
203. tex attributes structure mutatr get priority ceiling Gets the priority of a mutex attributes structure mutatr get sched protocol Gets the scheduling protocol of a mutex attributes structure mutatr get spin limit Gets the limited spin count of a mutex attributes structure mutatr get wait protocol Gets the waiting policy of a mutex attributes structure mutatr init Initializes a mutex attributes structure Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 69 Using MQX Table 3 17 Summary Using a Mutex Attributes Structure continued mutatr set priority ceiling Sets the priority value in a mutex attributes structure mutatr set sched protocol Sets the scheduling protocol of a mutex attributes structure mutatr set spin limit Sets limited spin count of a mutex attributes structure mutatr set wait protocol Sets the waiting protocol of a mutex attributes structure 3 7 6 6 Locking a Mutex To access a shared resource a task can lock the mutex that is associated with the resource by calling mutex lock If the mutex is not already locked the task locks it and continues to run If the mutex is already locked depending on the mutex waiting protocols that are described on page 68 the task might block until the mutex is unlocked To be sure that it does not block a task can try to lock a mutex with mutex trylock If the mutex is not already
204. the number of bits the vector number is shifted to get index of ISR linked list root For example with 256 potential interrupt sources and with shift value of 3 it makes 256223232 lists each with maximum depth of eight ISR entries Shift value of 8 would yield one big linked list of all ISR entries MQX TASK CREATION BLOCKS Default is one The option applies to multi processor applications only One A task blocks when it calls task create to create a task on another processor The creating task blocks until the new task is created and an error code is returned MQX TASK DESTRUCTION Default is one One MQX allows tasks to be terminated As a result MQX includes code that frees all the MQX managed resources that terminated tasks own MQX TIMER USES TICKS ONLY Default is zero One Timer task processes periodic timer and one shot timer requests using tick time for timeout reporting rather than second millisecond time Freescale MQX Real Time Operating System User Guide Rev 3 136 Freescale Semiconductor Using MQX MQX USE 32BIT MESSAGE QIDS Default is zero Zero Message component data types queue number and queue id are uint 16 One Message component data types queue number and queue id are uint_32 This allows for more than 256 message queues on a processor and more than 256 processors in a multi processor network MQX USE IDLE TASK Default is one One the kernel will create the idle task which wil
205. ticks Starts a periodic timer at a specific time in tick time timer start periodic every Starts a periodic timer every number of milliseconds timer start periodic every Starts a periodic timer every number of ticks ticks timer test Tests the timer component 3 9 4 1 Creating the Timer Component You can explicitly create the timer component by calling timer create component with the priority and stack size for Timer task which MQX creates when it creates the timer component Timer task manages timer queues and provides a context for notification functions If you do not explicitly create the timer component MQX creates it with default values the first time an application starts a timer Parameter Default Priority of Timer task 1 Stack size for Timer task 500 3 9 4 2 Starting Timers A task starts a timer with one of the following timer start oneshot after timer start oneshot after ticks e timer start oneshot at timer start oneshot at ticks timer start periodic at timer start periodic at ticks timer start periodic every timer start periodic every ticks When a task calls one of these functions MQX inserts a timer request into the queue of outstanding timers When the timer expires the notification function runs CAUTION The stack space for Timer task should include the stack space that the notification function needs 3 9 4 3 Cancelling Ou
206. ting table refers to an IPC that must have a corresponding entry in the protocol initialization table defining the protocol and communication path that implement the IPC NOTE ThelPC OUT QUEUE field in IPC PROTOCOL INIT STRUCT must match the QUEUE field in IPC ROUTING STRUCT The protocol initialization table is an array of protocol initialization structures and ends with a zero filled entry Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 85 Using MQX typedef struct ipc protocol init struct max uint CODE PTR IPC PROTOCOL INIT struct ipc protocol init struct PTR ipc init ptr pointer ipc info ptr pointer ipc info ptr pointer IPC PROTOCOL INIT DATA char PTR IPC NAME queue number IPC OUT QUEUE IPC PROTOCOL INIT STRUCT PTR IPC PROTOCOL INIT STRUCT PTR The fields are described in MQX Reference When MQX with the IPC component initializes it calls the IPC PROTOCOL INIT function for each IPC in the table It passes to the IPC the IPC PROTOCOL INIT DATA which contains IPC specific initialization information 3 8 4 3 IPC Using I O PCB Device Drivers While you can develop special purpose IPCs MQX provides a standard IPC that is built on I O packet control block PCB device drivers Using this IPC an application can use any I O PCB device driver to receive and send messages See Section 3 8 4 5 Example IPC Initialization Information Here is
207. to address memory applications and applications that need high speed Lightweight components typically use memory mapped data structures without multi processor capability They are faster than their regular counterparts however they have fewer features and protection mechanisms Lightweight components include Lightweight events new use a memory mapped data structure to define an event group Lightweight logs new consist of fixed sized entries Kernel log is now a lightweight log Lightweight memory component new uses less overhead to maintain heaps of variable sized memory blocks MQX can be configured to use the lightweight memory component as the default memory component lightweight semaphores use a memory mapped data structure to define a semaphore lightweight timers new use memory mapped data structures to provide repetitive time driven services Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 13 Before You Begin 1 4 Conventions 1 4 1 Tips Tips point out useful information TiP The most efficient way to allocate a message from an ISR is to use msg alloc 1 4 2 Notes Notes point out important information NOTE Non strict semaphores do not have priority inheritance 1 4 3 Cautions Cautions tell you about commands or procedures that could have unexpected or undesirable side effects or co
208. ts like MFS RTCS or USB are released together with the Freescale MQX RTOS Atthe moment of writing this document the default development environment for Freescale MQX RTOS and other MQX components is CodeWarrior Development Studio New releases may bring support for other development environments Compile time configuration of all key Freescale MQX RTOS components PSP BSP RTCS MFS USB is now accomplished by editing the user config h file located in board specific directory in the top level config folder In the previous versions the user configuration macros were passed to the build process on a command line by the makefile or using the CodeWarrior prefix file The PSP component is configured and built for specific board Originally the PSP component was built once for the particular device While the PSP code still remains board independent this feature enables finer kernel tuning for a specific board MQX now supports typed memory which allows additional information to be displayed in the task aware debugger plugin MQX version 2 50 is backward compatible with version 2 40 and offers these enhancements over version 2 40 Reduced dependency on 32 bit types types are determined by the natural size of the processor For instance on a 16 bit processor generic types are 16 bits in size Code and data size requirements are reduced for the smaller architecture processors Time is measured in ticks to allow for higher r
209. tstanding Timer Requests A task can cancel an outstanding timer request by calling timer cancel with the timer handle that was returned from one of the timer start family of functions Freescale MQX Real Time Operating System User Guide Rev 3 98 Freescale Semiconductor Using MQX 3 9 4 4 Example Using Timers Simulate a LED being turned on and off every second One timer turns the LED on and another turns it off The timers expire every two seconds offset by one second 3 9 4 4 1 Code for Timer Example main c include mgx h include lt bsp h gt include lt fio h gt include lt timer h gt define TIMER TASK PRIORITY 2 define TIMER STACK SIZE 1000 define MAIN TASK 10 extern void main task uint 32 TASK TEMPLATE STRUCT MOX template list MAIN TASK main task 2000 8 Main MOX AUTO START TASK OL 0 o 0 0 0 0 0 OL 0 FUNCTION Function Name LED on Returned Value none Comments E This timer function prints ON ox OR void LED on timer id id pointer data ptr MQX TICK STRUCT PTR tick ptr printf ON n JPRUNCTION 23222555 less lotes sees sre SORAA te eee ae renes ees Function Name LED off Returned Value none Comments This timer function prints OFF ENDESA SE acm Bc RA void LED off Freescale MQX Real Time Operating System User Guide Rev 3 Fre
210. ture you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details A task can start a timer at a specific time or at some specific time after the current time Timers can use elapsed time or absolute time There are two types of timers e One shot timers which expire once e Periodic timers which expire repeatedly at a specified interval When a periodic timer expires MQX resets the timer Table 3 22 Summary Using Timers Timers use certain structures and constants which are defined in timer h timer cancel Cancels an outstanding timer request timer create component Creates the timer component timer start oneshot after Starts a timer that expires once after a time delay in milliseconds timer start oneshot after ticks Starts a timer that expires once after a time delay in ticks timer start oneshot at Starts a timer that expires once at a specific time in second millisecond time Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 97 Using MQX Table 3 22 Summary Using Timers continued _timer_start_oneshot_at_ticks Starts a timer that expires once at a specific time in tick time _timer_start_periodic_at Starts a periodic timer at a specific time in second millisecond time _timer_start_periodic_at_
211. uantity of information in the data cache or in the instruction cache The quantity depends on the CPU little endian The most significant byte is the last byte in the word See also big endian local Pertaining to the processor on which the task runs See also remote lock verb When a task locks a mutex it gets owns the mutex When a task unlocks a mutex it releases the mutex See also post and wait log Logs let applications log and retrieve application specific information and associate it with timestamps Sometimes called user logs See also kernel log lightweight log logical address An address that is generated by the CPU When it is different from its physical address it is called a virtual address LWLog See lightweight log LWMem See lightweight memory LWSem See lightweight semaphore LWTimer See lightweight timer M memory Anywhere in the addressable memory range of the hardware See also memory block physical memory virtual memory and lightweight memory memory block A memory block is memory that a task has allocated and that MQX manages Memory blocks are not a fixed size and can be inside or outside the default memory pool See also memory memory block partition and partition block message pool Messages are allocated from message pools memory management unit See MMU Freescale MQX Real Time Operating System User Guide Rev 3 166 Freescale Semiconductor memory pool An
212. ue and puts them in their ready queues taskq suspend Suspends a task and puts it in the specified task queue and removes it from the task s ready queue taskq suspend task Suspends the non blocked task and puts it in the specified task queue and removes it from the task s ready queue taskq test Tests all task queues 3 7 8 1 Creating and Destroying Task Queues Before an application can perform explicit task scheduling it must first initialize a task queue by calling _taskq_create with the queuing policy for the task queue MQX creates the task queue and returns a queue ID which the task subsequently uses to access the task queue A task queue is not a resource of the task that created it It is a system resource and is not destroyed when its creating task is terminated A task can explicitly destroy a task queue with _taskq_destroy If there are tasks in the task queue MQX moves them to their ready queues 3 7 8 2 Suspending a Task A task can suspend itself in a specific task queue with taskq suspend MQX puts the task in the queue blocks the task according to the queuing policy of the task queue 3 7 8 3 Resuming a Task A task calls _taskq_resume to remove either one or all tasks from a specific task queue MQX puts them in their ready queues 3 7 8 4 Example Synchronizing Tasks A task is synchronized with an ISR A second task simulates the interrupt The service task task waits for a
213. ues and system partition blocks See also private resource Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 171 System task The MQX task that is really simply a task descriptor See System task descriptor System task descriptor MQX uses System task descriptor to store initialization errors Subsequently MQX uses the task descriptor so that it can own system resources system timer See periodic timer device I target Hardware on which the application runs It is defined by the BSP See also host task A body of C code usually an infinite loop that performs some function There are application tasks and MQX tasks An application task is defined by its task template There can be multiple instances of a task Unless it would create confusion the instance of the task is simply called the task See also autostart task task descriptor Context information for an instance of a task task error code Each task has a task error code associated to it A task error code can be MQX OK or MQX EOK for mutexes or a code that indicates that an error has occurred task ID Application unique MQX generated number that identifies an instance of a task task template Application defined template that MQX uses to create instances of a task The application either defines the template in the task template list of an MQX initialization structure or supplies the template at run time task templa
214. uld be dangerous to your files or your hardware CAUTION If you modify MQX data types some MQX Host Tools from MQX Embedded might not operate properly Freescale MQX Real Time Operating System User Guide Rev 3 14 Freescale Semiconductor Chapter 2 MQX at a Glance 2 1 Organization of MQX MQX consists of core non optional components and optional components In the case of core components only those functions that MQX or the application calls are included in the image To match its requirements an application extends and configures core components by adding optional components The following diagram shows core components in the center with optional components around the outside interrupts name services partitions veight memory N A messages time timers p utilities initialization S vents lightweight ightwelghttimers task errors uite eu semaphores watchdogs lightweight i semaphores automatic t sk E IPCs task d RR amp FIFO managemen scheduling scheduling H exception handling kernel logs log an oe Figure 2 1 en The following table summarizes core and optional components each of which is briefly described in subsequent sections of the chapter Table 2 1 Core and Optional Components Component Includes Type Initialization Initialization and automatic task creation Core Task mana
215. ult an application might consist of tasks that use any combination of FIFO or round robin scheduling Freescale MQX Real Time Operating System User Guide Rev 3 34 Freescale Semiconductor Using MQX 3 5 1 FIFO Scheduling FIFO is the default scheduling policy With FIFO scheduling the task that runs becomes active next is the highest priority task that has been waiting the longest time The active task runs until any of the following occurs The active task voluntarily relinquishes the processor because it calls a blocking MQX function Aninterrupt occurs that has higher priority than the active task Atask that has priority higher than the active task becomes ready You can change the priority of a task with task set priority 3 5 2 Round Robin Scheduling Round robin scheduling is similar to FIFO scheduling but with the additional constraint that each round robin task has a maximum amount of time the time slice during which it can be active A task uses round robin scheduling only if the MQX TIME SLICE TASK attribute is set in its task template The task s time slice is determined by the value of the template s DEFAULT TIME SLICE However if the value is zero the task s time slice is the default time slice for the processor Initially the default time slice for the processor is ten times the interval of the periodic timer interrupt Since the interval on most BSPs is five milliseconds the initial default ti
216. umber queue number Processor unique application defined number that identifies a message queue See also queue ID R ready queue There is a linked list of ready queues one ready queue for each task priority Each ready queue holds tasks that have the specific priority and that are in the ready state To distinguish it from other ready queues the ready queue that a task is in is referred to as the task s ready queue region See memory region remote Pertaining to a processor other than the local processor round robin interval See time slice round robin scheduling Guarantees that a task is not active for longer than the duration of the task s time slice With round robin scheduling the active task is the highest priority task that has been ready the longest without consuming its time slice Sometimes called time slice scheduling See also explicit scheduling and FIFO scheduling round robin task A task that uses round robin scheduling Freescale MQX Real Time Operating System User Guide Rev 3 170 Freescale Semiconductor RR Round robin See round robin scheduling RTOS Real time operating system run When a task is the active task it runs on the processor S schedule verb MQX finds the next ready task and makes it the active task scheduling See explicit scheduling FIFO scheduling and round robin scheduling semaphore A semaphore lets tasks synchronize access to shared resources Th
217. ures and constants which are defined in og h Iwlog h and klog h _klog_control Control kernel logging _klog_create Creates kernel log _klog_create_at Creates kernel log at a specific location klog disable logging task Disables kernel logging for the specified task klog enable logging task Enables kernel logging for the specified task klog display Displays an entry in kernel log 3 11 3 1 Using Kernel Log To use kernel log an application follows these general steps 1 Optionally create the lightweight log component as described on page 118 2 Create kernel log with klog create This is similar to creating a lightweight log which is described on page 118 You can also create kernel log at a specific location with klog create at 3 Setup control for logging by calling klog control and specifying any combination of bit flags as described in the following table Table 3 32 Select flags for MQX component Select for These functions are logged Errors For example mqx exit task set error mqx fatal error Events Most from the event family Interrupts Certain ones from the int family LWSems The Iwsem family Memory Certain ones from the mem family Messages Certain ones from the msg msgpool and msgq families Mutexes Certain ones from the mutatr and mutex families Names The name family Partitions Certain ones from the partition family Semaphores
218. ut queue of the IPC to use in order to reach the destination processor MQX then directs the message to that output queue The output function runs and transmits the message on the IPC When an IPC receives a message the input function runs The input function assembles the message and calls msgq send The input function needs not to determine whether the input message is for the local processor If the message is not for the local processor MQX routes the message to the destination processor 3 8 1 1 Example Four Processor Application The diagram shows a simple four processor application The numbers in the table are arbitrary but processor unique output queue numbers Each processor has two IPCs There are two possible routes between each processor for example processor one has one IPC to processor two and one to processor four The routing table supports one route so the best route should be selected The table illustrates one possibility for each of the processor s routing tables Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 83 Using MQX 3 8 1 1 1 Routing Table for Processor 1 Destination processor Source processor 1 2 3 4 1 10 10 11 2 21 20 20 3 31 31 30 4 40 41 41 As in the table when a task on processor one sends a message to a message queue on processor three MQX sends the message from processor one to proc
219. ut the ISR or task that was running before the exception occurred CAUTION If the MQX exception ISR determines that the interrupt stack contains incorrect information it calls mqx fatal error with error code MQX CORRUPT INTERRUPT STACK 3 10 6 Handling ISR Exceptions An application can install an ISR exception handler for each ISR If an exception occurs while the ISR is running MQX calls the handler and terminates the ISR If the application has not installed an exception handler MQX simply terminates the ISR When MQX calls the exception handler it passes current ISR number e data pointer for the ISR exception number address on the stack of the exception frame Table 3 27 Summary Handling ISR Exceptions int get exception handler Gets a pointer to the current exception handler for the ISR int set exception handler Sets the address of the current ISR exception handler for the interrupt 3 10 7 Handling Task Exceptions A task can install a task exception handler which MQX calls if the task causes an exception that is not supported Table 3 28 Summary Handling Task Exceptions task get exception handler Gets the task exception handler task set exception handler Sets the task exception handler Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor Using MQX 3 10 8 Example Installing an ISR Install an ISR to intercept the ke
220. utexes lightweight semaphores semaphores messages and queues P page See MMU page and physical page page number See MMU page number page offset See MMU page offset parent See creator partition Consists of partition blocks which are fixed size pieces of memory There are dynamic partitions and static partitions partition block Fixed size block from a partition Partition blocks are useful when an application needs to allocate and free same size pieces of memory quickly There are private partition blocks and system partition blocks See also memory block pending A message is pending if it is in a message queue that is if it has not been received by a task periodic timer device The hardware device that generates timer interrupts at a specific interval It is defined by the BSP MQX uses the interrupts to maintain time Sometimes called the system clock Freescale MQX Real Time Operating System User Guide Rev 3 168 Freescale Semiconductor Do not confuse the periodic timer device with the periodic timers that tasks can start by calling functions from the timer start periodic at family or timer start periodic every family physical address An address that is seen by the MMU that is an address that is loaded into the memory address register See also logical address and virtual address POSIX Portable Operating System Interface produced by IEEE and standardized by ANSI and ISO MQX conforms to
221. velop a new BSP 1 Select a baseline BSP to modify Clone selected BSP and PSP projects configuration and source code Prepare BSP specific Debugger Configuration Modify BSP specific include files Modify startup code Modify source code mc xc veio po Create default initialization for I O device drivers 5 3 Selecting a Baseline BSP It is usually easiest to select an existing baseline BSP and modify the baseline to suit your hardware In most cases select a baseline BSP that uses the same or similar processor 1 Create a new BSP source directory for example source bsp my52259board 2 Goto the baseline directory for example source bsp m52259evb 3 Copy the contents of the baseline directory to the new directory 4 In the new directory rename the old board specific names lt board gt to the name of the new BSP 5 Create additional files and directories related to the new BSP New BSP configuration directory config bsp my52259board New build output directory lib my52259board Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 149 Developing a New BSP 6 Clone BSP and PSP build projects as described in 4 6 2 Cloning Existing Configuration Do not forget to change the project settings in each build target This is namely remove the old board specific source code files from the project lt board gt and add the newly created files redirect t
222. wait_ticks Waits for all or any of the specified event bits in a lightweight event group for a specified number of ticks _lwevent_wait_until Waits for all or any of the specified event bits in a lightweight event group until a specified tick time 1 Lightweight events use certain structures and constants which are defined in Iwevent h Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 51 Using MQX 3 7 2 1 Creating a Lightweight Event Group To create a lightweight event group an application declares a variable of type LWEVENT_STRUCT and initializes it by calling Iwevent create with a pointer to the variable and a flag indicating whether the event group has autoclearing event bits 3 7 2 2 Waiting for Event Bits A task waits a pattern of event bits a mask in a lightweight event group with one of the Iwevent wait functions If the waiting condition is not met the function waits for a specified time to expire 3 7 2 3 Setting Event Bits A task sets a pattern of event bits a mask in a lightweight event group with _Iwevent_set If tasks are waiting for the appropriate bits MOX makes them ready If the event group has autoclearing event bits MQX makes ready only the first task that is waiting 3 7 2 4 Clearing Event Bits A task can clear a pattern of event bits a mask in a lightweight event group with Iwevent clear However if the lightweight event group is crea
223. y does not overlap code or data space that your application uses 3 6 3 3 Allocating and Freeing Partition Blocks An application can allocate two types of partition blocks from either a dynamic or static partition Type of partition Allocated by calling Is a resource of Can be freed block by Private partition alloc Taskthat allocated Owner only it System partition alloc system No one task Any task If the task is terminated its private partition blocks are freed Freescale MQX Real Time Operating System User Guide Rev 3 Freescale Semiconductor 39 Using MQX _ dynamic partition rg Partition block fixed size memory core A memory static partition data code 3 6 3 4 Destroying a Dynamic Partition If all the partition blocks in a dynamic partition are freed any task can destroy the partition by calling partition destroy You cannot destroy a static partition 3 6 3 5 Example Two Partitions The following diagram shows one static partition and one dynamic partition Figure 3 2 Example Two Partion Table 3 5 Summary Managing Memory with Fixed Sixe Blocks Partitions partition alloc Allocates a private partition block from a partition partition alloc system Allocates a system partition block from a partition partition alloc system
224. ystem User Guide Rev 3 124 Freescale Semiconductor Using MQX 3 11 4 Stack Usage Utilities MQX offers core utilities that let you examine and refine the size of the interrupt stack and the size of each task s stack Table 3 33 Summary Stack Usage Utilities To use these utilities you must have configured MQX with MQX MONITOR STACK For more information see Section 3 14 1 MQX Compile Time Configuration Options The complete procedure for recompiling MQX is described in Section 4 5 Rebuilding Freescale MQX RTOS _klog_get_interrupt_stack_ Gets the interrupt stack boundary and the total usage amount of stack used klog_get_task_stack_usage Gets the stack size and the total amount of the stack used for a specific task klog_show_stack_usage Calculates and displays the amount of stack used by each task and the interrupt stack 3 12 Utilities Utilities include queues name component e run time testing e additional utilities 3 12 14 Queues The queue component lets you manage doubly linked lists of elements FREESCALE MQX To optimize code and data memory requirements on some target platforms the Queue component is not compiled in the MQX kernel by default To test this feature you need to enable it first in the MQX user configuration file and recompile the MQX PSP BSP and other core components Please see Section 4 5 Rebuilding Freescale MQX RTOS for more details
225. ze Blocks However they have less overhead in data and code If you change an MQX compile time configuration option MQX uses the lightweight memory component when it allocates memory For more information see page 132 Table 3 4 Summary Managing Lightweight Memory with Variable Size Blocks Lightweight memory uses certain structures and constants which are defined in Iwmem h Iwmem alloc Allocates a private lightweight memory block from the default lightweight memory pool Iwmem alloc from Allocates a private lightweight memory block from the specified lightweight memory pool Iwmem alloc zero Allocates a zero filled private lightweight memory block from the default lightweight memory pool Iwmem alloc zero from Allocates a zero filled private lightweight memory block from the specified lightweight memory pool Iwmem alloc system Allocates a system lightweight memory block from the default lightweight memory pool Iwmem alloc system from Allocates a system lightweight memory block from the specified lightweight memory pool Iwmem alloc system zero Allocates a zero filled system lightweight memory block from the default lightweight memory pool Iwmem alloc system zero Allocates a zero filled system memory block from from the specified lightweight memory pool Iwmem create pool Creates a lightweight memory pool Freescale MQX Real Time Operating System User Guide Rev 3
226. zero Allocates a zero filled system partition block from a partition partition alloc zero Allocates a zero filled private partition block from a partition partition calculate blocks Calculates the number of partition blocks from the partition block size and the partition size for static partitions partition calculate size Calculates the size of a partition from the partition block size and the number of blocks partition create Creates a partition from the default memory pool dynamic partition partition create at Creates a partition at a specific location outside the default memory pool static partition partition create component Creates the partition component partition destroy Destroys a dynamic partition that has no allocated partition blocks Freescale MQX Real Time Operating System User Guide Rev 3 40 Freescale Semiconductor Table 3 5 Summary Managing Memory with Fixed Sixe Blocks Partitions continued _partition_extend Adds memory to a static partition the added memory is divided into partition blocks that are the same size as other blocks in the partition partition free Returns a partition block to a partition partition get block size Gets the size of partition blocks in a partition partition get free blocks Gets the number of free partition blocks in a partition partition get max used blocks Gets the number of allocated partiti

Download Pdf Manuals

image

Related Search

Related Contents

Nuna Pipa  Operação Symmetra® PX  Ask Proxima DP6800 User's Manual  Network Setup Guide - Supercircuits Inc.  Public Mode    Comment utiliser colle neoprene.indd  Clicca qui per scaricare il manuale dell`inserto a legna  第20期 第2四半期 平成22年9月30日 PDF 形式  à Perpignan, la MGET célèbre les 10 ans de l`IRPS  

Copyright © All rights reserved.
Failed to retrieve file